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