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