blob: 91e14953fd422baeb50922ad4512c127dd170f8e [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define TRACE_TAG TRACE_SYSDEPS
18
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080028#include "adb.h"
29
30extern void fatal(const char *fmt, ...);
31
Elliott Hughes6a096932015-04-16 16:47:02 -070032/* forward declarations */
33
34typedef const struct FHClassRec_* FHClass;
35typedef struct FHRec_* FH;
36typedef struct EventHookRec_* EventHook;
37
38typedef struct FHClassRec_ {
39 void (*_fh_init)(FH);
40 int (*_fh_close)(FH);
41 int (*_fh_lseek)(FH, int, int);
42 int (*_fh_read)(FH, void*, int);
43 int (*_fh_write)(FH, const void*, int);
44 void (*_fh_hook)(FH, int, EventHook);
45} FHClassRec;
46
47static void _fh_file_init(FH);
48static int _fh_file_close(FH);
49static int _fh_file_lseek(FH, int, int);
50static int _fh_file_read(FH, void*, int);
51static int _fh_file_write(FH, const void*, int);
52static void _fh_file_hook(FH, int, EventHook);
53
54static const FHClassRec _fh_file_class = {
55 _fh_file_init,
56 _fh_file_close,
57 _fh_file_lseek,
58 _fh_file_read,
59 _fh_file_write,
60 _fh_file_hook
61};
62
63static void _fh_socket_init(FH);
64static int _fh_socket_close(FH);
65static int _fh_socket_lseek(FH, int, int);
66static int _fh_socket_read(FH, void*, int);
67static int _fh_socket_write(FH, const void*, int);
68static void _fh_socket_hook(FH, int, EventHook);
69
70static const FHClassRec _fh_socket_class = {
71 _fh_socket_init,
72 _fh_socket_close,
73 _fh_socket_lseek,
74 _fh_socket_read,
75 _fh_socket_write,
76 _fh_socket_hook
77};
78
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080079#define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
80
81/**************************************************************************/
82/**************************************************************************/
83/***** *****/
84/***** replaces libs/cutils/load_file.c *****/
85/***** *****/
86/**************************************************************************/
87/**************************************************************************/
88
89void *load_file(const char *fn, unsigned *_sz)
90{
91 HANDLE file;
92 char *data;
93 DWORD file_size;
94
95 file = CreateFile( fn,
96 GENERIC_READ,
97 FILE_SHARE_READ,
98 NULL,
99 OPEN_EXISTING,
100 0,
101 NULL );
102
103 if (file == INVALID_HANDLE_VALUE)
104 return NULL;
105
106 file_size = GetFileSize( file, NULL );
107 data = NULL;
108
109 if (file_size > 0) {
110 data = (char*) malloc( file_size + 1 );
111 if (data == NULL) {
112 D("load_file: could not allocate %ld bytes\n", file_size );
113 file_size = 0;
114 } else {
115 DWORD out_bytes;
116
117 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
118 out_bytes != file_size )
119 {
120 D("load_file: could not read %ld bytes from '%s'\n", file_size, fn);
121 free(data);
122 data = NULL;
123 file_size = 0;
124 }
125 }
126 }
127 CloseHandle( file );
128
129 *_sz = (unsigned) file_size;
130 return data;
131}
132
133/**************************************************************************/
134/**************************************************************************/
135/***** *****/
136/***** common file descriptor handling *****/
137/***** *****/
138/**************************************************************************/
139/**************************************************************************/
140
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800141/* used to emulate unix-domain socket pairs */
142typedef struct SocketPairRec_* SocketPair;
143
144typedef struct FHRec_
145{
146 FHClass clazz;
147 int used;
148 int eof;
149 union {
150 HANDLE handle;
151 SOCKET socket;
152 SocketPair pair;
153 } u;
154
155 HANDLE event;
156 int mask;
157
158 char name[32];
159
160} FHRec;
161
162#define fh_handle u.handle
163#define fh_socket u.socket
164#define fh_pair u.pair
165
166#define WIN32_FH_BASE 100
167
168#define WIN32_MAX_FHS 128
169
170static adb_mutex_t _win32_lock;
171static FHRec _win32_fhs[ WIN32_MAX_FHS ];
172static int _win32_fh_count;
173
174static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700175_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800176{
177 FH f;
178
179 fd -= WIN32_FH_BASE;
180
181 if (fd < 0 || fd >= _win32_fh_count) {
Spencer Low3a2421b2015-05-22 20:09:06 -0700182 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
183 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800184 errno = EBADF;
185 return NULL;
186 }
187
188 f = &_win32_fhs[fd];
189
190 if (f->used == 0) {
Spencer Low3a2421b2015-05-22 20:09:06 -0700191 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
192 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800193 errno = EBADF;
194 return NULL;
195 }
196
197 return f;
198}
199
200
201static int
202_fh_to_int( FH f )
203{
204 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
205 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
206
207 return -1;
208}
209
210static FH
211_fh_alloc( FHClass clazz )
212{
213 int nn;
214 FH f = NULL;
215
216 adb_mutex_lock( &_win32_lock );
217
218 if (_win32_fh_count < WIN32_MAX_FHS) {
219 f = &_win32_fhs[ _win32_fh_count++ ];
220 goto Exit;
221 }
222
223 for (nn = 0; nn < WIN32_MAX_FHS; nn++) {
224 if ( _win32_fhs[nn].clazz == NULL) {
225 f = &_win32_fhs[nn];
226 goto Exit;
227 }
228 }
229 D( "_fh_alloc: no more free file descriptors\n" );
230Exit:
231 if (f) {
232 f->clazz = clazz;
233 f->used = 1;
234 f->eof = 0;
235 clazz->_fh_init(f);
236 }
237 adb_mutex_unlock( &_win32_lock );
238 return f;
239}
240
241
242static int
243_fh_close( FH f )
244{
245 if ( f->used ) {
246 f->clazz->_fh_close( f );
247 f->used = 0;
248 f->eof = 0;
249 f->clazz = NULL;
250 }
251 return 0;
252}
253
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800254/**************************************************************************/
255/**************************************************************************/
256/***** *****/
257/***** file-based descriptor handling *****/
258/***** *****/
259/**************************************************************************/
260/**************************************************************************/
261
Elliott Hughes6a096932015-04-16 16:47:02 -0700262static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800263 f->fh_handle = INVALID_HANDLE_VALUE;
264}
265
Elliott Hughes6a096932015-04-16 16:47:02 -0700266static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800267 CloseHandle( f->fh_handle );
268 f->fh_handle = INVALID_HANDLE_VALUE;
269 return 0;
270}
271
Elliott Hughes6a096932015-04-16 16:47:02 -0700272static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800273 DWORD read_bytes;
274
275 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
276 D( "adb_read: could not read %d bytes from %s\n", len, f->name );
277 errno = EIO;
278 return -1;
279 } else if (read_bytes < (DWORD)len) {
280 f->eof = 1;
281 }
282 return (int)read_bytes;
283}
284
Elliott Hughes6a096932015-04-16 16:47:02 -0700285static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800286 DWORD wrote_bytes;
287
288 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
289 D( "adb_file_write: could not write %d bytes from %s\n", len, f->name );
290 errno = EIO;
291 return -1;
292 } else if (wrote_bytes < (DWORD)len) {
293 f->eof = 1;
294 }
295 return (int)wrote_bytes;
296}
297
Elliott Hughes6a096932015-04-16 16:47:02 -0700298static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800299 DWORD method;
300 DWORD result;
301
302 switch (origin)
303 {
304 case SEEK_SET: method = FILE_BEGIN; break;
305 case SEEK_CUR: method = FILE_CURRENT; break;
306 case SEEK_END: method = FILE_END; break;
307 default:
308 errno = EINVAL;
309 return -1;
310 }
311
312 result = SetFilePointer( f->fh_handle, pos, NULL, method );
313 if (result == INVALID_SET_FILE_POINTER) {
314 errno = EIO;
315 return -1;
316 } else {
317 f->eof = 0;
318 }
319 return (int)result;
320}
321
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800322
323/**************************************************************************/
324/**************************************************************************/
325/***** *****/
326/***** file-based descriptor handling *****/
327/***** *****/
328/**************************************************************************/
329/**************************************************************************/
330
331int adb_open(const char* path, int options)
332{
333 FH f;
334
335 DWORD desiredAccess = 0;
336 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
337
338 switch (options) {
339 case O_RDONLY:
340 desiredAccess = GENERIC_READ;
341 break;
342 case O_WRONLY:
343 desiredAccess = GENERIC_WRITE;
344 break;
345 case O_RDWR:
346 desiredAccess = GENERIC_READ | GENERIC_WRITE;
347 break;
348 default:
349 D("adb_open: invalid options (0x%0x)\n", options);
350 errno = EINVAL;
351 return -1;
352 }
353
354 f = _fh_alloc( &_fh_file_class );
355 if ( !f ) {
356 errno = ENOMEM;
357 return -1;
358 }
359
360 f->fh_handle = CreateFile( path, desiredAccess, shareMode, NULL, OPEN_EXISTING,
361 0, NULL );
362
363 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700364 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800365 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700366 D( "adb_open: could not open '%s': ", path );
367 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800368 case ERROR_FILE_NOT_FOUND:
369 D( "file not found\n" );
370 errno = ENOENT;
371 return -1;
372
373 case ERROR_PATH_NOT_FOUND:
374 D( "path not found\n" );
375 errno = ENOTDIR;
376 return -1;
377
378 default:
Spencer Low5c761bd2015-07-21 02:06:26 -0700379 D( "unknown error: %ld\n", err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800380 errno = ENOENT;
381 return -1;
382 }
383 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800384
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800385 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
386 D( "adb_open: '%s' => fd %d\n", path, _fh_to_int(f) );
387 return _fh_to_int(f);
388}
389
390/* ignore mode on Win32 */
391int adb_creat(const char* path, int mode)
392{
393 FH f;
394
395 f = _fh_alloc( &_fh_file_class );
396 if ( !f ) {
397 errno = ENOMEM;
398 return -1;
399 }
400
401 f->fh_handle = CreateFile( path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
402 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
403 NULL );
404
405 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700406 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800407 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700408 D( "adb_creat: could not open '%s': ", path );
409 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800410 case ERROR_FILE_NOT_FOUND:
411 D( "file not found\n" );
412 errno = ENOENT;
413 return -1;
414
415 case ERROR_PATH_NOT_FOUND:
416 D( "path not found\n" );
417 errno = ENOTDIR;
418 return -1;
419
420 default:
Spencer Low5c761bd2015-07-21 02:06:26 -0700421 D( "unknown error: %ld\n", err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800422 errno = ENOENT;
423 return -1;
424 }
425 }
426 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
427 D( "adb_creat: '%s' => fd %d\n", path, _fh_to_int(f) );
428 return _fh_to_int(f);
429}
430
431
432int adb_read(int fd, void* buf, int len)
433{
Spencer Low3a2421b2015-05-22 20:09:06 -0700434 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800435
436 if (f == NULL) {
437 return -1;
438 }
439
440 return f->clazz->_fh_read( f, buf, len );
441}
442
443
444int adb_write(int fd, const void* buf, int len)
445{
Spencer Low3a2421b2015-05-22 20:09:06 -0700446 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800447
448 if (f == NULL) {
449 return -1;
450 }
451
452 return f->clazz->_fh_write(f, buf, len);
453}
454
455
456int adb_lseek(int fd, int pos, int where)
457{
Spencer Low3a2421b2015-05-22 20:09:06 -0700458 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800459
460 if (!f) {
461 return -1;
462 }
463
464 return f->clazz->_fh_lseek(f, pos, where);
465}
466
467
Mike Lockwood81ffe172009-10-11 23:04:18 -0400468int adb_shutdown(int fd)
469{
Spencer Low3a2421b2015-05-22 20:09:06 -0700470 FH f = _fh_from_int(fd, __func__);
Mike Lockwood81ffe172009-10-11 23:04:18 -0400471
Spencer Low31aafa62015-01-25 14:40:16 -0800472 if (!f || f->clazz != &_fh_socket_class) {
473 D("adb_shutdown: invalid fd %d\n", fd);
Mike Lockwood81ffe172009-10-11 23:04:18 -0400474 return -1;
475 }
476
477 D( "adb_shutdown: %s\n", f->name);
478 shutdown( f->fh_socket, SD_BOTH );
479 return 0;
480}
481
482
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483int adb_close(int fd)
484{
Spencer Low3a2421b2015-05-22 20:09:06 -0700485 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800486
487 if (!f) {
488 return -1;
489 }
490
491 D( "adb_close: %s\n", f->name);
492 _fh_close(f);
493 return 0;
494}
495
496/**************************************************************************/
497/**************************************************************************/
498/***** *****/
499/***** socket-based file descriptors *****/
500/***** *****/
501/**************************************************************************/
502/**************************************************************************/
503
Spencer Low31aafa62015-01-25 14:40:16 -0800504#undef setsockopt
505
Elliott Hughes6a096932015-04-16 16:47:02 -0700506static void _socket_set_errno( void ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800507 switch (WSAGetLastError()) {
508 case 0: errno = 0; break;
509 case WSAEWOULDBLOCK: errno = EAGAIN; break;
510 case WSAEINTR: errno = EINTR; break;
511 default:
512 D( "_socket_set_errno: unhandled value %d\n", WSAGetLastError() );
513 errno = EINVAL;
514 }
515}
516
Elliott Hughes6a096932015-04-16 16:47:02 -0700517static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800518 f->fh_socket = INVALID_SOCKET;
519 f->event = WSACreateEvent();
520 f->mask = 0;
521}
522
Elliott Hughes6a096932015-04-16 16:47:02 -0700523static int _fh_socket_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800524 /* gently tell any peer that we're closing the socket */
525 shutdown( f->fh_socket, SD_BOTH );
526 closesocket( f->fh_socket );
527 f->fh_socket = INVALID_SOCKET;
528 CloseHandle( f->event );
529 f->mask = 0;
530 return 0;
531}
532
Elliott Hughes6a096932015-04-16 16:47:02 -0700533static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800534 errno = EPIPE;
535 return -1;
536}
537
Elliott Hughes6a096932015-04-16 16:47:02 -0700538static int _fh_socket_read(FH f, void* buf, int len) {
539 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800540 if (result == SOCKET_ERROR) {
541 _socket_set_errno();
542 result = -1;
543 }
544 return result;
545}
546
Elliott Hughes6a096932015-04-16 16:47:02 -0700547static int _fh_socket_write(FH f, const void* buf, int len) {
548 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800549 if (result == SOCKET_ERROR) {
550 _socket_set_errno();
551 result = -1;
552 }
553 return result;
554}
555
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800556/**************************************************************************/
557/**************************************************************************/
558/***** *****/
559/***** replacement for libs/cutils/socket_xxxx.c *****/
560/***** *****/
561/**************************************************************************/
562/**************************************************************************/
563
564#include <winsock2.h>
565
566static int _winsock_init;
567
568static void
569_cleanup_winsock( void )
570{
571 WSACleanup();
572}
573
574static void
575_init_winsock( void )
576{
577 if (!_winsock_init) {
578 WSADATA wsaData;
579 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
580 if (rc != 0) {
581 fatal( "adb: could not initialize Winsock\n" );
582 }
583 atexit( _cleanup_winsock );
584 _winsock_init = 1;
585 }
586}
587
588int socket_loopback_client(int port, int type)
589{
590 FH f = _fh_alloc( &_fh_socket_class );
591 struct sockaddr_in addr;
592 SOCKET s;
593
594 if (!f)
595 return -1;
596
597 if (!_winsock_init)
598 _init_winsock();
599
600 memset(&addr, 0, sizeof(addr));
601 addr.sin_family = AF_INET;
602 addr.sin_port = htons(port);
603 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
604
605 s = socket(AF_INET, type, 0);
606 if(s == INVALID_SOCKET) {
607 D("socket_loopback_client: could not create socket\n" );
608 _fh_close(f);
609 return -1;
610 }
611
612 f->fh_socket = s;
613 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
614 D("socket_loopback_client: could not connect to %s:%d\n", type != SOCK_STREAM ? "udp" : "tcp", port );
615 _fh_close(f);
616 return -1;
617 }
618 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
619 D( "socket_loopback_client: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
620 return _fh_to_int(f);
621}
622
623#define LISTEN_BACKLOG 4
624
625int socket_loopback_server(int port, int type)
626{
627 FH f = _fh_alloc( &_fh_socket_class );
628 struct sockaddr_in addr;
629 SOCKET s;
630 int n;
631
632 if (!f) {
633 return -1;
634 }
635
636 if (!_winsock_init)
637 _init_winsock();
638
639 memset(&addr, 0, sizeof(addr));
640 addr.sin_family = AF_INET;
641 addr.sin_port = htons(port);
642 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
643
644 s = socket(AF_INET, type, 0);
645 if(s == INVALID_SOCKET) return -1;
646
647 f->fh_socket = s;
648
649 n = 1;
650 setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n));
651
652 if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
653 _fh_close(f);
654 return -1;
655 }
656 if (type == SOCK_STREAM) {
657 int ret;
658
659 ret = listen(s, LISTEN_BACKLOG);
660 if (ret < 0) {
661 _fh_close(f);
662 return -1;
663 }
664 }
665 snprintf( f->name, sizeof(f->name), "%d(lo-server:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
666 D( "socket_loopback_server: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
667 return _fh_to_int(f);
668}
669
670
Elliott Hughes43df1092015-07-23 17:12:58 -0700671int socket_network_client_timeout(const char *host, int port, int type, int timeout,
672 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800673 FH f = _fh_alloc( &_fh_socket_class );
Elliott Hughes43df1092015-07-23 17:12:58 -0700674 if (!f) return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800675
Elliott Hughes43df1092015-07-23 17:12:58 -0700676 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800677
Elliott Hughes43df1092015-07-23 17:12:58 -0700678 hostent* hp = gethostbyname(host);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800679 if(hp == 0) {
680 _fh_close(f);
681 return -1;
682 }
683
Elliott Hughes43df1092015-07-23 17:12:58 -0700684 sockaddr_in addr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800685 memset(&addr, 0, sizeof(addr));
686 addr.sin_family = hp->h_addrtype;
687 addr.sin_port = htons(port);
688 memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
689
Elliott Hughes43df1092015-07-23 17:12:58 -0700690 SOCKET s = socket(hp->h_addrtype, type, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800691 if(s == INVALID_SOCKET) {
692 _fh_close(f);
693 return -1;
694 }
695 f->fh_socket = s;
696
Elliott Hughes43df1092015-07-23 17:12:58 -0700697 // TODO: implement timeouts for Windows.
698
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800699 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
700 _fh_close(f);
701 return -1;
702 }
703
704 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
Elliott Hughes43df1092015-07-23 17:12:58 -0700705 D( "socket_network_client_timeout: host '%s' port %d type %s => fd %d\n", host, port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800706 return _fh_to_int(f);
707}
708
709
710int socket_inaddr_any_server(int port, int type)
711{
712 FH f = _fh_alloc( &_fh_socket_class );
713 struct sockaddr_in addr;
714 SOCKET s;
715 int n;
716
717 if (!f)
718 return -1;
719
720 if (!_winsock_init)
721 _init_winsock();
722
723 memset(&addr, 0, sizeof(addr));
724 addr.sin_family = AF_INET;
725 addr.sin_port = htons(port);
726 addr.sin_addr.s_addr = htonl(INADDR_ANY);
727
728 s = socket(AF_INET, type, 0);
729 if(s == INVALID_SOCKET) {
730 _fh_close(f);
731 return -1;
732 }
733
734 f->fh_socket = s;
735 n = 1;
736 setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n));
737
738 if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
739 _fh_close(f);
740 return -1;
741 }
742
743 if (type == SOCK_STREAM) {
744 int ret;
745
746 ret = listen(s, LISTEN_BACKLOG);
747 if (ret < 0) {
748 _fh_close(f);
749 return -1;
750 }
751 }
752 snprintf( f->name, sizeof(f->name), "%d(any-server:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
753 D( "socket_inaddr_server: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
754 return _fh_to_int(f);
755}
756
757#undef accept
758int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
759{
Spencer Low3a2421b2015-05-22 20:09:06 -0700760 FH serverfh = _fh_from_int(serverfd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800761 FH fh;
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200762
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800763 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
764 D( "adb_socket_accept: invalid fd %d\n", serverfd );
765 return -1;
766 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200767
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800768 fh = _fh_alloc( &_fh_socket_class );
769 if (!fh) {
770 D( "adb_socket_accept: not enough memory to allocate accepted socket descriptor\n" );
771 return -1;
772 }
773
774 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
775 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700776 const DWORD err = WSAGetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800777 _fh_close( fh );
Spencer Low5c761bd2015-07-21 02:06:26 -0700778 D( "adb_socket_accept: accept on fd %d return error %ld\n", serverfd, err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800779 return -1;
780 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200781
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800782 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", _fh_to_int(fh), serverfh->name );
783 D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, _fh_to_int(fh) );
784 return _fh_to_int(fh);
785}
786
787
Spencer Low31aafa62015-01-25 14:40:16 -0800788int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800789{
Spencer Low3a2421b2015-05-22 20:09:06 -0700790 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200791
Spencer Low31aafa62015-01-25 14:40:16 -0800792 if ( !fh || fh->clazz != &_fh_socket_class ) {
793 D("adb_setsockopt: invalid fd %d\n", fd);
794 return -1;
795 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800796
Elliott Hughes6a096932015-04-16 16:47:02 -0700797 return setsockopt( fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800798}
799
800/**************************************************************************/
801/**************************************************************************/
802/***** *****/
803/***** emulated socketpairs *****/
804/***** *****/
805/**************************************************************************/
806/**************************************************************************/
807
808/* we implement socketpairs directly in use space for the following reasons:
809 * - it avoids copying data from/to the Nt kernel
810 * - it allows us to implement fdevent hooks easily and cheaply, something
811 * that is not possible with standard Win32 pipes !!
812 *
813 * basically, we use two circular buffers, each one corresponding to a given
814 * direction.
815 *
816 * each buffer is implemented as two regions:
817 *
818 * region A which is (a_start,a_end)
819 * region B which is (0, b_end) with b_end <= a_start
820 *
821 * an empty buffer has: a_start = a_end = b_end = 0
822 *
823 * a_start is the pointer where we start reading data
824 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
825 * then you start writing at b_end
826 *
827 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
828 *
829 * there is room when b_end < a_start || a_end < BUFER_SIZE
830 *
831 * when reading, a_start is incremented, it a_start meets a_end, then
832 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
833 */
834
835#define BIP_BUFFER_SIZE 4096
836
837#if 0
838#include <stdio.h>
839# define BIPD(x) D x
840# define BIPDUMP bip_dump_hex
841
842static void bip_dump_hex( const unsigned char* ptr, size_t len )
843{
844 int nn, len2 = len;
845
846 if (len2 > 8) len2 = 8;
847
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800848 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800849 printf("%02x", ptr[nn]);
850 printf(" ");
851
852 for (nn = 0; nn < len2; nn++) {
853 int c = ptr[nn];
854 if (c < 32 || c > 127)
855 c = '.';
856 printf("%c", c);
857 }
858 printf("\n");
859 fflush(stdout);
860}
861
862#else
863# define BIPD(x) do {} while (0)
864# define BIPDUMP(p,l) BIPD(p)
865#endif
866
867typedef struct BipBufferRec_
868{
869 int a_start;
870 int a_end;
871 int b_end;
872 int fdin;
873 int fdout;
874 int closed;
875 int can_write; /* boolean */
876 HANDLE evt_write; /* event signaled when one can write to a buffer */
877 int can_read; /* boolean */
878 HANDLE evt_read; /* event signaled when one can read from a buffer */
879 CRITICAL_SECTION lock;
880 unsigned char buff[ BIP_BUFFER_SIZE ];
881
882} BipBufferRec, *BipBuffer;
883
884static void
885bip_buffer_init( BipBuffer buffer )
886{
887 D( "bit_buffer_init %p\n", buffer );
888 buffer->a_start = 0;
889 buffer->a_end = 0;
890 buffer->b_end = 0;
891 buffer->can_write = 1;
892 buffer->can_read = 0;
893 buffer->fdin = 0;
894 buffer->fdout = 0;
895 buffer->closed = 0;
896 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
897 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
898 InitializeCriticalSection( &buffer->lock );
899}
900
901static void
902bip_buffer_close( BipBuffer bip )
903{
904 bip->closed = 1;
905
906 if (!bip->can_read) {
907 SetEvent( bip->evt_read );
908 }
909 if (!bip->can_write) {
910 SetEvent( bip->evt_write );
911 }
912}
913
914static void
915bip_buffer_done( BipBuffer bip )
916{
917 BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
918 CloseHandle( bip->evt_read );
919 CloseHandle( bip->evt_write );
920 DeleteCriticalSection( &bip->lock );
921}
922
923static int
924bip_buffer_write( BipBuffer bip, const void* src, int len )
925{
926 int avail, count = 0;
927
928 if (len <= 0)
929 return 0;
930
931 BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
932 BIPDUMP( src, len );
933
934 EnterCriticalSection( &bip->lock );
935
936 while (!bip->can_write) {
937 int ret;
938 LeaveCriticalSection( &bip->lock );
939
940 if (bip->closed) {
941 errno = EPIPE;
942 return -1;
943 }
944 /* spinlocking here is probably unfair, but let's live with it */
945 ret = WaitForSingleObject( bip->evt_write, INFINITE );
946 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
947 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
948 return 0;
949 }
950 if (bip->closed) {
951 errno = EPIPE;
952 return -1;
953 }
954 EnterCriticalSection( &bip->lock );
955 }
956
957 BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
958
959 avail = BIP_BUFFER_SIZE - bip->a_end;
960 if (avail > 0)
961 {
962 /* we can append to region A */
963 if (avail > len)
964 avail = len;
965
966 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -0700967 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800968 count += avail;
969 len -= avail;
970
971 bip->a_end += avail;
972 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
973 bip->can_write = 0;
974 ResetEvent( bip->evt_write );
975 goto Exit;
976 }
977 }
978
979 if (len == 0)
980 goto Exit;
981
982 avail = bip->a_start - bip->b_end;
983 assert( avail > 0 ); /* since can_write is TRUE */
984
985 if (avail > len)
986 avail = len;
987
988 memcpy( bip->buff + bip->b_end, src, avail );
989 count += avail;
990 bip->b_end += avail;
991
992 if (bip->b_end == bip->a_start) {
993 bip->can_write = 0;
994 ResetEvent( bip->evt_write );
995 }
996
997Exit:
998 assert( count > 0 );
999
1000 if ( !bip->can_read ) {
1001 bip->can_read = 1;
1002 SetEvent( bip->evt_read );
1003 }
1004
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001005 BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001006 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1007 LeaveCriticalSection( &bip->lock );
1008
1009 return count;
1010 }
1011
1012static int
1013bip_buffer_read( BipBuffer bip, void* dst, int len )
1014{
1015 int avail, count = 0;
1016
1017 if (len <= 0)
1018 return 0;
1019
1020 BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1021
1022 EnterCriticalSection( &bip->lock );
1023 while ( !bip->can_read )
1024 {
1025#if 0
1026 LeaveCriticalSection( &bip->lock );
1027 errno = EAGAIN;
1028 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001029#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001030 int ret;
1031 LeaveCriticalSection( &bip->lock );
1032
1033 if (bip->closed) {
1034 errno = EPIPE;
1035 return -1;
1036 }
1037
1038 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1039 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
1040 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
1041 return 0;
1042 }
1043 if (bip->closed) {
1044 errno = EPIPE;
1045 return -1;
1046 }
1047 EnterCriticalSection( &bip->lock );
1048#endif
1049 }
1050
1051 BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1052
1053 avail = bip->a_end - bip->a_start;
1054 assert( avail > 0 ); /* since can_read is TRUE */
1055
1056 if (avail > len)
1057 avail = len;
1058
1059 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001060 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001061 count += avail;
1062 len -= avail;
1063
1064 bip->a_start += avail;
1065 if (bip->a_start < bip->a_end)
1066 goto Exit;
1067
1068 bip->a_start = 0;
1069 bip->a_end = bip->b_end;
1070 bip->b_end = 0;
1071
1072 avail = bip->a_end;
1073 if (avail > 0) {
1074 if (avail > len)
1075 avail = len;
1076 memcpy( dst, bip->buff, avail );
1077 count += avail;
1078 bip->a_start += avail;
1079
1080 if ( bip->a_start < bip->a_end )
1081 goto Exit;
1082
1083 bip->a_start = bip->a_end = 0;
1084 }
1085
1086 bip->can_read = 0;
1087 ResetEvent( bip->evt_read );
1088
1089Exit:
1090 assert( count > 0 );
1091
1092 if (!bip->can_write ) {
1093 bip->can_write = 1;
1094 SetEvent( bip->evt_write );
1095 }
1096
1097 BIPDUMP( (const unsigned char*)dst - count, count );
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001098 BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001099 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1100 LeaveCriticalSection( &bip->lock );
1101
1102 return count;
1103}
1104
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001105typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001106{
1107 BipBufferRec a2b_bip;
1108 BipBufferRec b2a_bip;
1109 FH a_fd;
1110 int used;
1111
1112} SocketPairRec;
1113
1114void _fh_socketpair_init( FH f )
1115{
1116 f->fh_pair = NULL;
1117}
1118
1119static int
1120_fh_socketpair_close( FH f )
1121{
1122 if ( f->fh_pair ) {
1123 SocketPair pair = f->fh_pair;
1124
1125 if ( f == pair->a_fd ) {
1126 pair->a_fd = NULL;
1127 }
1128
1129 bip_buffer_close( &pair->b2a_bip );
1130 bip_buffer_close( &pair->a2b_bip );
1131
1132 if ( --pair->used == 0 ) {
1133 bip_buffer_done( &pair->b2a_bip );
1134 bip_buffer_done( &pair->a2b_bip );
1135 free( pair );
1136 }
1137 f->fh_pair = NULL;
1138 }
1139 return 0;
1140}
1141
1142static int
1143_fh_socketpair_lseek( FH f, int pos, int origin )
1144{
1145 errno = ESPIPE;
1146 return -1;
1147}
1148
1149static int
1150_fh_socketpair_read( FH f, void* buf, int len )
1151{
1152 SocketPair pair = f->fh_pair;
1153 BipBuffer bip;
1154
1155 if (!pair)
1156 return -1;
1157
1158 if ( f == pair->a_fd )
1159 bip = &pair->b2a_bip;
1160 else
1161 bip = &pair->a2b_bip;
1162
1163 return bip_buffer_read( bip, buf, len );
1164}
1165
1166static int
1167_fh_socketpair_write( FH f, const void* buf, int len )
1168{
1169 SocketPair pair = f->fh_pair;
1170 BipBuffer bip;
1171
1172 if (!pair)
1173 return -1;
1174
1175 if ( f == pair->a_fd )
1176 bip = &pair->a2b_bip;
1177 else
1178 bip = &pair->b2a_bip;
1179
1180 return bip_buffer_write( bip, buf, len );
1181}
1182
1183
1184static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1185
1186static const FHClassRec _fh_socketpair_class =
1187{
1188 _fh_socketpair_init,
1189 _fh_socketpair_close,
1190 _fh_socketpair_lseek,
1191 _fh_socketpair_read,
1192 _fh_socketpair_write,
1193 _fh_socketpair_hook
1194};
1195
1196
Elliott Hughes6a096932015-04-16 16:47:02 -07001197int adb_socketpair(int sv[2]) {
1198 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001199
Elliott Hughes6a096932015-04-16 16:47:02 -07001200 FH fa = _fh_alloc(&_fh_socketpair_class);
1201 FH fb = _fh_alloc(&_fh_socketpair_class);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001202
1203 if (!fa || !fb)
1204 goto Fail;
1205
Elliott Hughes6a096932015-04-16 16:47:02 -07001206 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001207 if (pair == NULL) {
1208 D("adb_socketpair: not enough memory to allocate pipes\n" );
1209 goto Fail;
1210 }
1211
1212 bip_buffer_init( &pair->a2b_bip );
1213 bip_buffer_init( &pair->b2a_bip );
1214
1215 fa->fh_pair = pair;
1216 fb->fh_pair = pair;
1217 pair->used = 2;
1218 pair->a_fd = fa;
1219
1220 sv[0] = _fh_to_int(fa);
1221 sv[1] = _fh_to_int(fb);
1222
1223 pair->a2b_bip.fdin = sv[0];
1224 pair->a2b_bip.fdout = sv[1];
1225 pair->b2a_bip.fdin = sv[1];
1226 pair->b2a_bip.fdout = sv[0];
1227
1228 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1229 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
1230 D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
1231 return 0;
1232
1233Fail:
1234 _fh_close(fb);
1235 _fh_close(fa);
1236 return -1;
1237}
1238
1239/**************************************************************************/
1240/**************************************************************************/
1241/***** *****/
1242/***** fdevents emulation *****/
1243/***** *****/
1244/***** this is a very simple implementation, we rely on the fact *****/
1245/***** that ADB doesn't use FDE_ERROR. *****/
1246/***** *****/
1247/**************************************************************************/
1248/**************************************************************************/
1249
1250#define FATAL(x...) fatal(__FUNCTION__, x)
1251
1252#if DEBUG
1253static void dump_fde(fdevent *fde, const char *info)
1254{
1255 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1256 fde->state & FDE_READ ? 'R' : ' ',
1257 fde->state & FDE_WRITE ? 'W' : ' ',
1258 fde->state & FDE_ERROR ? 'E' : ' ',
1259 info);
1260}
1261#else
1262#define dump_fde(fde, info) do { } while(0)
1263#endif
1264
1265#define FDE_EVENTMASK 0x00ff
1266#define FDE_STATEMASK 0xff00
1267
1268#define FDE_ACTIVE 0x0100
1269#define FDE_PENDING 0x0200
1270#define FDE_CREATED 0x0400
1271
1272static void fdevent_plist_enqueue(fdevent *node);
1273static void fdevent_plist_remove(fdevent *node);
1274static fdevent *fdevent_plist_dequeue(void);
1275
1276static fdevent list_pending = {
1277 .next = &list_pending,
1278 .prev = &list_pending,
1279};
1280
1281static fdevent **fd_table = 0;
1282static int fd_table_max = 0;
1283
1284typedef struct EventLooperRec_* EventLooper;
1285
1286typedef struct EventHookRec_
1287{
1288 EventHook next;
1289 FH fh;
1290 HANDLE h;
1291 int wanted; /* wanted event flags */
1292 int ready; /* ready event flags */
1293 void* aux;
1294 void (*prepare)( EventHook hook );
1295 int (*start) ( EventHook hook );
1296 void (*stop) ( EventHook hook );
1297 int (*check) ( EventHook hook );
1298 int (*peek) ( EventHook hook );
1299} EventHookRec;
1300
1301static EventHook _free_hooks;
1302
1303static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001304event_hook_alloc(FH fh) {
1305 EventHook hook = _free_hooks;
1306 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001307 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001308 } else {
1309 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001310 if (hook == NULL)
1311 fatal( "could not allocate event hook\n" );
1312 }
1313 hook->next = NULL;
1314 hook->fh = fh;
1315 hook->wanted = 0;
1316 hook->ready = 0;
1317 hook->h = INVALID_HANDLE_VALUE;
1318 hook->aux = NULL;
1319
1320 hook->prepare = NULL;
1321 hook->start = NULL;
1322 hook->stop = NULL;
1323 hook->check = NULL;
1324 hook->peek = NULL;
1325
1326 return hook;
1327}
1328
1329static void
1330event_hook_free( EventHook hook )
1331{
1332 hook->fh = NULL;
1333 hook->wanted = 0;
1334 hook->ready = 0;
1335 hook->next = _free_hooks;
1336 _free_hooks = hook;
1337}
1338
1339
1340static void
1341event_hook_signal( EventHook hook )
1342{
1343 FH f = hook->fh;
1344 int fd = _fh_to_int(f);
1345 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1346
1347 if (fde != NULL && fde->fd == fd) {
1348 if ((fde->state & FDE_PENDING) == 0) {
1349 fde->state |= FDE_PENDING;
1350 fdevent_plist_enqueue( fde );
1351 }
1352 fde->events |= hook->wanted;
1353 }
1354}
1355
1356
1357#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1358
1359typedef struct EventLooperRec_
1360{
1361 EventHook hooks;
1362 HANDLE htab[ MAX_LOOPER_HANDLES ];
1363 int htab_count;
1364
1365} EventLooperRec;
1366
1367static EventHook*
1368event_looper_find_p( EventLooper looper, FH fh )
1369{
1370 EventHook *pnode = &looper->hooks;
1371 EventHook node = *pnode;
1372 for (;;) {
1373 if ( node == NULL || node->fh == fh )
1374 break;
1375 pnode = &node->next;
1376 node = *pnode;
1377 }
1378 return pnode;
1379}
1380
1381static void
1382event_looper_hook( EventLooper looper, int fd, int events )
1383{
Spencer Low3a2421b2015-05-22 20:09:06 -07001384 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001385 EventHook *pnode;
1386 EventHook node;
1387
1388 if (f == NULL) /* invalid arg */ {
1389 D("event_looper_hook: invalid fd=%d\n", fd);
1390 return;
1391 }
1392
1393 pnode = event_looper_find_p( looper, f );
1394 node = *pnode;
1395 if ( node == NULL ) {
1396 node = event_hook_alloc( f );
1397 node->next = *pnode;
1398 *pnode = node;
1399 }
1400
1401 if ( (node->wanted & events) != events ) {
1402 /* this should update start/stop/check/peek */
1403 D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
1404 fd, node->wanted, events);
1405 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1406 node->wanted |= events;
1407 } else {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001408 D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001409 events, fd, node->wanted);
1410 }
1411}
1412
1413static void
1414event_looper_unhook( EventLooper looper, int fd, int events )
1415{
Spencer Low3a2421b2015-05-22 20:09:06 -07001416 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001417 EventHook *pnode = event_looper_find_p( looper, fh );
1418 EventHook node = *pnode;
1419
1420 if (node != NULL) {
1421 int events2 = events & node->wanted;
1422 if ( events2 == 0 ) {
1423 D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
1424 return;
1425 }
1426 node->wanted &= ~events2;
1427 if (!node->wanted) {
1428 *pnode = node->next;
1429 event_hook_free( node );
1430 }
1431 }
1432}
1433
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001434/*
1435 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1436 * handles to wait on.
1437 *
1438 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1439 * instance, this may happen if there are more than 64 processes running on a
1440 * device, or there are multiple devices connected (including the emulator) with
1441 * the combined number of running processes greater than 64. In this case using
1442 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1443 * because of the API limitations (64 handles max). So, we need to provide a way
1444 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1445 * easiest (and "Microsoft recommended") way to do that would be dividing the
1446 * handle array into chunks with the chunk size less than 64, and fire up as many
1447 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1448 * handles, and will report back to the caller which handle has been set.
1449 * Here is the implementation of that algorithm.
1450 */
1451
1452/* Number of handles to wait on in each wating thread. */
1453#define WAIT_ALL_CHUNK_SIZE 63
1454
1455/* Descriptor for a wating thread */
1456typedef struct WaitForAllParam {
1457 /* A handle to an event to signal when waiting is over. This handle is shared
1458 * accross all the waiting threads, so each waiting thread knows when any
1459 * other thread has exited, so it can exit too. */
1460 HANDLE main_event;
1461 /* Upon exit from a waiting thread contains the index of the handle that has
1462 * been signaled. The index is an absolute index of the signaled handle in
1463 * the original array. This pointer is shared accross all the waiting threads
1464 * and it's not guaranteed (due to a race condition) that when all the
1465 * waiting threads exit, the value contained here would indicate the first
1466 * handle that was signaled. This is fine, because the caller cares only
1467 * about any handle being signaled. It doesn't care about the order, nor
1468 * about the whole list of handles that were signaled. */
1469 LONG volatile *signaled_index;
1470 /* Array of handles to wait on in a waiting thread. */
1471 HANDLE* handles;
1472 /* Number of handles in 'handles' array to wait on. */
1473 int handles_count;
1474 /* Index inside the main array of the first handle in the 'handles' array. */
1475 int first_handle_index;
1476 /* Waiting thread handle. */
1477 HANDLE thread;
1478} WaitForAllParam;
1479
1480/* Waiting thread routine. */
1481static unsigned __stdcall
1482_in_waiter_thread(void* arg)
1483{
1484 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1485 int res;
1486 WaitForAllParam* const param = (WaitForAllParam*)arg;
1487
1488 /* We have to wait on the main_event in order to be notified when any of the
1489 * sibling threads is exiting. */
1490 wait_on[0] = param->main_event;
1491 /* The rest of the handles go behind the main event handle. */
1492 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1493
1494 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1495 if (res > 0 && res < (param->handles_count + 1)) {
1496 /* One of the original handles got signaled. Save its absolute index into
1497 * the output variable. */
1498 InterlockedCompareExchange(param->signaled_index,
1499 res - 1L + param->first_handle_index, -1L);
1500 }
1501
1502 /* Notify the caller (and the siblings) that the wait is over. */
1503 SetEvent(param->main_event);
1504
1505 _endthreadex(0);
1506 return 0;
1507}
1508
1509/* WaitForMultipeObjects fixer routine.
1510 * Param:
1511 * handles Array of handles to wait on.
1512 * handles_count Number of handles in the array.
1513 * Return:
1514 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1515 * WAIT_FAILED on an error.
1516 */
1517static int
1518_wait_for_all(HANDLE* handles, int handles_count)
1519{
1520 WaitForAllParam* threads;
1521 HANDLE main_event;
1522 int chunks, chunk, remains;
1523
1524 /* This variable is going to be accessed by several threads at the same time,
1525 * this is bound to fail randomly when the core is run on multi-core machines.
1526 * To solve this, we need to do the following (1 _and_ 2):
1527 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1528 * out the reads/writes in this function unexpectedly.
1529 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1530 * all accesses inside a critical section. But we can also use
1531 * InterlockedCompareExchange() which always provide a full memory barrier
1532 * on Win32.
1533 */
1534 volatile LONG sig_index = -1;
1535
1536 /* Calculate number of chunks, and allocate thread param array. */
1537 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1538 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1539 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1540 sizeof(WaitForAllParam));
1541 if (threads == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001542 D("Unable to allocate thread array for %d handles.\n", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001543 return (int)WAIT_FAILED;
1544 }
1545
1546 /* Create main event to wait on for all waiting threads. This is a "manualy
1547 * reset" event that will remain set once it was set. */
1548 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1549 if (main_event == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001550 D("Unable to create main event. Error: %ld\n", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001551 free(threads);
1552 return (int)WAIT_FAILED;
1553 }
1554
1555 /*
1556 * Initialize waiting thread parameters.
1557 */
1558
1559 for (chunk = 0; chunk < chunks; chunk++) {
1560 threads[chunk].main_event = main_event;
1561 threads[chunk].signaled_index = &sig_index;
1562 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1563 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1564 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1565 }
1566 if (remains) {
1567 threads[chunk].main_event = main_event;
1568 threads[chunk].signaled_index = &sig_index;
1569 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1570 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1571 threads[chunk].handles_count = remains;
1572 chunks++;
1573 }
1574
1575 /* Start the waiting threads. */
1576 for (chunk = 0; chunk < chunks; chunk++) {
1577 /* Note that using adb_thread_create is not appropriate here, since we
1578 * need a handle to wait on for thread termination. */
1579 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1580 &threads[chunk], 0, NULL);
1581 if (threads[chunk].thread == NULL) {
1582 /* Unable to create a waiter thread. Collapse. */
Spencer Low5c761bd2015-07-21 02:06:26 -07001583 D("Unable to create a waiting thread %d of %d. errno=%d\n",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001584 chunk, chunks, errno);
1585 chunks = chunk;
1586 SetEvent(main_event);
1587 break;
1588 }
1589 }
1590
1591 /* Wait on any of the threads to get signaled. */
1592 WaitForSingleObject(main_event, INFINITE);
1593
1594 /* Wait on all the waiting threads to exit. */
1595 for (chunk = 0; chunk < chunks; chunk++) {
1596 WaitForSingleObject(threads[chunk].thread, INFINITE);
1597 CloseHandle(threads[chunk].thread);
1598 }
1599
1600 CloseHandle(main_event);
1601 free(threads);
1602
1603
1604 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1605 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1606}
1607
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001608static EventLooperRec win32_looper;
1609
1610static void fdevent_init(void)
1611{
1612 win32_looper.htab_count = 0;
1613 win32_looper.hooks = NULL;
1614}
1615
1616static void fdevent_connect(fdevent *fde)
1617{
1618 EventLooper looper = &win32_looper;
1619 int events = fde->state & FDE_EVENTMASK;
1620
1621 if (events != 0)
1622 event_looper_hook( looper, fde->fd, events );
1623}
1624
1625static void fdevent_disconnect(fdevent *fde)
1626{
1627 EventLooper looper = &win32_looper;
1628 int events = fde->state & FDE_EVENTMASK;
1629
1630 if (events != 0)
1631 event_looper_unhook( looper, fde->fd, events );
1632}
1633
1634static void fdevent_update(fdevent *fde, unsigned events)
1635{
1636 EventLooper looper = &win32_looper;
1637 unsigned events0 = fde->state & FDE_EVENTMASK;
1638
1639 if (events != events0) {
1640 int removes = events0 & ~events;
1641 int adds = events & ~events0;
1642 if (removes) {
1643 D("fdevent_update: remove %x from %d\n", removes, fde->fd);
1644 event_looper_unhook( looper, fde->fd, removes );
1645 }
1646 if (adds) {
1647 D("fdevent_update: add %x to %d\n", adds, fde->fd);
1648 event_looper_hook ( looper, fde->fd, adds );
1649 }
1650 }
1651}
1652
1653static void fdevent_process()
1654{
1655 EventLooper looper = &win32_looper;
1656 EventHook hook;
1657 int gotone = 0;
1658
1659 /* if we have at least one ready hook, execute it/them */
1660 for (hook = looper->hooks; hook; hook = hook->next) {
1661 hook->ready = 0;
1662 if (hook->prepare) {
1663 hook->prepare(hook);
1664 if (hook->ready != 0) {
1665 event_hook_signal( hook );
1666 gotone = 1;
1667 }
1668 }
1669 }
1670
1671 /* nothing's ready yet, so wait for something to happen */
1672 if (!gotone)
1673 {
1674 looper->htab_count = 0;
1675
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001676 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001677 {
1678 if (hook->start && !hook->start(hook)) {
1679 D( "fdevent_process: error when starting a hook\n" );
1680 return;
1681 }
1682 if (hook->h != INVALID_HANDLE_VALUE) {
1683 int nn;
1684
1685 for (nn = 0; nn < looper->htab_count; nn++)
1686 {
1687 if ( looper->htab[nn] == hook->h )
1688 goto DontAdd;
1689 }
1690 looper->htab[ looper->htab_count++ ] = hook->h;
1691 DontAdd:
1692 ;
1693 }
1694 }
1695
1696 if (looper->htab_count == 0) {
1697 D( "fdevent_process: nothing to wait for !!\n" );
1698 return;
1699 }
1700
1701 do
1702 {
1703 int wait_ret;
1704
1705 D( "adb_win32: waiting for %d events\n", looper->htab_count );
1706 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001707 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
1708 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1709 } else {
1710 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001711 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001712 if (wait_ret == (int)WAIT_FAILED) {
1713 D( "adb_win32: wait failed, error %ld\n", GetLastError() );
1714 } else {
1715 D( "adb_win32: got one (index %d)\n", wait_ret );
1716
1717 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1718 * like mouse movements. we need to filter these with the "check" function
1719 */
1720 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1721 {
1722 for (hook = looper->hooks; hook; hook = hook->next)
1723 {
1724 if ( looper->htab[wait_ret] == hook->h &&
1725 (!hook->check || hook->check(hook)) )
1726 {
1727 D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
1728 event_hook_signal( hook );
1729 gotone = 1;
1730 break;
1731 }
1732 }
1733 }
1734 }
1735 }
1736 while (!gotone);
1737
1738 for (hook = looper->hooks; hook; hook = hook->next) {
1739 if (hook->stop)
1740 hook->stop( hook );
1741 }
1742 }
1743
1744 for (hook = looper->hooks; hook; hook = hook->next) {
1745 if (hook->peek && hook->peek(hook))
1746 event_hook_signal( hook );
1747 }
1748}
1749
1750
1751static void fdevent_register(fdevent *fde)
1752{
1753 int fd = fde->fd - WIN32_FH_BASE;
1754
1755 if(fd < 0) {
1756 FATAL("bogus negative fd (%d)\n", fde->fd);
1757 }
1758
1759 if(fd >= fd_table_max) {
1760 int oldmax = fd_table_max;
1761 if(fde->fd > 32000) {
1762 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1763 }
1764 if(fd_table_max == 0) {
1765 fdevent_init();
1766 fd_table_max = 256;
1767 }
1768 while(fd_table_max <= fd) {
1769 fd_table_max *= 2;
1770 }
Elliott Hughes6a096932015-04-16 16:47:02 -07001771 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001772 if(fd_table == 0) {
1773 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1774 }
1775 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
1776 }
1777
1778 fd_table[fd] = fde;
1779}
1780
1781static void fdevent_unregister(fdevent *fde)
1782{
1783 int fd = fde->fd - WIN32_FH_BASE;
1784
1785 if((fd < 0) || (fd >= fd_table_max)) {
1786 FATAL("fd out of range (%d)\n", fde->fd);
1787 }
1788
1789 if(fd_table[fd] != fde) {
1790 FATAL("fd_table out of sync");
1791 }
1792
1793 fd_table[fd] = 0;
1794
1795 if(!(fde->state & FDE_DONT_CLOSE)) {
1796 dump_fde(fde, "close");
1797 adb_close(fde->fd);
1798 }
1799}
1800
1801static void fdevent_plist_enqueue(fdevent *node)
1802{
1803 fdevent *list = &list_pending;
1804
1805 node->next = list;
1806 node->prev = list->prev;
1807 node->prev->next = node;
1808 list->prev = node;
1809}
1810
1811static void fdevent_plist_remove(fdevent *node)
1812{
1813 node->prev->next = node->next;
1814 node->next->prev = node->prev;
1815 node->next = 0;
1816 node->prev = 0;
1817}
1818
1819static fdevent *fdevent_plist_dequeue(void)
1820{
1821 fdevent *list = &list_pending;
1822 fdevent *node = list->next;
1823
1824 if(node == list) return 0;
1825
1826 list->next = node->next;
1827 list->next->prev = list;
1828 node->next = 0;
1829 node->prev = 0;
1830
1831 return node;
1832}
1833
1834fdevent *fdevent_create(int fd, fd_func func, void *arg)
1835{
1836 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
1837 if(fde == 0) return 0;
1838 fdevent_install(fde, fd, func, arg);
1839 fde->state |= FDE_CREATED;
1840 return fde;
1841}
1842
1843void fdevent_destroy(fdevent *fde)
1844{
1845 if(fde == 0) return;
1846 if(!(fde->state & FDE_CREATED)) {
1847 FATAL("fde %p not created by fdevent_create()\n", fde);
1848 }
1849 fdevent_remove(fde);
1850}
1851
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001852void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001853{
1854 memset(fde, 0, sizeof(fdevent));
1855 fde->state = FDE_ACTIVE;
1856 fde->fd = fd;
1857 fde->func = func;
1858 fde->arg = arg;
1859
1860 fdevent_register(fde);
1861 dump_fde(fde, "connect");
1862 fdevent_connect(fde);
1863 fde->state |= FDE_ACTIVE;
1864}
1865
1866void fdevent_remove(fdevent *fde)
1867{
1868 if(fde->state & FDE_PENDING) {
1869 fdevent_plist_remove(fde);
1870 }
1871
1872 if(fde->state & FDE_ACTIVE) {
1873 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001874 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001875 fdevent_unregister(fde);
1876 }
1877
1878 fde->state = 0;
1879 fde->events = 0;
1880}
1881
1882
1883void fdevent_set(fdevent *fde, unsigned events)
1884{
1885 events &= FDE_EVENTMASK;
1886
1887 if((fde->state & FDE_EVENTMASK) == (int)events) return;
1888
1889 if(fde->state & FDE_ACTIVE) {
1890 fdevent_update(fde, events);
1891 dump_fde(fde, "update");
1892 }
1893
1894 fde->state = (fde->state & FDE_STATEMASK) | events;
1895
1896 if(fde->state & FDE_PENDING) {
1897 /* if we're pending, make sure
1898 ** we don't signal an event that
1899 ** is no longer wanted.
1900 */
1901 fde->events &= (~events);
1902 if(fde->events == 0) {
1903 fdevent_plist_remove(fde);
1904 fde->state &= (~FDE_PENDING);
1905 }
1906 }
1907}
1908
1909void fdevent_add(fdevent *fde, unsigned events)
1910{
1911 fdevent_set(
1912 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
1913}
1914
1915void fdevent_del(fdevent *fde, unsigned events)
1916{
1917 fdevent_set(
1918 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
1919}
1920
1921void fdevent_loop()
1922{
1923 fdevent *fde;
1924
1925 for(;;) {
1926#if DEBUG
1927 fprintf(stderr,"--- ---- waiting for events\n");
1928#endif
1929 fdevent_process();
1930
1931 while((fde = fdevent_plist_dequeue())) {
1932 unsigned events = fde->events;
1933 fde->events = 0;
1934 fde->state &= (~FDE_PENDING);
1935 dump_fde(fde, "callback");
1936 fde->func(fde->fd, events, fde->arg);
1937 }
1938 }
1939}
1940
1941/** FILE EVENT HOOKS
1942 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001943
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001944static void _event_file_prepare( EventHook hook )
1945{
1946 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
1947 /* we can always read/write */
1948 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
1949 }
1950}
1951
1952static int _event_file_peek( EventHook hook )
1953{
1954 return (hook->wanted & (FDE_READ|FDE_WRITE));
1955}
1956
1957static void _fh_file_hook( FH f, int events, EventHook hook )
1958{
1959 hook->h = f->fh_handle;
1960 hook->prepare = _event_file_prepare;
1961 hook->peek = _event_file_peek;
1962}
1963
1964/** SOCKET EVENT HOOKS
1965 **/
1966
1967static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
1968{
1969 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
1970 if (hook->wanted & FDE_READ)
1971 hook->ready |= FDE_READ;
1972 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
1973 hook->ready |= FDE_ERROR;
1974 }
1975 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
1976 if (hook->wanted & FDE_WRITE)
1977 hook->ready |= FDE_WRITE;
1978 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
1979 hook->ready |= FDE_ERROR;
1980 }
1981 if ( evts->lNetworkEvents & FD_OOB ) {
1982 if (hook->wanted & FDE_ERROR)
1983 hook->ready |= FDE_ERROR;
1984 }
1985}
1986
1987static void _event_socket_prepare( EventHook hook )
1988{
1989 WSANETWORKEVENTS evts;
1990
1991 /* look if some of the events we want already happened ? */
1992 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
1993 _event_socket_verify( hook, &evts );
1994}
1995
1996static int _socket_wanted_to_flags( int wanted )
1997{
1998 int flags = 0;
1999 if (wanted & FDE_READ)
2000 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2001
2002 if (wanted & FDE_WRITE)
2003 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2004
2005 if (wanted & FDE_ERROR)
2006 flags |= FD_OOB;
2007
2008 return flags;
2009}
2010
2011static int _event_socket_start( EventHook hook )
2012{
2013 /* create an event which we're going to wait for */
2014 FH fh = hook->fh;
2015 long flags = _socket_wanted_to_flags( hook->wanted );
2016
2017 hook->h = fh->event;
2018 if (hook->h == INVALID_HANDLE_VALUE) {
2019 D( "_event_socket_start: no event for %s\n", fh->name );
2020 return 0;
2021 }
2022
2023 if ( flags != fh->mask ) {
2024 D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
2025 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
2026 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
2027 CloseHandle( hook->h );
2028 hook->h = INVALID_HANDLE_VALUE;
2029 exit(1);
2030 return 0;
2031 }
2032 fh->mask = flags;
2033 }
2034 return 1;
2035}
2036
2037static void _event_socket_stop( EventHook hook )
2038{
2039 hook->h = INVALID_HANDLE_VALUE;
2040}
2041
2042static int _event_socket_check( EventHook hook )
2043{
2044 int result = 0;
2045 FH fh = hook->fh;
2046 WSANETWORKEVENTS evts;
2047
2048 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2049 _event_socket_verify( hook, &evts );
2050 result = (hook->ready != 0);
2051 if (result) {
2052 ResetEvent( hook->h );
2053 }
2054 }
2055 D( "_event_socket_check %s returns %d\n", fh->name, result );
2056 return result;
2057}
2058
2059static int _event_socket_peek( EventHook hook )
2060{
2061 WSANETWORKEVENTS evts;
2062 FH fh = hook->fh;
2063
2064 /* look if some of the events we want already happened ? */
2065 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2066 _event_socket_verify( hook, &evts );
2067 if (hook->ready)
2068 ResetEvent( hook->h );
2069 }
2070
2071 return hook->ready != 0;
2072}
2073
2074
2075
2076static void _fh_socket_hook( FH f, int events, EventHook hook )
2077{
2078 hook->prepare = _event_socket_prepare;
2079 hook->start = _event_socket_start;
2080 hook->stop = _event_socket_stop;
2081 hook->check = _event_socket_check;
2082 hook->peek = _event_socket_peek;
2083
2084 _event_socket_start( hook );
2085}
2086
2087/** SOCKETPAIR EVENT HOOKS
2088 **/
2089
2090static void _event_socketpair_prepare( EventHook hook )
2091{
2092 FH fh = hook->fh;
2093 SocketPair pair = fh->fh_pair;
2094 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2095 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2096
2097 if (hook->wanted & FDE_READ && rbip->can_read)
2098 hook->ready |= FDE_READ;
2099
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002100 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002101 hook->ready |= FDE_WRITE;
2102 }
2103
2104 static int _event_socketpair_start( EventHook hook )
2105 {
2106 FH fh = hook->fh;
2107 SocketPair pair = fh->fh_pair;
2108 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2109 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2110
2111 if (hook->wanted == FDE_READ)
2112 hook->h = rbip->evt_read;
2113
2114 else if (hook->wanted == FDE_WRITE)
2115 hook->h = wbip->evt_write;
2116
2117 else {
2118 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
2119 return 0;
2120 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002121 D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002122 hook->fh->name, _fh_to_int(fh), hook->wanted);
2123 return 1;
2124}
2125
2126static int _event_socketpair_peek( EventHook hook )
2127{
2128 _event_socketpair_prepare( hook );
2129 return hook->ready != 0;
2130}
2131
2132static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2133{
2134 hook->prepare = _event_socketpair_prepare;
2135 hook->start = _event_socketpair_start;
2136 hook->peek = _event_socketpair_peek;
2137}
2138
2139
2140void
2141adb_sysdeps_init( void )
2142{
2143#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2144#include "mutex_list.h"
2145 InitializeCriticalSection( &_win32_lock );
2146}
2147
Spencer Lowbeb61982015-03-01 15:06:21 -08002148/**************************************************************************/
2149/**************************************************************************/
2150/***** *****/
2151/***** Console Window Terminal Emulation *****/
2152/***** *****/
2153/**************************************************************************/
2154/**************************************************************************/
2155
2156// This reads input from a Win32 console window and translates it into Unix
2157// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2158// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2159// is emulated instead of xterm because it is probably more popular than xterm:
2160// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2161// supports modern fonts, etc. It seems best to emulate the terminal that most
2162// Android developers use because they'll fix apps (the shell, etc.) to keep
2163// working with that terminal's emulation.
2164//
2165// The point of this emulation is not to be perfect or to solve all issues with
2166// console windows on Windows, but to be better than the original code which
2167// just called read() (which called ReadFile(), which called ReadConsoleA())
2168// which did not support Ctrl-C, tab completion, shell input line editing
2169// keys, server echo, and more.
2170//
2171// This implementation reconfigures the console with SetConsoleMode(), then
2172// calls ReadConsoleInput() to get raw input which it remaps to Unix
2173// terminal-style sequences which is returned via unix_read() which is used
2174// by the 'adb shell' command.
2175//
2176// Code organization:
2177//
2178// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2179// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2180// * _console_read() is the main code of the emulation.
2181
2182
2183// Read an input record from the console; one that should be processed.
2184static bool _get_interesting_input_record_uncached(const HANDLE console,
2185 INPUT_RECORD* const input_record) {
2186 for (;;) {
2187 DWORD read_count = 0;
2188 memset(input_record, 0, sizeof(*input_record));
2189 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2190 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
2191 "failure, error %ld\n", GetLastError());
2192 errno = EIO;
2193 return false;
2194 }
2195
2196 if (read_count == 0) { // should be impossible
2197 fatal("ReadConsoleInputA returned 0");
2198 }
2199
2200 if (read_count != 1) { // should be impossible
2201 fatal("ReadConsoleInputA did not return one input record");
2202 }
2203
2204 if ((input_record->EventType == KEY_EVENT) &&
2205 (input_record->Event.KeyEvent.bKeyDown)) {
2206 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2207 fatal("ReadConsoleInputA returned a key event with zero repeat"
2208 " count");
2209 }
2210
2211 // Got an interesting INPUT_RECORD, so return
2212 return true;
2213 }
2214 }
2215}
2216
2217// Cached input record (in case _console_read() is passed a buffer that doesn't
2218// have enough space to fit wRepeatCount number of key sequences). A non-zero
2219// wRepeatCount indicates that a record is cached.
2220static INPUT_RECORD _win32_input_record;
2221
2222// Get the next KEY_EVENT_RECORD that should be processed.
2223static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2224 // If nothing cached, read directly from the console until we get an
2225 // interesting record.
2226 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2227 if (!_get_interesting_input_record_uncached(console,
2228 &_win32_input_record)) {
2229 // There was an error, so make sure wRepeatCount is zero because
2230 // that signifies no cached input record.
2231 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2232 return NULL;
2233 }
2234 }
2235
2236 return &_win32_input_record.Event.KeyEvent;
2237}
2238
2239static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2240 return (control_key_state & SHIFT_PRESSED) != 0;
2241}
2242
2243static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2244 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2245}
2246
2247static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2248 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2249}
2250
2251static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2252 return (control_key_state & NUMLOCK_ON) != 0;
2253}
2254
2255static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2256 return (control_key_state & CAPSLOCK_ON) != 0;
2257}
2258
2259static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2260 return (control_key_state & ENHANCED_KEY) != 0;
2261}
2262
2263// Constants from MSDN for ToAscii().
2264static const BYTE TOASCII_KEY_OFF = 0x00;
2265static const BYTE TOASCII_KEY_DOWN = 0x80;
2266static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2267
2268// Given a key event, ignore a modifier key and return the character that was
2269// entered without the modifier. Writes to *ch and returns the number of bytes
2270// written.
2271static size_t _get_char_ignoring_modifier(char* const ch,
2272 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2273 const WORD modifier) {
2274 // If there is no character from Windows, try ignoring the specified
2275 // modifier and look for a character. Note that if AltGr is being used,
2276 // there will be a character from Windows.
2277 if (key_event->uChar.AsciiChar == '\0') {
2278 // Note that we read the control key state from the passed in argument
2279 // instead of from key_event since the argument has been normalized.
2280 if (((modifier == VK_SHIFT) &&
2281 _is_shift_pressed(control_key_state)) ||
2282 ((modifier == VK_CONTROL) &&
2283 _is_ctrl_pressed(control_key_state)) ||
2284 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2285
2286 BYTE key_state[256] = {0};
2287 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2288 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2289 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2290 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2291 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2292 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2293 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2294 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2295
2296 // cause this modifier to be ignored
2297 key_state[modifier] = TOASCII_KEY_OFF;
2298
2299 WORD translated = 0;
2300 if (ToAscii(key_event->wVirtualKeyCode,
2301 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2302 // Ignoring the modifier, we found a character.
2303 *ch = (CHAR)translated;
2304 return 1;
2305 }
2306 }
2307 }
2308
2309 // Just use whatever Windows told us originally.
2310 *ch = key_event->uChar.AsciiChar;
2311
2312 // If the character from Windows is NULL, return a size of zero.
2313 return (*ch == '\0') ? 0 : 1;
2314}
2315
2316// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2317// but taking into account the shift key. This is because for a sequence like
2318// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2319// we want to find the character ')'.
2320//
2321// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2322// because it is the default key-sequence to switch the input language.
2323// This is configurable in the Region and Language control panel.
2324static __inline__ size_t _get_non_control_char(char* const ch,
2325 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2326 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2327 VK_CONTROL);
2328}
2329
2330// Get without Alt.
2331static __inline__ size_t _get_non_alt_char(char* const ch,
2332 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2333 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2334 VK_MENU);
2335}
2336
2337// Ignore the control key, find the character from Windows, and apply any
2338// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2339// *pch and returns number of bytes written.
2340static size_t _get_control_character(char* const pch,
2341 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2342 const size_t len = _get_non_control_char(pch, key_event,
2343 control_key_state);
2344
2345 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2346 char ch = *pch;
2347 switch (ch) {
2348 case '2':
2349 case '@':
2350 case '`':
2351 ch = '\0';
2352 break;
2353 case '3':
2354 case '[':
2355 case '{':
2356 ch = '\x1b';
2357 break;
2358 case '4':
2359 case '\\':
2360 case '|':
2361 ch = '\x1c';
2362 break;
2363 case '5':
2364 case ']':
2365 case '}':
2366 ch = '\x1d';
2367 break;
2368 case '6':
2369 case '^':
2370 case '~':
2371 ch = '\x1e';
2372 break;
2373 case '7':
2374 case '-':
2375 case '_':
2376 ch = '\x1f';
2377 break;
2378 case '8':
2379 ch = '\x7f';
2380 break;
2381 case '/':
2382 if (!_is_alt_pressed(control_key_state)) {
2383 ch = '\x1f';
2384 }
2385 break;
2386 case '?':
2387 if (!_is_alt_pressed(control_key_state)) {
2388 ch = '\x7f';
2389 }
2390 break;
2391 }
2392 *pch = ch;
2393 }
2394
2395 return len;
2396}
2397
2398static DWORD _normalize_altgr_control_key_state(
2399 const KEY_EVENT_RECORD* const key_event) {
2400 DWORD control_key_state = key_event->dwControlKeyState;
2401
2402 // If we're in an AltGr situation where the AltGr key is down (depending on
2403 // the keyboard layout, that might be the physical right alt key which
2404 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2405 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2406 // a character (which indicates that there was an AltGr mapping), then act
2407 // as if alt and control are not really down for the purposes of modifiers.
2408 // This makes it so that if the user with, say, a German keyboard layout
2409 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2410 // output the key and we don't see the Alt and Ctrl keys.
2411 if (_is_ctrl_pressed(control_key_state) &&
2412 _is_alt_pressed(control_key_state)
2413 && (key_event->uChar.AsciiChar != '\0')) {
2414 // Try to remove as few bits as possible to improve our chances of
2415 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2416 // Left-Alt + Right-Ctrl + AltGr.
2417 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2418 // Remove Right-Alt.
2419 control_key_state &= ~RIGHT_ALT_PRESSED;
2420 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2421 // pressed, Left-Ctrl is almost always set, except if the user
2422 // presses Right-Ctrl, then AltGr (in that specific order) for
2423 // whatever reason. At any rate, make sure the bit is not set.
2424 control_key_state &= ~LEFT_CTRL_PRESSED;
2425 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2426 // Remove Left-Alt.
2427 control_key_state &= ~LEFT_ALT_PRESSED;
2428 // Whichever Ctrl key is down, remove it from the state. We only
2429 // remove one key, to improve our chances of detecting the
2430 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2431 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2432 // Remove Left-Ctrl.
2433 control_key_state &= ~LEFT_CTRL_PRESSED;
2434 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2435 // Remove Right-Ctrl.
2436 control_key_state &= ~RIGHT_CTRL_PRESSED;
2437 }
2438 }
2439
2440 // Note that this logic isn't 100% perfect because Windows doesn't
2441 // allow us to detect all combinations because a physical AltGr key
2442 // press shows up as two bits, plus some combinations are ambiguous
2443 // about what is actually physically pressed.
2444 }
2445
2446 return control_key_state;
2447}
2448
2449// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2450// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2451// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2452// appropriately.
2453static DWORD _normalize_keypad_control_key_state(const WORD vk,
2454 const DWORD control_key_state) {
2455 if (!_is_numlock_on(control_key_state)) {
2456 return control_key_state;
2457 }
2458 if (!_is_enhanced_key(control_key_state)) {
2459 switch (vk) {
2460 case VK_INSERT: // 0
2461 case VK_DELETE: // .
2462 case VK_END: // 1
2463 case VK_DOWN: // 2
2464 case VK_NEXT: // 3
2465 case VK_LEFT: // 4
2466 case VK_CLEAR: // 5
2467 case VK_RIGHT: // 6
2468 case VK_HOME: // 7
2469 case VK_UP: // 8
2470 case VK_PRIOR: // 9
2471 return control_key_state | SHIFT_PRESSED;
2472 }
2473 }
2474
2475 return control_key_state;
2476}
2477
2478static const char* _get_keypad_sequence(const DWORD control_key_state,
2479 const char* const normal, const char* const shifted) {
2480 if (_is_shift_pressed(control_key_state)) {
2481 // Shift is pressed and NumLock is off
2482 return shifted;
2483 } else {
2484 // Shift is not pressed and NumLock is off, or,
2485 // Shift is pressed and NumLock is on, in which case we want the
2486 // NumLock and Shift to neutralize each other, thus, we want the normal
2487 // sequence.
2488 return normal;
2489 }
2490 // If Shift is not pressed and NumLock is on, a different virtual key code
2491 // is returned by Windows, which can be taken care of by a different case
2492 // statement in _console_read().
2493}
2494
2495// Write sequence to buf and return the number of bytes written.
2496static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2497 DWORD control_key_state, const char* const normal) {
2498 // Copy the base sequence into buf.
2499 const size_t len = strlen(normal);
2500 memcpy(buf, normal, len);
2501
2502 int code = 0;
2503
2504 control_key_state = _normalize_keypad_control_key_state(vk,
2505 control_key_state);
2506
2507 if (_is_shift_pressed(control_key_state)) {
2508 code |= 0x1;
2509 }
2510 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2511 code |= 0x2;
2512 }
2513 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2514 code |= 0x4;
2515 }
2516 // If some modifier was held down, then we need to insert the modifier code
2517 if (code != 0) {
2518 if (len == 0) {
2519 // Should be impossible because caller should pass a string of
2520 // non-zero length.
2521 return 0;
2522 }
2523 size_t index = len - 1;
2524 const char lastChar = buf[index];
2525 if (lastChar != '~') {
2526 buf[index++] = '1';
2527 }
2528 buf[index++] = ';'; // modifier separator
2529 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2530 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2531 buf[index++] = '1' + code;
2532 buf[index++] = lastChar; // move ~ (or other last char) to the end
2533 return index;
2534 }
2535 return len;
2536}
2537
2538// Write sequence to buf and return the number of bytes written.
2539static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2540 const DWORD control_key_state, const char* const normal,
2541 const char shifted) {
2542 if (_is_shift_pressed(control_key_state)) {
2543 // Shift is pressed and NumLock is off
2544 if (shifted != '\0') {
2545 buf[0] = shifted;
2546 return sizeof(buf[0]);
2547 } else {
2548 return 0;
2549 }
2550 } else {
2551 // Shift is not pressed and NumLock is off, or,
2552 // Shift is pressed and NumLock is on, in which case we want the
2553 // NumLock and Shift to neutralize each other, thus, we want the normal
2554 // sequence.
2555 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2556 }
2557 // If Shift is not pressed and NumLock is on, a different virtual key code
2558 // is returned by Windows, which can be taken care of by a different case
2559 // statement in _console_read().
2560}
2561
2562// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2563// Standard German. Figure this out at runtime so we know what to output for
2564// Shift-VK_DELETE.
2565static char _get_decimal_char() {
2566 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2567}
2568
2569// Prefix the len bytes in buf with the escape character, and then return the
2570// new buffer length.
2571size_t _escape_prefix(char* const buf, const size_t len) {
2572 // If nothing to prefix, don't do anything. We might be called with
2573 // len == 0, if alt was held down with a dead key which produced nothing.
2574 if (len == 0) {
2575 return 0;
2576 }
2577
2578 memmove(&buf[1], buf, len);
2579 buf[0] = '\x1b';
2580 return len + 1;
2581}
2582
2583// Writes to buffer buf (of length len), returning number of bytes written or
2584// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2585// (as far as I can tell).
2586static int _console_read(const HANDLE console, void* buf, size_t len) {
2587 for (;;) {
2588 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2589 if (key_event == NULL) {
2590 return -1;
2591 }
2592
2593 const WORD vk = key_event->wVirtualKeyCode;
2594 const CHAR ch = key_event->uChar.AsciiChar;
2595 const DWORD control_key_state = _normalize_altgr_control_key_state(
2596 key_event);
2597
2598 // The following emulation code should write the output sequence to
2599 // either seqstr or to seqbuf and seqbuflen.
2600 const char* seqstr = NULL; // NULL terminated C-string
2601 // Enough space for max sequence string below, plus modifiers and/or
2602 // escape prefix.
2603 char seqbuf[16];
2604 size_t seqbuflen = 0; // Space used in seqbuf.
2605
2606#define MATCH(vk, normal) \
2607 case (vk): \
2608 { \
2609 seqstr = (normal); \
2610 } \
2611 break;
2612
2613 // Modifier keys should affect the output sequence.
2614#define MATCH_MODIFIER(vk, normal) \
2615 case (vk): \
2616 { \
2617 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2618 control_key_state, (normal)); \
2619 } \
2620 break;
2621
2622 // The shift key should affect the output sequence.
2623#define MATCH_KEYPAD(vk, normal, shifted) \
2624 case (vk): \
2625 { \
2626 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2627 (shifted)); \
2628 } \
2629 break;
2630
2631 // The shift key and other modifier keys should affect the output
2632 // sequence.
2633#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2634 case (vk): \
2635 { \
2636 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2637 control_key_state, (normal), (shifted)); \
2638 } \
2639 break;
2640
2641#define ESC "\x1b"
2642#define CSI ESC "["
2643#define SS3 ESC "O"
2644
2645 // Only support normal mode, not application mode.
2646
2647 // Enhanced keys:
2648 // * 6-pack: insert, delete, home, end, page up, page down
2649 // * cursor keys: up, down, right, left
2650 // * keypad: divide, enter
2651 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2652 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2653 if (_is_enhanced_key(control_key_state)) {
2654 switch (vk) {
2655 case VK_RETURN: // Enter key on keypad
2656 if (_is_ctrl_pressed(control_key_state)) {
2657 seqstr = "\n";
2658 } else {
2659 seqstr = "\r";
2660 }
2661 break;
2662
2663 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2664 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2665
2666 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2667 // will be fixed soon to match xterm which sends CSI "F" and
2668 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2669 MATCH(VK_END, CSI "F");
2670 MATCH(VK_HOME, CSI "H");
2671
2672 MATCH_MODIFIER(VK_LEFT, CSI "D");
2673 MATCH_MODIFIER(VK_UP, CSI "A");
2674 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2675 MATCH_MODIFIER(VK_DOWN, CSI "B");
2676
2677 MATCH_MODIFIER(VK_INSERT, CSI "2~");
2678 MATCH_MODIFIER(VK_DELETE, CSI "3~");
2679
2680 MATCH(VK_DIVIDE, "/");
2681 }
2682 } else { // Non-enhanced keys:
2683 switch (vk) {
2684 case VK_BACK: // backspace
2685 if (_is_alt_pressed(control_key_state)) {
2686 seqstr = ESC "\x7f";
2687 } else {
2688 seqstr = "\x7f";
2689 }
2690 break;
2691
2692 case VK_TAB:
2693 if (_is_shift_pressed(control_key_state)) {
2694 seqstr = CSI "Z";
2695 } else {
2696 seqstr = "\t";
2697 }
2698 break;
2699
2700 // Number 5 key in keypad when NumLock is off, or if NumLock is
2701 // on and Shift is down.
2702 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2703
2704 case VK_RETURN: // Enter key on main keyboard
2705 if (_is_alt_pressed(control_key_state)) {
2706 seqstr = ESC "\n";
2707 } else if (_is_ctrl_pressed(control_key_state)) {
2708 seqstr = "\n";
2709 } else {
2710 seqstr = "\r";
2711 }
2712 break;
2713
2714 // VK_ESCAPE: Don't do any special handling. The OS uses many
2715 // of the sequences with Escape and many of the remaining
2716 // sequences don't produce bKeyDown messages, only !bKeyDown
2717 // for whatever reason.
2718
2719 case VK_SPACE:
2720 if (_is_alt_pressed(control_key_state)) {
2721 seqstr = ESC " ";
2722 } else if (_is_ctrl_pressed(control_key_state)) {
2723 seqbuf[0] = '\0'; // NULL char
2724 seqbuflen = 1;
2725 } else {
2726 seqstr = " ";
2727 }
2728 break;
2729
2730 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2731 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
2732
2733 MATCH_KEYPAD(VK_END, CSI "4~", "1");
2734 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2735
2736 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
2737 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
2738 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2739 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
2740
2741 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2742 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2743 _get_decimal_char());
2744
2745 case 0x30: // 0
2746 case 0x31: // 1
2747 case 0x39: // 9
2748 case VK_OEM_1: // ;:
2749 case VK_OEM_PLUS: // =+
2750 case VK_OEM_COMMA: // ,<
2751 case VK_OEM_PERIOD: // .>
2752 case VK_OEM_7: // '"
2753 case VK_OEM_102: // depends on keyboard, could be <> or \|
2754 case VK_OEM_2: // /?
2755 case VK_OEM_3: // `~
2756 case VK_OEM_4: // [{
2757 case VK_OEM_5: // \|
2758 case VK_OEM_6: // ]}
2759 {
2760 seqbuflen = _get_control_character(seqbuf, key_event,
2761 control_key_state);
2762
2763 if (_is_alt_pressed(control_key_state)) {
2764 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2765 }
2766 }
2767 break;
2768
2769 case 0x32: // 2
2770 case 0x36: // 6
2771 case VK_OEM_MINUS: // -_
2772 {
2773 seqbuflen = _get_control_character(seqbuf, key_event,
2774 control_key_state);
2775
2776 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2777 // prefix with escape.
2778 if (_is_alt_pressed(control_key_state) &&
2779 !(_is_ctrl_pressed(control_key_state) &&
2780 !_is_shift_pressed(control_key_state))) {
2781 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2782 }
2783 }
2784 break;
2785
2786 case 0x33: // 3
2787 case 0x34: // 4
2788 case 0x35: // 5
2789 case 0x37: // 7
2790 case 0x38: // 8
2791 {
2792 seqbuflen = _get_control_character(seqbuf, key_event,
2793 control_key_state);
2794
2795 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2796 // prefix with escape.
2797 if (_is_alt_pressed(control_key_state) &&
2798 !(_is_ctrl_pressed(control_key_state) &&
2799 !_is_shift_pressed(control_key_state))) {
2800 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2801 }
2802 }
2803 break;
2804
2805 case 0x41: // a
2806 case 0x42: // b
2807 case 0x43: // c
2808 case 0x44: // d
2809 case 0x45: // e
2810 case 0x46: // f
2811 case 0x47: // g
2812 case 0x48: // h
2813 case 0x49: // i
2814 case 0x4a: // j
2815 case 0x4b: // k
2816 case 0x4c: // l
2817 case 0x4d: // m
2818 case 0x4e: // n
2819 case 0x4f: // o
2820 case 0x50: // p
2821 case 0x51: // q
2822 case 0x52: // r
2823 case 0x53: // s
2824 case 0x54: // t
2825 case 0x55: // u
2826 case 0x56: // v
2827 case 0x57: // w
2828 case 0x58: // x
2829 case 0x59: // y
2830 case 0x5a: // z
2831 {
2832 seqbuflen = _get_non_alt_char(seqbuf, key_event,
2833 control_key_state);
2834
2835 // If Alt is pressed, then prefix with escape.
2836 if (_is_alt_pressed(control_key_state)) {
2837 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2838 }
2839 }
2840 break;
2841
2842 // These virtual key codes are generated by the keys on the
2843 // keypad *when NumLock is on* and *Shift is up*.
2844 MATCH(VK_NUMPAD0, "0");
2845 MATCH(VK_NUMPAD1, "1");
2846 MATCH(VK_NUMPAD2, "2");
2847 MATCH(VK_NUMPAD3, "3");
2848 MATCH(VK_NUMPAD4, "4");
2849 MATCH(VK_NUMPAD5, "5");
2850 MATCH(VK_NUMPAD6, "6");
2851 MATCH(VK_NUMPAD7, "7");
2852 MATCH(VK_NUMPAD8, "8");
2853 MATCH(VK_NUMPAD9, "9");
2854
2855 MATCH(VK_MULTIPLY, "*");
2856 MATCH(VK_ADD, "+");
2857 MATCH(VK_SUBTRACT, "-");
2858 // VK_DECIMAL is generated by the . key on the keypad *when
2859 // NumLock is on* and *Shift is up* and the sequence is not
2860 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
2861 // Windows Security screen to come up).
2862 case VK_DECIMAL:
2863 // U.S. English uses '.', Germany German uses ','.
2864 seqbuflen = _get_non_control_char(seqbuf, key_event,
2865 control_key_state);
2866 break;
2867
2868 MATCH_MODIFIER(VK_F1, SS3 "P");
2869 MATCH_MODIFIER(VK_F2, SS3 "Q");
2870 MATCH_MODIFIER(VK_F3, SS3 "R");
2871 MATCH_MODIFIER(VK_F4, SS3 "S");
2872 MATCH_MODIFIER(VK_F5, CSI "15~");
2873 MATCH_MODIFIER(VK_F6, CSI "17~");
2874 MATCH_MODIFIER(VK_F7, CSI "18~");
2875 MATCH_MODIFIER(VK_F8, CSI "19~");
2876 MATCH_MODIFIER(VK_F9, CSI "20~");
2877 MATCH_MODIFIER(VK_F10, CSI "21~");
2878 MATCH_MODIFIER(VK_F11, CSI "23~");
2879 MATCH_MODIFIER(VK_F12, CSI "24~");
2880
2881 MATCH_MODIFIER(VK_F13, CSI "25~");
2882 MATCH_MODIFIER(VK_F14, CSI "26~");
2883 MATCH_MODIFIER(VK_F15, CSI "28~");
2884 MATCH_MODIFIER(VK_F16, CSI "29~");
2885 MATCH_MODIFIER(VK_F17, CSI "31~");
2886 MATCH_MODIFIER(VK_F18, CSI "32~");
2887 MATCH_MODIFIER(VK_F19, CSI "33~");
2888 MATCH_MODIFIER(VK_F20, CSI "34~");
2889
2890 // MATCH_MODIFIER(VK_F21, ???);
2891 // MATCH_MODIFIER(VK_F22, ???);
2892 // MATCH_MODIFIER(VK_F23, ???);
2893 // MATCH_MODIFIER(VK_F24, ???);
2894 }
2895 }
2896
2897#undef MATCH
2898#undef MATCH_MODIFIER
2899#undef MATCH_KEYPAD
2900#undef MATCH_MODIFIER_KEYPAD
2901#undef ESC
2902#undef CSI
2903#undef SS3
2904
2905 const char* out;
2906 size_t outlen;
2907
2908 // Check for output in any of:
2909 // * seqstr is set (and strlen can be used to determine the length).
2910 // * seqbuf and seqbuflen are set
2911 // Fallback to ch from Windows.
2912 if (seqstr != NULL) {
2913 out = seqstr;
2914 outlen = strlen(seqstr);
2915 } else if (seqbuflen > 0) {
2916 out = seqbuf;
2917 outlen = seqbuflen;
2918 } else if (ch != '\0') {
2919 // Use whatever Windows told us it is.
2920 seqbuf[0] = ch;
2921 seqbuflen = 1;
2922 out = seqbuf;
2923 outlen = seqbuflen;
2924 } else {
2925 // No special handling for the virtual key code and Windows isn't
2926 // telling us a character code, then we don't know how to translate
2927 // the key press.
2928 //
2929 // Consume the input and 'continue' to cause us to get a new key
2930 // event.
2931 D("_console_read: unknown virtual key code: %d, enhanced: %s\n",
2932 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
2933 key_event->wRepeatCount = 0;
2934 continue;
2935 }
2936
2937 int bytesRead = 0;
2938
2939 // put output wRepeatCount times into buf/len
2940 while (key_event->wRepeatCount > 0) {
2941 if (len >= outlen) {
2942 // Write to buf/len
2943 memcpy(buf, out, outlen);
2944 buf = (void*)((char*)buf + outlen);
2945 len -= outlen;
2946 bytesRead += outlen;
2947
2948 // consume the input
2949 --key_event->wRepeatCount;
2950 } else {
2951 // Not enough space, so just leave it in _win32_input_record
2952 // for a subsequent retrieval.
2953 if (bytesRead == 0) {
2954 // We didn't write anything because there wasn't enough
2955 // space to even write one sequence. This should never
2956 // happen if the caller uses sensible buffer sizes
2957 // (i.e. >= maximum sequence length which is probably a
2958 // few bytes long).
2959 D("_console_read: no buffer space to write one sequence; "
2960 "buffer: %ld, sequence: %ld\n", (long)len,
2961 (long)outlen);
2962 errno = ENOMEM;
2963 return -1;
2964 } else {
2965 // Stop trying to write to buf/len, just return whatever
2966 // we wrote so far.
2967 break;
2968 }
2969 }
2970 }
2971
2972 return bytesRead;
2973 }
2974}
2975
2976static DWORD _old_console_mode; // previous GetConsoleMode() result
2977static HANDLE _console_handle; // when set, console mode should be restored
2978
2979void stdin_raw_init(const int fd) {
2980 if (STDIN_FILENO == fd) {
2981 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
2982 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
2983 return;
2984 }
2985
2986 if (GetFileType(in) != FILE_TYPE_CHAR) {
2987 // stdin might be a file or pipe.
2988 return;
2989 }
2990
2991 if (!GetConsoleMode(in, &_old_console_mode)) {
2992 // If GetConsoleMode() fails, stdin is probably is not a console.
2993 return;
2994 }
2995
2996 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2997 // calling the process Ctrl-C routine (configured by
2998 // SetConsoleCtrlHandler()).
2999 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3000 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3001 // flag also seems necessary to have proper line-ending processing.
3002 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3003 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3004 // This really should not fail.
3005 D("stdin_raw_init: SetConsoleMode() failure, error %ld\n",
3006 GetLastError());
3007 }
3008
3009 // Once this is set, it means that stdin has been configured for
3010 // reading from and that the old console mode should be restored later.
3011 _console_handle = in;
3012
3013 // Note that we don't need to configure C Runtime line-ending
3014 // translation because _console_read() does not call the C Runtime to
3015 // read from the console.
3016 }
3017}
3018
3019void stdin_raw_restore(const int fd) {
3020 if (STDIN_FILENO == fd) {
3021 if (_console_handle != NULL) {
3022 const HANDLE in = _console_handle;
3023 _console_handle = NULL; // clear state
3024
3025 if (!SetConsoleMode(in, _old_console_mode)) {
3026 // This really should not fail.
3027 D("stdin_raw_restore: SetConsoleMode() failure, error %ld\n",
3028 GetLastError());
3029 }
3030 }
3031 }
3032}
3033
Spencer Low3a2421b2015-05-22 20:09:06 -07003034// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003035int unix_read(int fd, void* buf, size_t len) {
3036 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3037 // If it is a request to read from stdin, and stdin_raw_init() has been
3038 // called, and it successfully configured the console, then read from
3039 // the console using Win32 console APIs and partially emulate a unix
3040 // terminal.
3041 return _console_read(_console_handle, buf, len);
3042 } else {
3043 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003044 // can do LF/CR translation (which is overridable with _setmode()).
3045 // Undefine the macro that is set in sysdeps.h which bans calls to
3046 // plain read() in favor of unix_read() or adb_read().
3047#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003048#undef read
3049 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003050#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003051 }
3052}