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