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