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