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