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