sysdeps_win32.cpp revision 87e97ee305627f01ad2b17220fd9a7aa2c3bef30
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 <memory>
29#include <string>
30#include <unordered_map>
31
32#include <cutils/sockets.h>
33
34#include <base/logging.h>
35#include <base/stringprintf.h>
36#include <base/strings.h>
37
38#include "adb.h"
39
40extern void fatal(const char *fmt, ...);
41
42/* forward declarations */
43
44typedef const struct FHClassRec_* FHClass;
45typedef struct FHRec_* FH;
46typedef struct EventHookRec_* EventHook;
47
48typedef struct FHClassRec_ {
49    void (*_fh_init)(FH);
50    int (*_fh_close)(FH);
51    int (*_fh_lseek)(FH, int, int);
52    int (*_fh_read)(FH, void*, int);
53    int (*_fh_write)(FH, const void*, int);
54    void (*_fh_hook)(FH, int, EventHook);
55} FHClassRec;
56
57static void _fh_file_init(FH);
58static int _fh_file_close(FH);
59static int _fh_file_lseek(FH, int, int);
60static int _fh_file_read(FH, void*, int);
61static int _fh_file_write(FH, const void*, int);
62static void _fh_file_hook(FH, int, EventHook);
63
64static const FHClassRec _fh_file_class = {
65    _fh_file_init,
66    _fh_file_close,
67    _fh_file_lseek,
68    _fh_file_read,
69    _fh_file_write,
70    _fh_file_hook
71};
72
73static void _fh_socket_init(FH);
74static int _fh_socket_close(FH);
75static int _fh_socket_lseek(FH, int, int);
76static int _fh_socket_read(FH, void*, int);
77static int _fh_socket_write(FH, const void*, int);
78static void _fh_socket_hook(FH, int, EventHook);
79
80static const FHClassRec _fh_socket_class = {
81    _fh_socket_init,
82    _fh_socket_close,
83    _fh_socket_lseek,
84    _fh_socket_read,
85    _fh_socket_write,
86    _fh_socket_hook
87};
88
89#define assert(cond)  do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
90
91std::string SystemErrorCodeToString(const DWORD error_code) {
92  const int kErrorMessageBufferSize = 256;
93  WCHAR msgbuf[kErrorMessageBufferSize];
94  DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
95  DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf,
96                             arraysize(msgbuf), nullptr);
97  if (len == 0) {
98    return android::base::StringPrintf(
99        "Error (%lu) while retrieving error. (%lu)", GetLastError(),
100        error_code);
101  }
102
103  // Convert UTF-16 to UTF-8.
104  std::string msg(narrow(msgbuf));
105  // Messages returned by the system end with line breaks.
106  msg = android::base::Trim(msg);
107  // There are many Windows error messages compared to POSIX, so include the
108  // numeric error code for easier, quicker, accurate identification. Use
109  // decimal instead of hex because there are decimal ranges like 10000-11999
110  // for Winsock.
111  android::base::StringAppendF(&msg, " (%lu)", error_code);
112  return msg;
113}
114
115/**************************************************************************/
116/**************************************************************************/
117/*****                                                                *****/
118/*****      replaces libs/cutils/load_file.c                          *****/
119/*****                                                                *****/
120/**************************************************************************/
121/**************************************************************************/
122
123void *load_file(const char *fn, unsigned *_sz)
124{
125    HANDLE    file;
126    char     *data;
127    DWORD     file_size;
128
129    file = CreateFileW( widen(fn).c_str(),
130                        GENERIC_READ,
131                        FILE_SHARE_READ,
132                        NULL,
133                        OPEN_EXISTING,
134                        0,
135                        NULL );
136
137    if (file == INVALID_HANDLE_VALUE)
138        return NULL;
139
140    file_size = GetFileSize( file, NULL );
141    data      = NULL;
142
143    if (file_size > 0) {
144        data = (char*) malloc( file_size + 1 );
145        if (data == NULL) {
146            D("load_file: could not allocate %ld bytes\n", file_size );
147            file_size = 0;
148        } else {
149            DWORD  out_bytes;
150
151            if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
152                 out_bytes != file_size )
153            {
154                D("load_file: could not read %ld bytes from '%s'\n", file_size, fn);
155                free(data);
156                data      = NULL;
157                file_size = 0;
158            }
159        }
160    }
161    CloseHandle( file );
162
163    *_sz = (unsigned) file_size;
164    return  data;
165}
166
167/**************************************************************************/
168/**************************************************************************/
169/*****                                                                *****/
170/*****    common file descriptor handling                             *****/
171/*****                                                                *****/
172/**************************************************************************/
173/**************************************************************************/
174
175/* used to emulate unix-domain socket pairs */
176typedef struct SocketPairRec_*  SocketPair;
177
178typedef struct FHRec_
179{
180    FHClass    clazz;
181    int        used;
182    int        eof;
183    union {
184        HANDLE      handle;
185        SOCKET      socket;
186        SocketPair  pair;
187    } u;
188
189    HANDLE    event;
190    int       mask;
191
192    char  name[32];
193
194} FHRec;
195
196#define  fh_handle  u.handle
197#define  fh_socket  u.socket
198#define  fh_pair    u.pair
199
200#define  WIN32_FH_BASE    100
201
202#define  WIN32_MAX_FHS    128
203
204static adb_mutex_t   _win32_lock;
205static  FHRec        _win32_fhs[ WIN32_MAX_FHS ];
206static  int          _win32_fh_next;  // where to start search for free FHRec
207
208static FH
209_fh_from_int( int   fd, const char*   func )
210{
211    FH  f;
212
213    fd -= WIN32_FH_BASE;
214
215    if (fd < 0 || fd >= WIN32_MAX_FHS) {
216        D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
217           func );
218        errno = EBADF;
219        return NULL;
220    }
221
222    f = &_win32_fhs[fd];
223
224    if (f->used == 0) {
225        D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
226           func );
227        errno = EBADF;
228        return NULL;
229    }
230
231    return f;
232}
233
234
235static int
236_fh_to_int( FH  f )
237{
238    if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
239        return (int)(f - _win32_fhs) + WIN32_FH_BASE;
240
241    return -1;
242}
243
244static FH
245_fh_alloc( FHClass  clazz )
246{
247    FH   f = NULL;
248
249    adb_mutex_lock( &_win32_lock );
250
251    // Search entire array, starting from _win32_fh_next.
252    for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
253        // Keep incrementing _win32_fh_next to avoid giving out an index that
254        // was recently closed, to try to avoid use-after-free.
255        const int index = _win32_fh_next++;
256        // Handle wrap-around of _win32_fh_next.
257        if (_win32_fh_next == WIN32_MAX_FHS) {
258            _win32_fh_next = 0;
259        }
260        if (_win32_fhs[index].clazz == NULL) {
261            f = &_win32_fhs[index];
262            goto Exit;
263        }
264    }
265    D( "_fh_alloc: no more free file descriptors\n" );
266    errno = EMFILE;   // Too many open files
267Exit:
268    if (f) {
269        f->clazz   = clazz;
270        f->used    = 1;
271        f->eof     = 0;
272        f->name[0] = '\0';
273        clazz->_fh_init(f);
274    }
275    adb_mutex_unlock( &_win32_lock );
276    return f;
277}
278
279
280static int
281_fh_close( FH   f )
282{
283    // Use lock so that closing only happens once and so that _fh_alloc can't
284    // allocate a FH that we're in the middle of closing.
285    adb_mutex_lock(&_win32_lock);
286    if (f->used) {
287        f->clazz->_fh_close( f );
288        f->name[0] = '\0';
289        f->eof     = 0;
290        f->used    = 0;
291        f->clazz   = NULL;
292    }
293    adb_mutex_unlock(&_win32_lock);
294    return 0;
295}
296
297// Deleter for unique_fh.
298class fh_deleter {
299 public:
300  void operator()(struct FHRec_* fh) {
301    // We're called from a destructor and destructors should not overwrite
302    // errno because callers may do:
303    //   errno = EBLAH;
304    //   return -1; // calls destructor, which should not overwrite errno
305    const int saved_errno = errno;
306    _fh_close(fh);
307    errno = saved_errno;
308  }
309};
310
311// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
312typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
313
314/**************************************************************************/
315/**************************************************************************/
316/*****                                                                *****/
317/*****    file-based descriptor handling                              *****/
318/*****                                                                *****/
319/**************************************************************************/
320/**************************************************************************/
321
322static void _fh_file_init( FH  f ) {
323    f->fh_handle = INVALID_HANDLE_VALUE;
324}
325
326static int _fh_file_close( FH  f ) {
327    CloseHandle( f->fh_handle );
328    f->fh_handle = INVALID_HANDLE_VALUE;
329    return 0;
330}
331
332static int _fh_file_read( FH  f,  void*  buf, int   len ) {
333    DWORD  read_bytes;
334
335    if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
336        D( "adb_read: could not read %d bytes from %s\n", len, f->name );
337        errno = EIO;
338        return -1;
339    } else if (read_bytes < (DWORD)len) {
340        f->eof = 1;
341    }
342    return (int)read_bytes;
343}
344
345static int _fh_file_write( FH  f,  const void*  buf, int   len ) {
346    DWORD  wrote_bytes;
347
348    if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
349        D( "adb_file_write: could not write %d bytes from %s\n", len, f->name );
350        errno = EIO;
351        return -1;
352    } else if (wrote_bytes < (DWORD)len) {
353        f->eof = 1;
354    }
355    return  (int)wrote_bytes;
356}
357
358static int _fh_file_lseek( FH  f, int  pos, int  origin ) {
359    DWORD  method;
360    DWORD  result;
361
362    switch (origin)
363    {
364        case SEEK_SET:  method = FILE_BEGIN; break;
365        case SEEK_CUR:  method = FILE_CURRENT; break;
366        case SEEK_END:  method = FILE_END; break;
367        default:
368            errno = EINVAL;
369            return -1;
370    }
371
372    result = SetFilePointer( f->fh_handle, pos, NULL, method );
373    if (result == INVALID_SET_FILE_POINTER) {
374        errno = EIO;
375        return -1;
376    } else {
377        f->eof = 0;
378    }
379    return (int)result;
380}
381
382
383/**************************************************************************/
384/**************************************************************************/
385/*****                                                                *****/
386/*****    file-based descriptor handling                              *****/
387/*****                                                                *****/
388/**************************************************************************/
389/**************************************************************************/
390
391int  adb_open(const char*  path, int  options)
392{
393    FH  f;
394
395    DWORD  desiredAccess       = 0;
396    DWORD  shareMode           = FILE_SHARE_READ | FILE_SHARE_WRITE;
397
398    switch (options) {
399        case O_RDONLY:
400            desiredAccess = GENERIC_READ;
401            break;
402        case O_WRONLY:
403            desiredAccess = GENERIC_WRITE;
404            break;
405        case O_RDWR:
406            desiredAccess = GENERIC_READ | GENERIC_WRITE;
407            break;
408        default:
409            D("adb_open: invalid options (0x%0x)\n", options);
410            errno = EINVAL;
411            return -1;
412    }
413
414    f = _fh_alloc( &_fh_file_class );
415    if ( !f ) {
416        return -1;
417    }
418
419    f->fh_handle = CreateFileW( widen(path).c_str(), desiredAccess, shareMode,
420                                NULL, OPEN_EXISTING, 0, NULL );
421
422    if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
423        const DWORD err = GetLastError();
424        _fh_close(f);
425        D( "adb_open: could not open '%s': ", path );
426        switch (err) {
427            case ERROR_FILE_NOT_FOUND:
428                D( "file not found\n" );
429                errno = ENOENT;
430                return -1;
431
432            case ERROR_PATH_NOT_FOUND:
433                D( "path not found\n" );
434                errno = ENOTDIR;
435                return -1;
436
437            default:
438                D( "unknown error: %s\n",
439                   SystemErrorCodeToString( err ).c_str() );
440                errno = ENOENT;
441                return -1;
442        }
443    }
444
445    snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
446    D( "adb_open: '%s' => fd %d\n", path, _fh_to_int(f) );
447    return _fh_to_int(f);
448}
449
450/* ignore mode on Win32 */
451int  adb_creat(const char*  path, int  mode)
452{
453    FH  f;
454
455    f = _fh_alloc( &_fh_file_class );
456    if ( !f ) {
457        return -1;
458    }
459
460    f->fh_handle = CreateFileW( widen(path).c_str(), GENERIC_WRITE,
461                                FILE_SHARE_READ | FILE_SHARE_WRITE,
462                                NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
463                                NULL );
464
465    if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
466        const DWORD err = GetLastError();
467        _fh_close(f);
468        D( "adb_creat: could not open '%s': ", path );
469        switch (err) {
470            case ERROR_FILE_NOT_FOUND:
471                D( "file not found\n" );
472                errno = ENOENT;
473                return -1;
474
475            case ERROR_PATH_NOT_FOUND:
476                D( "path not found\n" );
477                errno = ENOTDIR;
478                return -1;
479
480            default:
481                D( "unknown error: %s\n",
482                   SystemErrorCodeToString( err ).c_str() );
483                errno = ENOENT;
484                return -1;
485        }
486    }
487    snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
488    D( "adb_creat: '%s' => fd %d\n", path, _fh_to_int(f) );
489    return _fh_to_int(f);
490}
491
492
493int  adb_read(int  fd, void* buf, int len)
494{
495    FH     f = _fh_from_int(fd, __func__);
496
497    if (f == NULL) {
498        return -1;
499    }
500
501    return f->clazz->_fh_read( f, buf, len );
502}
503
504
505int  adb_write(int  fd, const void*  buf, int  len)
506{
507    FH     f = _fh_from_int(fd, __func__);
508
509    if (f == NULL) {
510        return -1;
511    }
512
513    return f->clazz->_fh_write(f, buf, len);
514}
515
516
517int  adb_lseek(int  fd, int  pos, int  where)
518{
519    FH     f = _fh_from_int(fd, __func__);
520
521    if (!f) {
522        return -1;
523    }
524
525    return f->clazz->_fh_lseek(f, pos, where);
526}
527
528
529int  adb_close(int  fd)
530{
531    FH   f = _fh_from_int(fd, __func__);
532
533    if (!f) {
534        return -1;
535    }
536
537    D( "adb_close: %s\n", f->name);
538    _fh_close(f);
539    return 0;
540}
541
542/**************************************************************************/
543/**************************************************************************/
544/*****                                                                *****/
545/*****    socket-based file descriptors                               *****/
546/*****                                                                *****/
547/**************************************************************************/
548/**************************************************************************/
549
550#undef setsockopt
551
552static void _socket_set_errno( const DWORD err ) {
553    // The Windows C Runtime (MSVCRT.DLL) strerror() does not support a lot of
554    // POSIX and socket error codes, so this can only meaningfully map so much.
555    switch ( err ) {
556    case 0:              errno = 0; break;
557    case WSAEWOULDBLOCK: errno = EAGAIN; break;
558    case WSAEINTR:       errno = EINTR; break;
559    case WSAEFAULT:      errno = EFAULT; break;
560    case WSAEINVAL:      errno = EINVAL; break;
561    case WSAEMFILE:      errno = EMFILE; break;
562    default:
563        errno = EINVAL;
564        D( "_socket_set_errno: mapping Windows error code %lu to errno %d\n",
565           err, errno );
566    }
567}
568
569static void _fh_socket_init( FH  f ) {
570    f->fh_socket = INVALID_SOCKET;
571    f->event     = WSACreateEvent();
572    if (f->event == WSA_INVALID_EVENT) {
573        D("WSACreateEvent failed: %s\n",
574          SystemErrorCodeToString(WSAGetLastError()).c_str());
575
576        // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
577        // on failure, instead of NULL which is what Windows really returns on
578        // error. It might be better to change all the other code to look for
579        // NULL, but that is a much riskier change.
580        f->event = INVALID_HANDLE_VALUE;
581    }
582    f->mask      = 0;
583}
584
585static int _fh_socket_close( FH  f ) {
586    if (f->fh_socket != INVALID_SOCKET) {
587        /* gently tell any peer that we're closing the socket */
588        if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
589            // If the socket is not connected, this returns an error. We want to
590            // minimize logging spam, so don't log these errors for now.
591#if 0
592            D("socket shutdown failed: %s\n",
593              SystemErrorCodeToString(WSAGetLastError()).c_str());
594#endif
595        }
596        if (closesocket(f->fh_socket) == SOCKET_ERROR) {
597            D("closesocket failed: %s\n",
598              SystemErrorCodeToString(WSAGetLastError()).c_str());
599        }
600        f->fh_socket = INVALID_SOCKET;
601    }
602    if (f->event != NULL) {
603        if (!CloseHandle(f->event)) {
604            D("CloseHandle failed: %s\n",
605              SystemErrorCodeToString(GetLastError()).c_str());
606        }
607        f->event = NULL;
608    }
609    f->mask = 0;
610    return 0;
611}
612
613static int _fh_socket_lseek( FH  f, int pos, int origin ) {
614    errno = EPIPE;
615    return -1;
616}
617
618static int _fh_socket_read(FH f, void* buf, int len) {
619    int  result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
620    if (result == SOCKET_ERROR) {
621        const DWORD err = WSAGetLastError();
622        D("recv fd %d failed: %s\n", _fh_to_int(f),
623          SystemErrorCodeToString(err).c_str());
624        _socket_set_errno(err);
625        result = -1;
626    }
627    return  result;
628}
629
630static int _fh_socket_write(FH f, const void* buf, int len) {
631    int  result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
632    if (result == SOCKET_ERROR) {
633        const DWORD err = WSAGetLastError();
634        D("send fd %d failed: %s\n", _fh_to_int(f),
635          SystemErrorCodeToString(err).c_str());
636        _socket_set_errno(err);
637        result = -1;
638    }
639    return result;
640}
641
642/**************************************************************************/
643/**************************************************************************/
644/*****                                                                *****/
645/*****    replacement for libs/cutils/socket_xxxx.c                   *****/
646/*****                                                                *****/
647/**************************************************************************/
648/**************************************************************************/
649
650#include <winsock2.h>
651
652static int  _winsock_init;
653
654static void
655_init_winsock( void )
656{
657    // TODO: Multiple threads calling this may potentially cause multiple calls
658    // to WSAStartup() which offers no real benefit.
659    if (!_winsock_init) {
660        WSADATA  wsaData;
661        int      rc = WSAStartup( MAKEWORD(2,2), &wsaData);
662        if (rc != 0) {
663            fatal( "adb: could not initialize Winsock: %s",
664                   SystemErrorCodeToString( rc ).c_str());
665        }
666        _winsock_init = 1;
667
668        // Note that we do not call atexit() to register WSACleanup to be called
669        // at normal process termination because:
670        // 1) When exit() is called, there are still threads actively using
671        //    Winsock because we don't cleanly shutdown all threads, so it
672        //    doesn't make sense to call WSACleanup() and may cause problems
673        //    with those threads.
674        // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
675        //    calls WSACleanup() which tries to unload a DLL, which tries to
676        //    grab the LoaderLock. This conflicts with the device_poll_thread
677        //    which holds the LoaderLock because AdbWinApi.dll calls
678        //    setupapi.dll which tries to load wintrust.dll which tries to load
679        //    crypt32.dll which calls atexit() which tries to acquire the C
680        //    Runtime lock that the other thread holds.
681    }
682}
683
684int network_loopback_client(int port, int type, std::string* error) {
685    struct sockaddr_in addr;
686    SOCKET  s;
687
688    unique_fh  f(_fh_alloc(&_fh_socket_class));
689    if (!f) {
690        *error = strerror(errno);
691        return -1;
692    }
693
694    if (!_winsock_init)
695        _init_winsock();
696
697    memset(&addr, 0, sizeof(addr));
698    addr.sin_family = AF_INET;
699    addr.sin_port = htons(port);
700    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
701
702    s = socket(AF_INET, type, 0);
703    if(s == INVALID_SOCKET) {
704        *error = SystemErrorCodeToString(WSAGetLastError());
705        D("could not create socket: %s\n", error->c_str());
706        return -1;
707    }
708    f->fh_socket = s;
709
710    if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
711        *error = SystemErrorCodeToString(WSAGetLastError());
712        D("could not connect to %s:%d: %s\n",
713          type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
714        return -1;
715    }
716
717    const int fd = _fh_to_int(f.get());
718    snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
719              type != SOCK_STREAM ? "udp:" : "", port );
720    D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
721       fd );
722    f.release();
723    return fd;
724}
725
726#define LISTEN_BACKLOG 4
727
728// interface_address is INADDR_LOOPBACK or INADDR_ANY.
729static int _network_server(int port, int type, u_long interface_address,
730                           std::string* error) {
731    struct sockaddr_in addr;
732    SOCKET  s;
733    int  n;
734
735    unique_fh   f(_fh_alloc(&_fh_socket_class));
736    if (!f) {
737        *error = strerror(errno);
738        return -1;
739    }
740
741    if (!_winsock_init)
742        _init_winsock();
743
744    memset(&addr, 0, sizeof(addr));
745    addr.sin_family = AF_INET;
746    addr.sin_port = htons(port);
747    addr.sin_addr.s_addr = htonl(interface_address);
748
749    // TODO: Consider using dual-stack socket that can simultaneously listen on
750    // IPv4 and IPv6.
751    s = socket(AF_INET, type, 0);
752    if (s == INVALID_SOCKET) {
753        *error = SystemErrorCodeToString(WSAGetLastError());
754        D("could not create socket: %s\n", error->c_str());
755        return -1;
756    }
757
758    f->fh_socket = s;
759
760    n = 1;
761    if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
762                   sizeof(n)) == SOCKET_ERROR) {
763        *error = SystemErrorCodeToString(WSAGetLastError());
764        D("setsockopt level %d optname %d failed: %s\n",
765          SOL_SOCKET, SO_EXCLUSIVEADDRUSE, error->c_str());
766        return -1;
767    }
768
769    if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
770        *error = SystemErrorCodeToString(WSAGetLastError());
771        D("could not bind to %s:%d: %s\n",
772          type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
773        return -1;
774    }
775    if (type == SOCK_STREAM) {
776        if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
777            *error = SystemErrorCodeToString(WSAGetLastError());
778            D("could not listen on %s:%d: %s\n",
779              type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
780            return -1;
781        }
782    }
783    const int fd = _fh_to_int(f.get());
784    snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
785              interface_address == INADDR_LOOPBACK ? "lo" : "any",
786              type != SOCK_STREAM ? "udp:" : "", port );
787    D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
788       fd );
789    f.release();
790    return fd;
791}
792
793int network_loopback_server(int port, int type, std::string* error) {
794    return _network_server(port, type, INADDR_LOOPBACK, error);
795}
796
797int network_inaddr_any_server(int port, int type, std::string* error) {
798    return _network_server(port, type, INADDR_ANY, error);
799}
800
801int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
802    unique_fh f(_fh_alloc(&_fh_socket_class));
803    if (!f) {
804        *error = strerror(errno);
805        return -1;
806    }
807
808    if (!_winsock_init) _init_winsock();
809
810    struct addrinfo hints;
811    memset(&hints, 0, sizeof(hints));
812    hints.ai_family = AF_UNSPEC;
813    hints.ai_socktype = type;
814
815    char port_str[16];
816    snprintf(port_str, sizeof(port_str), "%d", port);
817
818    struct addrinfo* addrinfo_ptr = nullptr;
819
820#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
821    // TODO: When the Android SDK tools increases the Windows system
822    // requirements >= WinXP SP2, switch to GetAddrInfoW(widen(host).c_str()).
823#else
824    // Otherwise, keep using getaddrinfo(), or do runtime API detection
825    // with GetProcAddress("GetAddrInfoW").
826#endif
827    if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
828        *error = SystemErrorCodeToString(WSAGetLastError());
829        D("could not resolve host '%s' and port %s: %s\n", host.c_str(),
830          port_str, error->c_str());
831        return -1;
832    }
833    std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
834        addrinfo(addrinfo_ptr, freeaddrinfo);
835    addrinfo_ptr = nullptr;
836
837    // TODO: Try all the addresses if there's more than one? This just uses
838    // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
839    // which tries all addresses, takes a timeout and more.
840    SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
841                      addrinfo->ai_protocol);
842    if(s == INVALID_SOCKET) {
843        *error = SystemErrorCodeToString(WSAGetLastError());
844        D("could not create socket: %s\n", error->c_str());
845        return -1;
846    }
847    f->fh_socket = s;
848
849    // TODO: Implement timeouts for Windows. Seems like the default in theory
850    // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
851    if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
852        *error = SystemErrorCodeToString(WSAGetLastError());
853        D("could not connect to %s:%s:%s: %s\n",
854          type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
855          error->c_str());
856        return -1;
857    }
858
859    const int fd = _fh_to_int(f.get());
860    snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
861              type != SOCK_STREAM ? "udp:" : "", port );
862    D( "host '%s' port %d type %s => fd %d\n", host.c_str(), port,
863       type != SOCK_STREAM ? "udp" : "tcp", fd );
864    f.release();
865    return fd;
866}
867
868#undef accept
869int  adb_socket_accept(int  serverfd, struct sockaddr*  addr, socklen_t  *addrlen)
870{
871    FH   serverfh = _fh_from_int(serverfd, __func__);
872
873    if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
874        D("adb_socket_accept: invalid fd %d\n", serverfd);
875        errno = EBADF;
876        return -1;
877    }
878
879    unique_fh fh(_fh_alloc( &_fh_socket_class ));
880    if (!fh) {
881        PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
882                       "descriptor";
883        return -1;
884    }
885
886    fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
887    if (fh->fh_socket == INVALID_SOCKET) {
888        const DWORD err = WSAGetLastError();
889        LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
890                      " failed: " + SystemErrorCodeToString(err);
891        _socket_set_errno( err );
892        return -1;
893    }
894
895    const int fd = _fh_to_int(fh.get());
896    snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
897    D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, fd );
898    fh.release();
899    return  fd;
900}
901
902
903int  adb_setsockopt( int  fd, int  level, int  optname, const void*  optval, socklen_t  optlen )
904{
905    FH   fh = _fh_from_int(fd, __func__);
906
907    if ( !fh || fh->clazz != &_fh_socket_class ) {
908        D("adb_setsockopt: invalid fd %d\n", fd);
909        errno = EBADF;
910        return -1;
911    }
912    int result = setsockopt( fh->fh_socket, level, optname,
913                             reinterpret_cast<const char*>(optval), optlen );
914    if ( result == SOCKET_ERROR ) {
915        const DWORD err = WSAGetLastError();
916        D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
917           "failed: %s\n", fd, level, optname,
918           SystemErrorCodeToString(err).c_str() );
919        _socket_set_errno( err );
920        result = -1;
921    }
922    return result;
923}
924
925
926int  adb_shutdown(int  fd)
927{
928    FH   f = _fh_from_int(fd, __func__);
929
930    if (!f || f->clazz != &_fh_socket_class) {
931        D("adb_shutdown: invalid fd %d\n", fd);
932        errno = EBADF;
933        return -1;
934    }
935
936    D( "adb_shutdown: %s\n", f->name);
937    if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
938        const DWORD err = WSAGetLastError();
939        D("socket shutdown fd %d failed: %s\n", fd,
940          SystemErrorCodeToString(err).c_str());
941        _socket_set_errno(err);
942        return -1;
943    }
944    return 0;
945}
946
947/**************************************************************************/
948/**************************************************************************/
949/*****                                                                *****/
950/*****    emulated socketpairs                                       *****/
951/*****                                                                *****/
952/**************************************************************************/
953/**************************************************************************/
954
955/* we implement socketpairs directly in use space for the following reasons:
956 *   - it avoids copying data from/to the Nt kernel
957 *   - it allows us to implement fdevent hooks easily and cheaply, something
958 *     that is not possible with standard Win32 pipes !!
959 *
960 * basically, we use two circular buffers, each one corresponding to a given
961 * direction.
962 *
963 * each buffer is implemented as two regions:
964 *
965 *   region A which is (a_start,a_end)
966 *   region B which is (0, b_end)  with b_end <= a_start
967 *
968 * an empty buffer has:  a_start = a_end = b_end = 0
969 *
970 * a_start is the pointer where we start reading data
971 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
972 * then you start writing at b_end
973 *
974 * the buffer is full when  b_end == a_start && a_end == BUFFER_SIZE
975 *
976 * there is room when b_end < a_start || a_end < BUFER_SIZE
977 *
978 * when reading, a_start is incremented, it a_start meets a_end, then
979 * we do:  a_start = 0, a_end = b_end, b_end = 0, and keep going on..
980 */
981
982#define  BIP_BUFFER_SIZE   4096
983
984#if 0
985#include <stdio.h>
986#  define  BIPD(x)      D x
987#  define  BIPDUMP   bip_dump_hex
988
989static void  bip_dump_hex( const unsigned char*  ptr, size_t  len )
990{
991    int  nn, len2 = len;
992
993    if (len2 > 8) len2 = 8;
994
995    for (nn = 0; nn < len2; nn++)
996        printf("%02x", ptr[nn]);
997    printf("  ");
998
999    for (nn = 0; nn < len2; nn++) {
1000        int  c = ptr[nn];
1001        if (c < 32 || c > 127)
1002            c = '.';
1003        printf("%c", c);
1004    }
1005    printf("\n");
1006    fflush(stdout);
1007}
1008
1009#else
1010#  define  BIPD(x)        do {} while (0)
1011#  define  BIPDUMP(p,l)   BIPD(p)
1012#endif
1013
1014typedef struct BipBufferRec_
1015{
1016    int                a_start;
1017    int                a_end;
1018    int                b_end;
1019    int                fdin;
1020    int                fdout;
1021    int                closed;
1022    int                can_write;  /* boolean */
1023    HANDLE             evt_write;  /* event signaled when one can write to a buffer  */
1024    int                can_read;   /* boolean */
1025    HANDLE             evt_read;   /* event signaled when one can read from a buffer */
1026    CRITICAL_SECTION  lock;
1027    unsigned char      buff[ BIP_BUFFER_SIZE ];
1028
1029} BipBufferRec, *BipBuffer;
1030
1031static void
1032bip_buffer_init( BipBuffer  buffer )
1033{
1034    D( "bit_buffer_init %p\n", buffer );
1035    buffer->a_start   = 0;
1036    buffer->a_end     = 0;
1037    buffer->b_end     = 0;
1038    buffer->can_write = 1;
1039    buffer->can_read  = 0;
1040    buffer->fdin      = 0;
1041    buffer->fdout     = 0;
1042    buffer->closed    = 0;
1043    buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1044    buffer->evt_read  = CreateEvent( NULL, TRUE, FALSE, NULL );
1045    InitializeCriticalSection( &buffer->lock );
1046}
1047
1048static void
1049bip_buffer_close( BipBuffer  bip )
1050{
1051    bip->closed = 1;
1052
1053    if (!bip->can_read) {
1054        SetEvent( bip->evt_read );
1055    }
1056    if (!bip->can_write) {
1057        SetEvent( bip->evt_write );
1058    }
1059}
1060
1061static void
1062bip_buffer_done( BipBuffer  bip )
1063{
1064    BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
1065    CloseHandle( bip->evt_read );
1066    CloseHandle( bip->evt_write );
1067    DeleteCriticalSection( &bip->lock );
1068}
1069
1070static int
1071bip_buffer_write( BipBuffer  bip, const void* src, int  len )
1072{
1073    int  avail, count = 0;
1074
1075    if (len <= 0)
1076        return 0;
1077
1078    BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1079    BIPDUMP( src, len );
1080
1081    EnterCriticalSection( &bip->lock );
1082
1083    while (!bip->can_write) {
1084        int  ret;
1085        LeaveCriticalSection( &bip->lock );
1086
1087        if (bip->closed) {
1088            errno = EPIPE;
1089            return -1;
1090        }
1091        /* spinlocking here is probably unfair, but let's live with it */
1092        ret = WaitForSingleObject( bip->evt_write, INFINITE );
1093        if (ret != WAIT_OBJECT_0) {  /* buffer probably closed */
1094            D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
1095            return 0;
1096        }
1097        if (bip->closed) {
1098            errno = EPIPE;
1099            return -1;
1100        }
1101        EnterCriticalSection( &bip->lock );
1102    }
1103
1104    BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1105
1106    avail = BIP_BUFFER_SIZE - bip->a_end;
1107    if (avail > 0)
1108    {
1109        /* we can append to region A */
1110        if (avail > len)
1111            avail = len;
1112
1113        memcpy( bip->buff + bip->a_end, src, avail );
1114        src   = (const char *)src + avail;
1115        count += avail;
1116        len   -= avail;
1117
1118        bip->a_end += avail;
1119        if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1120            bip->can_write = 0;
1121            ResetEvent( bip->evt_write );
1122            goto Exit;
1123        }
1124    }
1125
1126    if (len == 0)
1127        goto Exit;
1128
1129    avail = bip->a_start - bip->b_end;
1130    assert( avail > 0 );  /* since can_write is TRUE */
1131
1132    if (avail > len)
1133        avail = len;
1134
1135    memcpy( bip->buff + bip->b_end, src, avail );
1136    count += avail;
1137    bip->b_end += avail;
1138
1139    if (bip->b_end == bip->a_start) {
1140        bip->can_write = 0;
1141        ResetEvent( bip->evt_write );
1142    }
1143
1144Exit:
1145    assert( count > 0 );
1146
1147    if ( !bip->can_read ) {
1148        bip->can_read = 1;
1149        SetEvent( bip->evt_read );
1150    }
1151
1152    BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
1153            bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1154    LeaveCriticalSection( &bip->lock );
1155
1156    return count;
1157 }
1158
1159static int
1160bip_buffer_read( BipBuffer  bip, void*  dst, int  len )
1161{
1162    int  avail, count = 0;
1163
1164    if (len <= 0)
1165        return 0;
1166
1167    BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1168
1169    EnterCriticalSection( &bip->lock );
1170    while ( !bip->can_read )
1171    {
1172#if 0
1173        LeaveCriticalSection( &bip->lock );
1174        errno = EAGAIN;
1175        return -1;
1176#else
1177        int  ret;
1178        LeaveCriticalSection( &bip->lock );
1179
1180        if (bip->closed) {
1181            errno = EPIPE;
1182            return -1;
1183        }
1184
1185        ret = WaitForSingleObject( bip->evt_read, INFINITE );
1186        if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
1187            D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
1188            return 0;
1189        }
1190        if (bip->closed) {
1191            errno = EPIPE;
1192            return -1;
1193        }
1194        EnterCriticalSection( &bip->lock );
1195#endif
1196    }
1197
1198    BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1199
1200    avail = bip->a_end - bip->a_start;
1201    assert( avail > 0 );  /* since can_read is TRUE */
1202
1203    if (avail > len)
1204        avail = len;
1205
1206    memcpy( dst, bip->buff + bip->a_start, avail );
1207    dst   = (char *)dst + avail;
1208    count += avail;
1209    len   -= avail;
1210
1211    bip->a_start += avail;
1212    if (bip->a_start < bip->a_end)
1213        goto Exit;
1214
1215    bip->a_start = 0;
1216    bip->a_end   = bip->b_end;
1217    bip->b_end   = 0;
1218
1219    avail = bip->a_end;
1220    if (avail > 0) {
1221        if (avail > len)
1222            avail = len;
1223        memcpy( dst, bip->buff, avail );
1224        count += avail;
1225        bip->a_start += avail;
1226
1227        if ( bip->a_start < bip->a_end )
1228            goto Exit;
1229
1230        bip->a_start = bip->a_end = 0;
1231    }
1232
1233    bip->can_read = 0;
1234    ResetEvent( bip->evt_read );
1235
1236Exit:
1237    assert( count > 0 );
1238
1239    if (!bip->can_write ) {
1240        bip->can_write = 1;
1241        SetEvent( bip->evt_write );
1242    }
1243
1244    BIPDUMP( (const unsigned char*)dst - count, count );
1245    BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
1246            bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1247    LeaveCriticalSection( &bip->lock );
1248
1249    return count;
1250}
1251
1252typedef struct SocketPairRec_
1253{
1254    BipBufferRec  a2b_bip;
1255    BipBufferRec  b2a_bip;
1256    FH            a_fd;
1257    int           used;
1258
1259} SocketPairRec;
1260
1261void _fh_socketpair_init( FH  f )
1262{
1263    f->fh_pair = NULL;
1264}
1265
1266static int
1267_fh_socketpair_close( FH  f )
1268{
1269    if ( f->fh_pair ) {
1270        SocketPair  pair = f->fh_pair;
1271
1272        if ( f == pair->a_fd ) {
1273            pair->a_fd = NULL;
1274        }
1275
1276        bip_buffer_close( &pair->b2a_bip );
1277        bip_buffer_close( &pair->a2b_bip );
1278
1279        if ( --pair->used == 0 ) {
1280            bip_buffer_done( &pair->b2a_bip );
1281            bip_buffer_done( &pair->a2b_bip );
1282            free( pair );
1283        }
1284        f->fh_pair = NULL;
1285    }
1286    return 0;
1287}
1288
1289static int
1290_fh_socketpair_lseek( FH  f, int pos, int  origin )
1291{
1292    errno = ESPIPE;
1293    return -1;
1294}
1295
1296static int
1297_fh_socketpair_read( FH  f, void* buf, int  len )
1298{
1299    SocketPair  pair = f->fh_pair;
1300    BipBuffer   bip;
1301
1302    if (!pair)
1303        return -1;
1304
1305    if ( f == pair->a_fd )
1306        bip = &pair->b2a_bip;
1307    else
1308        bip = &pair->a2b_bip;
1309
1310    return bip_buffer_read( bip, buf, len );
1311}
1312
1313static int
1314_fh_socketpair_write( FH  f, const void*  buf, int  len )
1315{
1316    SocketPair  pair = f->fh_pair;
1317    BipBuffer   bip;
1318
1319    if (!pair)
1320        return -1;
1321
1322    if ( f == pair->a_fd )
1323        bip = &pair->a2b_bip;
1324    else
1325        bip = &pair->b2a_bip;
1326
1327    return bip_buffer_write( bip, buf, len );
1328}
1329
1330
1331static void  _fh_socketpair_hook( FH  f, int  event, EventHook  hook );  /* forward */
1332
1333static const FHClassRec  _fh_socketpair_class =
1334{
1335    _fh_socketpair_init,
1336    _fh_socketpair_close,
1337    _fh_socketpair_lseek,
1338    _fh_socketpair_read,
1339    _fh_socketpair_write,
1340    _fh_socketpair_hook
1341};
1342
1343
1344int  adb_socketpair(int sv[2]) {
1345    SocketPair pair;
1346
1347    unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1348    if (!fa) {
1349        return -1;
1350    }
1351    unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1352    if (!fb) {
1353        return -1;
1354    }
1355
1356    pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
1357    if (pair == NULL) {
1358        D("adb_socketpair: not enough memory to allocate pipes\n" );
1359        return -1;
1360    }
1361
1362    bip_buffer_init( &pair->a2b_bip );
1363    bip_buffer_init( &pair->b2a_bip );
1364
1365    fa->fh_pair = pair;
1366    fb->fh_pair = pair;
1367    pair->used  = 2;
1368    pair->a_fd  = fa.get();
1369
1370    sv[0] = _fh_to_int(fa.get());
1371    sv[1] = _fh_to_int(fb.get());
1372
1373    pair->a2b_bip.fdin  = sv[0];
1374    pair->a2b_bip.fdout = sv[1];
1375    pair->b2a_bip.fdin  = sv[1];
1376    pair->b2a_bip.fdout = sv[0];
1377
1378    snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1379    snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
1380    D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
1381    fa.release();
1382    fb.release();
1383    return 0;
1384}
1385
1386/**************************************************************************/
1387/**************************************************************************/
1388/*****                                                                *****/
1389/*****    fdevents emulation                                          *****/
1390/*****                                                                *****/
1391/*****   this is a very simple implementation, we rely on the fact    *****/
1392/*****   that ADB doesn't use FDE_ERROR.                              *****/
1393/*****                                                                *****/
1394/**************************************************************************/
1395/**************************************************************************/
1396
1397#define FATAL(x...) fatal(__FUNCTION__, x)
1398
1399#if DEBUG
1400static void dump_fde(fdevent *fde, const char *info)
1401{
1402    fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1403            fde->state & FDE_READ ? 'R' : ' ',
1404            fde->state & FDE_WRITE ? 'W' : ' ',
1405            fde->state & FDE_ERROR ? 'E' : ' ',
1406            info);
1407}
1408#else
1409#define dump_fde(fde, info) do { } while(0)
1410#endif
1411
1412#define FDE_EVENTMASK  0x00ff
1413#define FDE_STATEMASK  0xff00
1414
1415#define FDE_ACTIVE     0x0100
1416#define FDE_PENDING    0x0200
1417#define FDE_CREATED    0x0400
1418
1419static void fdevent_plist_enqueue(fdevent *node);
1420static void fdevent_plist_remove(fdevent *node);
1421static fdevent *fdevent_plist_dequeue(void);
1422
1423static fdevent list_pending = {
1424    .next = &list_pending,
1425    .prev = &list_pending,
1426};
1427
1428static fdevent **fd_table = 0;
1429static int       fd_table_max = 0;
1430
1431typedef struct EventLooperRec_*  EventLooper;
1432
1433typedef struct EventHookRec_
1434{
1435    EventHook    next;
1436    FH           fh;
1437    HANDLE       h;
1438    int          wanted;   /* wanted event flags */
1439    int          ready;    /* ready event flags  */
1440    void*        aux;
1441    void        (*prepare)( EventHook  hook );
1442    int         (*start)  ( EventHook  hook );
1443    void        (*stop)   ( EventHook  hook );
1444    int         (*check)  ( EventHook  hook );
1445    int         (*peek)   ( EventHook  hook );
1446} EventHookRec;
1447
1448static EventHook  _free_hooks;
1449
1450static EventHook
1451event_hook_alloc(FH fh) {
1452    EventHook hook = _free_hooks;
1453    if (hook != NULL) {
1454        _free_hooks = hook->next;
1455    } else {
1456        hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
1457        if (hook == NULL)
1458            fatal( "could not allocate event hook\n" );
1459    }
1460    hook->next   = NULL;
1461    hook->fh     = fh;
1462    hook->wanted = 0;
1463    hook->ready  = 0;
1464    hook->h      = INVALID_HANDLE_VALUE;
1465    hook->aux    = NULL;
1466
1467    hook->prepare = NULL;
1468    hook->start   = NULL;
1469    hook->stop    = NULL;
1470    hook->check   = NULL;
1471    hook->peek    = NULL;
1472
1473    return hook;
1474}
1475
1476static void
1477event_hook_free( EventHook  hook )
1478{
1479    hook->fh     = NULL;
1480    hook->wanted = 0;
1481    hook->ready  = 0;
1482    hook->next   = _free_hooks;
1483    _free_hooks  = hook;
1484}
1485
1486
1487static void
1488event_hook_signal( EventHook  hook )
1489{
1490    FH        f   = hook->fh;
1491    int       fd  = _fh_to_int(f);
1492    fdevent*  fde = fd_table[ fd - WIN32_FH_BASE ];
1493
1494    if (fde != NULL && fde->fd == fd) {
1495        if ((fde->state & FDE_PENDING) == 0) {
1496            fde->state |= FDE_PENDING;
1497            fdevent_plist_enqueue( fde );
1498        }
1499        fde->events |= hook->wanted;
1500    }
1501}
1502
1503
1504#define  MAX_LOOPER_HANDLES  WIN32_MAX_FHS
1505
1506typedef struct EventLooperRec_
1507{
1508    EventHook    hooks;
1509    HANDLE       htab[ MAX_LOOPER_HANDLES ];
1510    int          htab_count;
1511
1512} EventLooperRec;
1513
1514static EventHook*
1515event_looper_find_p( EventLooper  looper, FH  fh )
1516{
1517    EventHook  *pnode = &looper->hooks;
1518    EventHook   node  = *pnode;
1519    for (;;) {
1520        if ( node == NULL || node->fh == fh )
1521            break;
1522        pnode = &node->next;
1523        node  = *pnode;
1524    }
1525    return  pnode;
1526}
1527
1528static void
1529event_looper_hook( EventLooper  looper, int  fd, int  events )
1530{
1531    FH          f = _fh_from_int(fd, __func__);
1532    EventHook  *pnode;
1533    EventHook   node;
1534
1535    if (f == NULL)  /* invalid arg */ {
1536        D("event_looper_hook: invalid fd=%d\n", fd);
1537        return;
1538    }
1539
1540    pnode = event_looper_find_p( looper, f );
1541    node  = *pnode;
1542    if ( node == NULL ) {
1543        node       = event_hook_alloc( f );
1544        node->next = *pnode;
1545        *pnode     = node;
1546    }
1547
1548    if ( (node->wanted & events) != events ) {
1549        /* this should update start/stop/check/peek */
1550        D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
1551           fd, node->wanted, events);
1552        f->clazz->_fh_hook( f, events & ~node->wanted, node );
1553        node->wanted |= events;
1554    } else {
1555        D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
1556           events, fd, node->wanted);
1557    }
1558}
1559
1560static void
1561event_looper_unhook( EventLooper  looper, int  fd, int  events )
1562{
1563    FH          fh    = _fh_from_int(fd, __func__);
1564    EventHook  *pnode = event_looper_find_p( looper, fh );
1565    EventHook   node  = *pnode;
1566
1567    if (node != NULL) {
1568        int  events2 = events & node->wanted;
1569        if ( events2 == 0 ) {
1570            D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
1571            return;
1572        }
1573        node->wanted &= ~events2;
1574        if (!node->wanted) {
1575            *pnode = node->next;
1576            event_hook_free( node );
1577        }
1578    }
1579}
1580
1581/*
1582 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1583 * handles to wait on.
1584 *
1585 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1586 * instance, this may happen if there are more than 64 processes running on a
1587 * device, or there are multiple devices connected (including the emulator) with
1588 * the combined number of running processes greater than 64. In this case using
1589 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1590 * because of the API limitations (64 handles max). So, we need to provide a way
1591 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1592 * easiest (and "Microsoft recommended") way to do that would be dividing the
1593 * handle array into chunks with the chunk size less than 64, and fire up as many
1594 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1595 * handles, and will report back to the caller which handle has been set.
1596 * Here is the implementation of that algorithm.
1597 */
1598
1599/* Number of handles to wait on in each wating thread. */
1600#define WAIT_ALL_CHUNK_SIZE 63
1601
1602/* Descriptor for a wating thread */
1603typedef struct WaitForAllParam {
1604    /* A handle to an event to signal when waiting is over. This handle is shared
1605     * accross all the waiting threads, so each waiting thread knows when any
1606     * other thread has exited, so it can exit too. */
1607    HANDLE          main_event;
1608    /* Upon exit from a waiting thread contains the index of the handle that has
1609     * been signaled. The index is an absolute index of the signaled handle in
1610     * the original array. This pointer is shared accross all the waiting threads
1611     * and it's not guaranteed (due to a race condition) that when all the
1612     * waiting threads exit, the value contained here would indicate the first
1613     * handle that was signaled. This is fine, because the caller cares only
1614     * about any handle being signaled. It doesn't care about the order, nor
1615     * about the whole list of handles that were signaled. */
1616    LONG volatile   *signaled_index;
1617    /* Array of handles to wait on in a waiting thread. */
1618    HANDLE*         handles;
1619    /* Number of handles in 'handles' array to wait on. */
1620    int             handles_count;
1621    /* Index inside the main array of the first handle in the 'handles' array. */
1622    int             first_handle_index;
1623    /* Waiting thread handle. */
1624    HANDLE          thread;
1625} WaitForAllParam;
1626
1627/* Waiting thread routine. */
1628static unsigned __stdcall
1629_in_waiter_thread(void*  arg)
1630{
1631    HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1632    int res;
1633    WaitForAllParam* const param = (WaitForAllParam*)arg;
1634
1635    /* We have to wait on the main_event in order to be notified when any of the
1636     * sibling threads is exiting. */
1637    wait_on[0] = param->main_event;
1638    /* The rest of the handles go behind the main event handle. */
1639    memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1640
1641    res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1642    if (res > 0 && res < (param->handles_count + 1)) {
1643        /* One of the original handles got signaled. Save its absolute index into
1644         * the output variable. */
1645        InterlockedCompareExchange(param->signaled_index,
1646                                   res - 1L + param->first_handle_index, -1L);
1647    }
1648
1649    /* Notify the caller (and the siblings) that the wait is over. */
1650    SetEvent(param->main_event);
1651
1652    _endthreadex(0);
1653    return 0;
1654}
1655
1656/* WaitForMultipeObjects fixer routine.
1657 * Param:
1658 *  handles Array of handles to wait on.
1659 *  handles_count Number of handles in the array.
1660 * Return:
1661 *  (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1662 *  WAIT_FAILED on an error.
1663 */
1664static int
1665_wait_for_all(HANDLE* handles, int handles_count)
1666{
1667    WaitForAllParam* threads;
1668    HANDLE main_event;
1669    int chunks, chunk, remains;
1670
1671    /* This variable is going to be accessed by several threads at the same time,
1672     * this is bound to fail randomly when the core is run on multi-core machines.
1673     * To solve this, we need to do the following (1 _and_ 2):
1674     * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1675     *    out the reads/writes in this function unexpectedly.
1676     * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1677     *    all accesses inside a critical section. But we can also use
1678     *    InterlockedCompareExchange() which always provide a full memory barrier
1679     *    on Win32.
1680     */
1681    volatile LONG sig_index = -1;
1682
1683    /* Calculate number of chunks, and allocate thread param array. */
1684    chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1685    remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1686    threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1687                                        sizeof(WaitForAllParam));
1688    if (threads == NULL) {
1689        D("Unable to allocate thread array for %d handles.\n", handles_count);
1690        return (int)WAIT_FAILED;
1691    }
1692
1693    /* Create main event to wait on for all waiting threads. This is a "manualy
1694     * reset" event that will remain set once it was set. */
1695    main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1696    if (main_event == NULL) {
1697        D("Unable to create main event. Error: %ld\n", GetLastError());
1698        free(threads);
1699        return (int)WAIT_FAILED;
1700    }
1701
1702    /*
1703     * Initialize waiting thread parameters.
1704     */
1705
1706    for (chunk = 0; chunk < chunks; chunk++) {
1707        threads[chunk].main_event = main_event;
1708        threads[chunk].signaled_index = &sig_index;
1709        threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1710        threads[chunk].handles = handles + threads[chunk].first_handle_index;
1711        threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1712    }
1713    if (remains) {
1714        threads[chunk].main_event = main_event;
1715        threads[chunk].signaled_index = &sig_index;
1716        threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1717        threads[chunk].handles = handles + threads[chunk].first_handle_index;
1718        threads[chunk].handles_count = remains;
1719        chunks++;
1720    }
1721
1722    /* Start the waiting threads. */
1723    for (chunk = 0; chunk < chunks; chunk++) {
1724        /* Note that using adb_thread_create is not appropriate here, since we
1725         * need a handle to wait on for thread termination. */
1726        threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1727                                                       &threads[chunk], 0, NULL);
1728        if (threads[chunk].thread == NULL) {
1729            /* Unable to create a waiter thread. Collapse. */
1730            D("Unable to create a waiting thread %d of %d. errno=%d\n",
1731              chunk, chunks, errno);
1732            chunks = chunk;
1733            SetEvent(main_event);
1734            break;
1735        }
1736    }
1737
1738    /* Wait on any of the threads to get signaled. */
1739    WaitForSingleObject(main_event, INFINITE);
1740
1741    /* Wait on all the waiting threads to exit. */
1742    for (chunk = 0; chunk < chunks; chunk++) {
1743        WaitForSingleObject(threads[chunk].thread, INFINITE);
1744        CloseHandle(threads[chunk].thread);
1745    }
1746
1747    CloseHandle(main_event);
1748    free(threads);
1749
1750
1751    const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1752    return (ret >= 0) ? ret : (int)WAIT_FAILED;
1753}
1754
1755static EventLooperRec  win32_looper;
1756
1757static void fdevent_init(void)
1758{
1759    win32_looper.htab_count = 0;
1760    win32_looper.hooks      = NULL;
1761}
1762
1763static void fdevent_connect(fdevent *fde)
1764{
1765    EventLooper  looper = &win32_looper;
1766    int          events = fde->state & FDE_EVENTMASK;
1767
1768    if (events != 0)
1769        event_looper_hook( looper, fde->fd, events );
1770}
1771
1772static void fdevent_disconnect(fdevent *fde)
1773{
1774    EventLooper  looper = &win32_looper;
1775    int          events = fde->state & FDE_EVENTMASK;
1776
1777    if (events != 0)
1778        event_looper_unhook( looper, fde->fd, events );
1779}
1780
1781static void fdevent_update(fdevent *fde, unsigned events)
1782{
1783    EventLooper  looper  = &win32_looper;
1784    unsigned     events0 = fde->state & FDE_EVENTMASK;
1785
1786    if (events != events0) {
1787        int  removes = events0 & ~events;
1788        int  adds    = events  & ~events0;
1789        if (removes) {
1790            D("fdevent_update: remove %x from %d\n", removes, fde->fd);
1791            event_looper_unhook( looper, fde->fd, removes );
1792        }
1793        if (adds) {
1794            D("fdevent_update: add %x to %d\n", adds, fde->fd);
1795            event_looper_hook  ( looper, fde->fd, adds );
1796        }
1797    }
1798}
1799
1800static void fdevent_process()
1801{
1802    EventLooper  looper = &win32_looper;
1803    EventHook    hook;
1804    int          gotone = 0;
1805
1806    /* if we have at least one ready hook, execute it/them */
1807    for (hook = looper->hooks; hook; hook = hook->next) {
1808        hook->ready = 0;
1809        if (hook->prepare) {
1810            hook->prepare(hook);
1811            if (hook->ready != 0) {
1812                event_hook_signal( hook );
1813                gotone = 1;
1814            }
1815        }
1816    }
1817
1818    /* nothing's ready yet, so wait for something to happen */
1819    if (!gotone)
1820    {
1821        looper->htab_count = 0;
1822
1823        for (hook = looper->hooks; hook; hook = hook->next)
1824        {
1825            if (hook->start && !hook->start(hook)) {
1826                D( "fdevent_process: error when starting a hook\n" );
1827                return;
1828            }
1829            if (hook->h != INVALID_HANDLE_VALUE) {
1830                int  nn;
1831
1832                for (nn = 0; nn < looper->htab_count; nn++)
1833                {
1834                    if ( looper->htab[nn] == hook->h )
1835                        goto DontAdd;
1836                }
1837                looper->htab[ looper->htab_count++ ] = hook->h;
1838            DontAdd:
1839                ;
1840            }
1841        }
1842
1843        if (looper->htab_count == 0) {
1844            D( "fdevent_process: nothing to wait for !!\n" );
1845            return;
1846        }
1847
1848        do
1849        {
1850            int   wait_ret;
1851
1852            D( "adb_win32: waiting for %d events\n", looper->htab_count );
1853            if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
1854                D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
1855                wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1856            } else {
1857                wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
1858            }
1859            if (wait_ret == (int)WAIT_FAILED) {
1860                D( "adb_win32: wait failed, error %ld\n", GetLastError() );
1861            } else {
1862                D( "adb_win32: got one (index %d)\n", wait_ret );
1863
1864                /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1865                 * like mouse movements. we need to filter these with the "check" function
1866                 */
1867                if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1868                {
1869                    for (hook = looper->hooks; hook; hook = hook->next)
1870                    {
1871                        if ( looper->htab[wait_ret] == hook->h       &&
1872                         (!hook->check || hook->check(hook)) )
1873                        {
1874                            D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
1875                            event_hook_signal( hook );
1876                            gotone = 1;
1877                            break;
1878                        }
1879                    }
1880                }
1881            }
1882        }
1883        while (!gotone);
1884
1885        for (hook = looper->hooks; hook; hook = hook->next) {
1886            if (hook->stop)
1887                hook->stop( hook );
1888        }
1889    }
1890
1891    for (hook = looper->hooks; hook; hook = hook->next) {
1892        if (hook->peek && hook->peek(hook))
1893                event_hook_signal( hook );
1894    }
1895}
1896
1897
1898static void fdevent_register(fdevent *fde)
1899{
1900    int  fd = fde->fd - WIN32_FH_BASE;
1901
1902    if(fd < 0) {
1903        FATAL("bogus negative fd (%d)\n", fde->fd);
1904    }
1905
1906    if(fd >= fd_table_max) {
1907        int oldmax = fd_table_max;
1908        if(fde->fd > 32000) {
1909            FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1910        }
1911        if(fd_table_max == 0) {
1912            fdevent_init();
1913            fd_table_max = 256;
1914        }
1915        while(fd_table_max <= fd) {
1916            fd_table_max *= 2;
1917        }
1918        fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
1919        if(fd_table == 0) {
1920            FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1921        }
1922        memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
1923    }
1924
1925    fd_table[fd] = fde;
1926}
1927
1928static void fdevent_unregister(fdevent *fde)
1929{
1930    int  fd = fde->fd - WIN32_FH_BASE;
1931
1932    if((fd < 0) || (fd >= fd_table_max)) {
1933        FATAL("fd out of range (%d)\n", fde->fd);
1934    }
1935
1936    if(fd_table[fd] != fde) {
1937        FATAL("fd_table out of sync");
1938    }
1939
1940    fd_table[fd] = 0;
1941
1942    if(!(fde->state & FDE_DONT_CLOSE)) {
1943        dump_fde(fde, "close");
1944        adb_close(fde->fd);
1945    }
1946}
1947
1948static void fdevent_plist_enqueue(fdevent *node)
1949{
1950    fdevent *list = &list_pending;
1951
1952    node->next = list;
1953    node->prev = list->prev;
1954    node->prev->next = node;
1955    list->prev = node;
1956}
1957
1958static void fdevent_plist_remove(fdevent *node)
1959{
1960    node->prev->next = node->next;
1961    node->next->prev = node->prev;
1962    node->next = 0;
1963    node->prev = 0;
1964}
1965
1966static fdevent *fdevent_plist_dequeue(void)
1967{
1968    fdevent *list = &list_pending;
1969    fdevent *node = list->next;
1970
1971    if(node == list) return 0;
1972
1973    list->next = node->next;
1974    list->next->prev = list;
1975    node->next = 0;
1976    node->prev = 0;
1977
1978    return node;
1979}
1980
1981fdevent *fdevent_create(int fd, fd_func func, void *arg)
1982{
1983    fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
1984    if(fde == 0) return 0;
1985    fdevent_install(fde, fd, func, arg);
1986    fde->state |= FDE_CREATED;
1987    return fde;
1988}
1989
1990void fdevent_destroy(fdevent *fde)
1991{
1992    if(fde == 0) return;
1993    if(!(fde->state & FDE_CREATED)) {
1994        FATAL("fde %p not created by fdevent_create()\n", fde);
1995    }
1996    fdevent_remove(fde);
1997}
1998
1999void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
2000{
2001    memset(fde, 0, sizeof(fdevent));
2002    fde->state = FDE_ACTIVE;
2003    fde->fd = fd;
2004    fde->func = func;
2005    fde->arg = arg;
2006
2007    fdevent_register(fde);
2008    dump_fde(fde, "connect");
2009    fdevent_connect(fde);
2010    fde->state |= FDE_ACTIVE;
2011}
2012
2013void fdevent_remove(fdevent *fde)
2014{
2015    if(fde->state & FDE_PENDING) {
2016        fdevent_plist_remove(fde);
2017    }
2018
2019    if(fde->state & FDE_ACTIVE) {
2020        fdevent_disconnect(fde);
2021        dump_fde(fde, "disconnect");
2022        fdevent_unregister(fde);
2023    }
2024
2025    fde->state = 0;
2026    fde->events = 0;
2027}
2028
2029
2030void fdevent_set(fdevent *fde, unsigned events)
2031{
2032    events &= FDE_EVENTMASK;
2033
2034    if((fde->state & FDE_EVENTMASK) == (int)events) return;
2035
2036    if(fde->state & FDE_ACTIVE) {
2037        fdevent_update(fde, events);
2038        dump_fde(fde, "update");
2039    }
2040
2041    fde->state = (fde->state & FDE_STATEMASK) | events;
2042
2043    if(fde->state & FDE_PENDING) {
2044            /* if we're pending, make sure
2045            ** we don't signal an event that
2046            ** is no longer wanted.
2047            */
2048        fde->events &= (~events);
2049        if(fde->events == 0) {
2050            fdevent_plist_remove(fde);
2051            fde->state &= (~FDE_PENDING);
2052        }
2053    }
2054}
2055
2056void fdevent_add(fdevent *fde, unsigned events)
2057{
2058    fdevent_set(
2059        fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2060}
2061
2062void fdevent_del(fdevent *fde, unsigned events)
2063{
2064    fdevent_set(
2065        fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2066}
2067
2068void fdevent_loop()
2069{
2070    fdevent *fde;
2071
2072    for(;;) {
2073#if DEBUG
2074        fprintf(stderr,"--- ---- waiting for events\n");
2075#endif
2076        fdevent_process();
2077
2078        while((fde = fdevent_plist_dequeue())) {
2079            unsigned events = fde->events;
2080            fde->events = 0;
2081            fde->state &= (~FDE_PENDING);
2082            dump_fde(fde, "callback");
2083            fde->func(fde->fd, events, fde->arg);
2084        }
2085    }
2086}
2087
2088/**  FILE EVENT HOOKS
2089 **/
2090
2091static void  _event_file_prepare( EventHook  hook )
2092{
2093    if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2094        /* we can always read/write */
2095        hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2096    }
2097}
2098
2099static int  _event_file_peek( EventHook  hook )
2100{
2101    return (hook->wanted & (FDE_READ|FDE_WRITE));
2102}
2103
2104static void  _fh_file_hook( FH  f, int  events, EventHook  hook )
2105{
2106    hook->h       = f->fh_handle;
2107    hook->prepare = _event_file_prepare;
2108    hook->peek    = _event_file_peek;
2109}
2110
2111/** SOCKET EVENT HOOKS
2112 **/
2113
2114static void  _event_socket_verify( EventHook  hook, WSANETWORKEVENTS*  evts )
2115{
2116    if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2117        if (hook->wanted & FDE_READ)
2118            hook->ready |= FDE_READ;
2119        if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2120            hook->ready |= FDE_ERROR;
2121    }
2122    if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2123        if (hook->wanted & FDE_WRITE)
2124            hook->ready |= FDE_WRITE;
2125        if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2126            hook->ready |= FDE_ERROR;
2127    }
2128    if ( evts->lNetworkEvents & FD_OOB ) {
2129        if (hook->wanted & FDE_ERROR)
2130            hook->ready |= FDE_ERROR;
2131    }
2132}
2133
2134static void  _event_socket_prepare( EventHook  hook )
2135{
2136    WSANETWORKEVENTS  evts;
2137
2138    /* look if some of the events we want already happened ? */
2139    if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2140        _event_socket_verify( hook, &evts );
2141}
2142
2143static int  _socket_wanted_to_flags( int  wanted )
2144{
2145    int  flags = 0;
2146    if (wanted & FDE_READ)
2147        flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2148
2149    if (wanted & FDE_WRITE)
2150        flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2151
2152    if (wanted & FDE_ERROR)
2153        flags |= FD_OOB;
2154
2155    return flags;
2156}
2157
2158static int _event_socket_start( EventHook  hook )
2159{
2160    /* create an event which we're going to wait for */
2161    FH    fh    = hook->fh;
2162    long  flags = _socket_wanted_to_flags( hook->wanted );
2163
2164    hook->h = fh->event;
2165    if (hook->h == INVALID_HANDLE_VALUE) {
2166        D( "_event_socket_start: no event for %s\n", fh->name );
2167        return 0;
2168    }
2169
2170    if ( flags != fh->mask ) {
2171        D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
2172        if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
2173            D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
2174            CloseHandle( hook->h );
2175            hook->h = INVALID_HANDLE_VALUE;
2176            exit(1);
2177            return 0;
2178        }
2179        fh->mask = flags;
2180    }
2181    return 1;
2182}
2183
2184static void _event_socket_stop( EventHook  hook )
2185{
2186    hook->h = INVALID_HANDLE_VALUE;
2187}
2188
2189static int  _event_socket_check( EventHook  hook )
2190{
2191    int               result = 0;
2192    FH                fh = hook->fh;
2193    WSANETWORKEVENTS  evts;
2194
2195    if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2196        _event_socket_verify( hook, &evts );
2197        result = (hook->ready != 0);
2198        if (result) {
2199            ResetEvent( hook->h );
2200        }
2201    }
2202    D( "_event_socket_check %s returns %d\n", fh->name, result );
2203    return  result;
2204}
2205
2206static int  _event_socket_peek( EventHook  hook )
2207{
2208    WSANETWORKEVENTS  evts;
2209    FH                fh = hook->fh;
2210
2211    /* look if some of the events we want already happened ? */
2212    if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2213        _event_socket_verify( hook, &evts );
2214        if (hook->ready)
2215            ResetEvent( hook->h );
2216    }
2217
2218    return hook->ready != 0;
2219}
2220
2221
2222
2223static void  _fh_socket_hook( FH  f, int  events, EventHook  hook )
2224{
2225    hook->prepare = _event_socket_prepare;
2226    hook->start   = _event_socket_start;
2227    hook->stop    = _event_socket_stop;
2228    hook->check   = _event_socket_check;
2229    hook->peek    = _event_socket_peek;
2230
2231    // TODO: check return value?
2232    _event_socket_start( hook );
2233}
2234
2235/** SOCKETPAIR EVENT HOOKS
2236 **/
2237
2238static void  _event_socketpair_prepare( EventHook  hook )
2239{
2240    FH          fh   = hook->fh;
2241    SocketPair  pair = fh->fh_pair;
2242    BipBuffer   rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2243    BipBuffer   wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2244
2245    if (hook->wanted & FDE_READ && rbip->can_read)
2246        hook->ready |= FDE_READ;
2247
2248    if (hook->wanted & FDE_WRITE && wbip->can_write)
2249        hook->ready |= FDE_WRITE;
2250 }
2251
2252 static int  _event_socketpair_start( EventHook  hook )
2253 {
2254    FH          fh   = hook->fh;
2255    SocketPair  pair = fh->fh_pair;
2256    BipBuffer   rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2257    BipBuffer   wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2258
2259    if (hook->wanted == FDE_READ)
2260        hook->h = rbip->evt_read;
2261
2262    else if (hook->wanted == FDE_WRITE)
2263        hook->h = wbip->evt_write;
2264
2265    else {
2266        D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
2267        return 0;
2268    }
2269    D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
2270       hook->fh->name, _fh_to_int(fh), hook->wanted);
2271    return 1;
2272}
2273
2274static int  _event_socketpair_peek( EventHook  hook )
2275{
2276    _event_socketpair_prepare( hook );
2277    return hook->ready != 0;
2278}
2279
2280static void  _fh_socketpair_hook( FH  fh, int  events, EventHook  hook )
2281{
2282    hook->prepare = _event_socketpair_prepare;
2283    hook->start   = _event_socketpair_start;
2284    hook->peek    = _event_socketpair_peek;
2285}
2286
2287
2288void
2289adb_sysdeps_init( void )
2290{
2291#define  ADB_MUTEX(x)  InitializeCriticalSection( & x );
2292#include "mutex_list.h"
2293    InitializeCriticalSection( &_win32_lock );
2294}
2295
2296/**************************************************************************/
2297/**************************************************************************/
2298/*****                                                                *****/
2299/*****      Console Window Terminal Emulation                         *****/
2300/*****                                                                *****/
2301/**************************************************************************/
2302/**************************************************************************/
2303
2304// This reads input from a Win32 console window and translates it into Unix
2305// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2306// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2307// is emulated instead of xterm because it is probably more popular than xterm:
2308// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2309// supports modern fonts, etc. It seems best to emulate the terminal that most
2310// Android developers use because they'll fix apps (the shell, etc.) to keep
2311// working with that terminal's emulation.
2312//
2313// The point of this emulation is not to be perfect or to solve all issues with
2314// console windows on Windows, but to be better than the original code which
2315// just called read() (which called ReadFile(), which called ReadConsoleA())
2316// which did not support Ctrl-C, tab completion, shell input line editing
2317// keys, server echo, and more.
2318//
2319// This implementation reconfigures the console with SetConsoleMode(), then
2320// calls ReadConsoleInput() to get raw input which it remaps to Unix
2321// terminal-style sequences which is returned via unix_read() which is used
2322// by the 'adb shell' command.
2323//
2324// Code organization:
2325//
2326// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2327// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2328// * _console_read() is the main code of the emulation.
2329
2330
2331// Read an input record from the console; one that should be processed.
2332static bool _get_interesting_input_record_uncached(const HANDLE console,
2333    INPUT_RECORD* const input_record) {
2334    for (;;) {
2335        DWORD read_count = 0;
2336        memset(input_record, 0, sizeof(*input_record));
2337        if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2338            D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
2339              "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
2340            errno = EIO;
2341            return false;
2342        }
2343
2344        if (read_count == 0) {   // should be impossible
2345            fatal("ReadConsoleInputA returned 0");
2346        }
2347
2348        if (read_count != 1) {   // should be impossible
2349            fatal("ReadConsoleInputA did not return one input record");
2350        }
2351
2352        if ((input_record->EventType == KEY_EVENT) &&
2353            (input_record->Event.KeyEvent.bKeyDown)) {
2354            if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2355                fatal("ReadConsoleInputA returned a key event with zero repeat"
2356                      " count");
2357            }
2358
2359            // Got an interesting INPUT_RECORD, so return
2360            return true;
2361        }
2362    }
2363}
2364
2365// Cached input record (in case _console_read() is passed a buffer that doesn't
2366// have enough space to fit wRepeatCount number of key sequences). A non-zero
2367// wRepeatCount indicates that a record is cached.
2368static INPUT_RECORD _win32_input_record;
2369
2370// Get the next KEY_EVENT_RECORD that should be processed.
2371static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2372    // If nothing cached, read directly from the console until we get an
2373    // interesting record.
2374    if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2375        if (!_get_interesting_input_record_uncached(console,
2376            &_win32_input_record)) {
2377            // There was an error, so make sure wRepeatCount is zero because
2378            // that signifies no cached input record.
2379            _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2380            return NULL;
2381        }
2382    }
2383
2384    return &_win32_input_record.Event.KeyEvent;
2385}
2386
2387static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2388    return (control_key_state & SHIFT_PRESSED) != 0;
2389}
2390
2391static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2392    return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2393}
2394
2395static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2396    return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2397}
2398
2399static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2400    return (control_key_state & NUMLOCK_ON) != 0;
2401}
2402
2403static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2404    return (control_key_state & CAPSLOCK_ON) != 0;
2405}
2406
2407static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2408    return (control_key_state & ENHANCED_KEY) != 0;
2409}
2410
2411// Constants from MSDN for ToAscii().
2412static const BYTE TOASCII_KEY_OFF = 0x00;
2413static const BYTE TOASCII_KEY_DOWN = 0x80;
2414static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01;   // for CapsLock
2415
2416// Given a key event, ignore a modifier key and return the character that was
2417// entered without the modifier. Writes to *ch and returns the number of bytes
2418// written.
2419static size_t _get_char_ignoring_modifier(char* const ch,
2420    const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2421    const WORD modifier) {
2422    // If there is no character from Windows, try ignoring the specified
2423    // modifier and look for a character. Note that if AltGr is being used,
2424    // there will be a character from Windows.
2425    if (key_event->uChar.AsciiChar == '\0') {
2426        // Note that we read the control key state from the passed in argument
2427        // instead of from key_event since the argument has been normalized.
2428        if (((modifier == VK_SHIFT)   &&
2429            _is_shift_pressed(control_key_state)) ||
2430            ((modifier == VK_CONTROL) &&
2431            _is_ctrl_pressed(control_key_state)) ||
2432            ((modifier == VK_MENU)    && _is_alt_pressed(control_key_state))) {
2433
2434            BYTE key_state[256]   = {0};
2435            key_state[VK_SHIFT]   = _is_shift_pressed(control_key_state) ?
2436                TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2437            key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state)  ?
2438                TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2439            key_state[VK_MENU]    = _is_alt_pressed(control_key_state)   ?
2440                TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2441            key_state[VK_CAPITAL] = _is_capslock_on(control_key_state)   ?
2442                TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2443
2444            // cause this modifier to be ignored
2445            key_state[modifier]   = TOASCII_KEY_OFF;
2446
2447            WORD translated = 0;
2448            if (ToAscii(key_event->wVirtualKeyCode,
2449                key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2450                // Ignoring the modifier, we found a character.
2451                *ch = (CHAR)translated;
2452                return 1;
2453            }
2454        }
2455    }
2456
2457    // Just use whatever Windows told us originally.
2458    *ch = key_event->uChar.AsciiChar;
2459
2460    // If the character from Windows is NULL, return a size of zero.
2461    return (*ch == '\0') ? 0 : 1;
2462}
2463
2464// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2465// but taking into account the shift key. This is because for a sequence like
2466// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2467// we want to find the character ')'.
2468//
2469// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2470// because it is the default key-sequence to switch the input language.
2471// This is configurable in the Region and Language control panel.
2472static __inline__ size_t _get_non_control_char(char* const ch,
2473    const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2474    return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2475        VK_CONTROL);
2476}
2477
2478// Get without Alt.
2479static __inline__ size_t _get_non_alt_char(char* const ch,
2480    const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2481    return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2482        VK_MENU);
2483}
2484
2485// Ignore the control key, find the character from Windows, and apply any
2486// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2487// *pch and returns number of bytes written.
2488static size_t _get_control_character(char* const pch,
2489    const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2490    const size_t len = _get_non_control_char(pch, key_event,
2491        control_key_state);
2492
2493    if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2494        char ch = *pch;
2495        switch (ch) {
2496        case '2':
2497        case '@':
2498        case '`':
2499            ch = '\0';
2500            break;
2501        case '3':
2502        case '[':
2503        case '{':
2504            ch = '\x1b';
2505            break;
2506        case '4':
2507        case '\\':
2508        case '|':
2509            ch = '\x1c';
2510            break;
2511        case '5':
2512        case ']':
2513        case '}':
2514            ch = '\x1d';
2515            break;
2516        case '6':
2517        case '^':
2518        case '~':
2519            ch = '\x1e';
2520            break;
2521        case '7':
2522        case '-':
2523        case '_':
2524            ch = '\x1f';
2525            break;
2526        case '8':
2527            ch = '\x7f';
2528            break;
2529        case '/':
2530            if (!_is_alt_pressed(control_key_state)) {
2531                ch = '\x1f';
2532            }
2533            break;
2534        case '?':
2535            if (!_is_alt_pressed(control_key_state)) {
2536                ch = '\x7f';
2537            }
2538            break;
2539        }
2540        *pch = ch;
2541    }
2542
2543    return len;
2544}
2545
2546static DWORD _normalize_altgr_control_key_state(
2547    const KEY_EVENT_RECORD* const key_event) {
2548    DWORD control_key_state = key_event->dwControlKeyState;
2549
2550    // If we're in an AltGr situation where the AltGr key is down (depending on
2551    // the keyboard layout, that might be the physical right alt key which
2552    // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2553    // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2554    // a character (which indicates that there was an AltGr mapping), then act
2555    // as if alt and control are not really down for the purposes of modifiers.
2556    // This makes it so that if the user with, say, a German keyboard layout
2557    // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2558    // output the key and we don't see the Alt and Ctrl keys.
2559    if (_is_ctrl_pressed(control_key_state) &&
2560        _is_alt_pressed(control_key_state)
2561        && (key_event->uChar.AsciiChar != '\0')) {
2562        // Try to remove as few bits as possible to improve our chances of
2563        // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2564        // Left-Alt + Right-Ctrl + AltGr.
2565        if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2566            // Remove Right-Alt.
2567            control_key_state &= ~RIGHT_ALT_PRESSED;
2568            // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2569            // pressed, Left-Ctrl is almost always set, except if the user
2570            // presses Right-Ctrl, then AltGr (in that specific order) for
2571            // whatever reason. At any rate, make sure the bit is not set.
2572            control_key_state &= ~LEFT_CTRL_PRESSED;
2573        } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2574            // Remove Left-Alt.
2575            control_key_state &= ~LEFT_ALT_PRESSED;
2576            // Whichever Ctrl key is down, remove it from the state. We only
2577            // remove one key, to improve our chances of detecting the
2578            // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2579            if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2580                // Remove Left-Ctrl.
2581                control_key_state &= ~LEFT_CTRL_PRESSED;
2582            } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2583                // Remove Right-Ctrl.
2584                control_key_state &= ~RIGHT_CTRL_PRESSED;
2585            }
2586        }
2587
2588        // Note that this logic isn't 100% perfect because Windows doesn't
2589        // allow us to detect all combinations because a physical AltGr key
2590        // press shows up as two bits, plus some combinations are ambiguous
2591        // about what is actually physically pressed.
2592    }
2593
2594    return control_key_state;
2595}
2596
2597// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2598// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2599// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2600// appropriately.
2601static DWORD _normalize_keypad_control_key_state(const WORD vk,
2602    const DWORD control_key_state) {
2603    if (!_is_numlock_on(control_key_state)) {
2604        return control_key_state;
2605    }
2606    if (!_is_enhanced_key(control_key_state)) {
2607        switch (vk) {
2608            case VK_INSERT: // 0
2609            case VK_DELETE: // .
2610            case VK_END:    // 1
2611            case VK_DOWN:   // 2
2612            case VK_NEXT:   // 3
2613            case VK_LEFT:   // 4
2614            case VK_CLEAR:  // 5
2615            case VK_RIGHT:  // 6
2616            case VK_HOME:   // 7
2617            case VK_UP:     // 8
2618            case VK_PRIOR:  // 9
2619                return control_key_state | SHIFT_PRESSED;
2620        }
2621    }
2622
2623    return control_key_state;
2624}
2625
2626static const char* _get_keypad_sequence(const DWORD control_key_state,
2627    const char* const normal, const char* const shifted) {
2628    if (_is_shift_pressed(control_key_state)) {
2629        // Shift is pressed and NumLock is off
2630        return shifted;
2631    } else {
2632        // Shift is not pressed and NumLock is off, or,
2633        // Shift is pressed and NumLock is on, in which case we want the
2634        // NumLock and Shift to neutralize each other, thus, we want the normal
2635        // sequence.
2636        return normal;
2637    }
2638    // If Shift is not pressed and NumLock is on, a different virtual key code
2639    // is returned by Windows, which can be taken care of by a different case
2640    // statement in _console_read().
2641}
2642
2643// Write sequence to buf and return the number of bytes written.
2644static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2645    DWORD control_key_state, const char* const normal) {
2646    // Copy the base sequence into buf.
2647    const size_t len = strlen(normal);
2648    memcpy(buf, normal, len);
2649
2650    int code = 0;
2651
2652    control_key_state = _normalize_keypad_control_key_state(vk,
2653        control_key_state);
2654
2655    if (_is_shift_pressed(control_key_state)) {
2656        code |= 0x1;
2657    }
2658    if (_is_alt_pressed(control_key_state)) {   // any alt key pressed
2659        code |= 0x2;
2660    }
2661    if (_is_ctrl_pressed(control_key_state)) {  // any control key pressed
2662        code |= 0x4;
2663    }
2664    // If some modifier was held down, then we need to insert the modifier code
2665    if (code != 0) {
2666        if (len == 0) {
2667            // Should be impossible because caller should pass a string of
2668            // non-zero length.
2669            return 0;
2670        }
2671        size_t index = len - 1;
2672        const char lastChar = buf[index];
2673        if (lastChar != '~') {
2674            buf[index++] = '1';
2675        }
2676        buf[index++] = ';';         // modifier separator
2677        // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2678        // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2679        buf[index++] = '1' + code;
2680        buf[index++] = lastChar;    // move ~ (or other last char) to the end
2681        return index;
2682    }
2683    return len;
2684}
2685
2686// Write sequence to buf and return the number of bytes written.
2687static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2688    const DWORD control_key_state, const char* const normal,
2689    const char shifted) {
2690    if (_is_shift_pressed(control_key_state)) {
2691        // Shift is pressed and NumLock is off
2692        if (shifted != '\0') {
2693            buf[0] = shifted;
2694            return sizeof(buf[0]);
2695        } else {
2696            return 0;
2697        }
2698    } else {
2699        // Shift is not pressed and NumLock is off, or,
2700        // Shift is pressed and NumLock is on, in which case we want the
2701        // NumLock and Shift to neutralize each other, thus, we want the normal
2702        // sequence.
2703        return _get_modifier_sequence(buf, vk, control_key_state, normal);
2704    }
2705    // If Shift is not pressed and NumLock is on, a different virtual key code
2706    // is returned by Windows, which can be taken care of by a different case
2707    // statement in _console_read().
2708}
2709
2710// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2711// Standard German. Figure this out at runtime so we know what to output for
2712// Shift-VK_DELETE.
2713static char _get_decimal_char() {
2714    return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2715}
2716
2717// Prefix the len bytes in buf with the escape character, and then return the
2718// new buffer length.
2719size_t _escape_prefix(char* const buf, const size_t len) {
2720    // If nothing to prefix, don't do anything. We might be called with
2721    // len == 0, if alt was held down with a dead key which produced nothing.
2722    if (len == 0) {
2723        return 0;
2724    }
2725
2726    memmove(&buf[1], buf, len);
2727    buf[0] = '\x1b';
2728    return len + 1;
2729}
2730
2731// Writes to buffer buf (of length len), returning number of bytes written or
2732// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2733// (as far as I can tell).
2734static int _console_read(const HANDLE console, void* buf, size_t len) {
2735    for (;;) {
2736        KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2737        if (key_event == NULL) {
2738            return -1;
2739        }
2740
2741        const WORD vk = key_event->wVirtualKeyCode;
2742        const CHAR ch = key_event->uChar.AsciiChar;
2743        const DWORD control_key_state = _normalize_altgr_control_key_state(
2744            key_event);
2745
2746        // The following emulation code should write the output sequence to
2747        // either seqstr or to seqbuf and seqbuflen.
2748        const char* seqstr = NULL;  // NULL terminated C-string
2749        // Enough space for max sequence string below, plus modifiers and/or
2750        // escape prefix.
2751        char seqbuf[16];
2752        size_t seqbuflen = 0;       // Space used in seqbuf.
2753
2754#define MATCH(vk, normal) \
2755            case (vk): \
2756            { \
2757                seqstr = (normal); \
2758            } \
2759            break;
2760
2761        // Modifier keys should affect the output sequence.
2762#define MATCH_MODIFIER(vk, normal) \
2763            case (vk): \
2764            { \
2765                seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2766                    control_key_state, (normal)); \
2767            } \
2768            break;
2769
2770        // The shift key should affect the output sequence.
2771#define MATCH_KEYPAD(vk, normal, shifted) \
2772            case (vk): \
2773            { \
2774                seqstr = _get_keypad_sequence(control_key_state, (normal), \
2775                    (shifted)); \
2776            } \
2777            break;
2778
2779        // The shift key and other modifier keys should affect the output
2780        // sequence.
2781#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2782            case (vk): \
2783            { \
2784                seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2785                    control_key_state, (normal), (shifted)); \
2786            } \
2787            break;
2788
2789#define ESC "\x1b"
2790#define CSI ESC "["
2791#define SS3 ESC "O"
2792
2793        // Only support normal mode, not application mode.
2794
2795        // Enhanced keys:
2796        // * 6-pack: insert, delete, home, end, page up, page down
2797        // * cursor keys: up, down, right, left
2798        // * keypad: divide, enter
2799        // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2800        //   VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2801        if (_is_enhanced_key(control_key_state)) {
2802            switch (vk) {
2803                case VK_RETURN: // Enter key on keypad
2804                    if (_is_ctrl_pressed(control_key_state)) {
2805                        seqstr = "\n";
2806                    } else {
2807                        seqstr = "\r";
2808                    }
2809                    break;
2810
2811                MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2812                MATCH_MODIFIER(VK_NEXT,  CSI "6~"); // Page Down
2813
2814                // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2815                // will be fixed soon to match xterm which sends CSI "F" and
2816                // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2817                MATCH(VK_END,  CSI "F");
2818                MATCH(VK_HOME, CSI "H");
2819
2820                MATCH_MODIFIER(VK_LEFT,  CSI "D");
2821                MATCH_MODIFIER(VK_UP,    CSI "A");
2822                MATCH_MODIFIER(VK_RIGHT, CSI "C");
2823                MATCH_MODIFIER(VK_DOWN,  CSI "B");
2824
2825                MATCH_MODIFIER(VK_INSERT, CSI "2~");
2826                MATCH_MODIFIER(VK_DELETE, CSI "3~");
2827
2828                MATCH(VK_DIVIDE, "/");
2829            }
2830        } else {    // Non-enhanced keys:
2831            switch (vk) {
2832                case VK_BACK:   // backspace
2833                    if (_is_alt_pressed(control_key_state)) {
2834                        seqstr = ESC "\x7f";
2835                    } else {
2836                        seqstr = "\x7f";
2837                    }
2838                    break;
2839
2840                case VK_TAB:
2841                    if (_is_shift_pressed(control_key_state)) {
2842                        seqstr = CSI "Z";
2843                    } else {
2844                        seqstr = "\t";
2845                    }
2846                    break;
2847
2848                // Number 5 key in keypad when NumLock is off, or if NumLock is
2849                // on and Shift is down.
2850                MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2851
2852                case VK_RETURN:     // Enter key on main keyboard
2853                    if (_is_alt_pressed(control_key_state)) {
2854                        seqstr = ESC "\n";
2855                    } else if (_is_ctrl_pressed(control_key_state)) {
2856                        seqstr = "\n";
2857                    } else {
2858                        seqstr = "\r";
2859                    }
2860                    break;
2861
2862                // VK_ESCAPE: Don't do any special handling. The OS uses many
2863                // of the sequences with Escape and many of the remaining
2864                // sequences don't produce bKeyDown messages, only !bKeyDown
2865                // for whatever reason.
2866
2867                case VK_SPACE:
2868                    if (_is_alt_pressed(control_key_state)) {
2869                        seqstr = ESC " ";
2870                    } else if (_is_ctrl_pressed(control_key_state)) {
2871                        seqbuf[0] = '\0';   // NULL char
2872                        seqbuflen = 1;
2873                    } else {
2874                        seqstr = " ";
2875                    }
2876                    break;
2877
2878                MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2879                MATCH_MODIFIER_KEYPAD(VK_NEXT,  CSI "6~", '3'); // Page Down
2880
2881                MATCH_KEYPAD(VK_END,  CSI "4~", "1");
2882                MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2883
2884                MATCH_MODIFIER_KEYPAD(VK_LEFT,  CSI "D", '4');
2885                MATCH_MODIFIER_KEYPAD(VK_UP,    CSI "A", '8');
2886                MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2887                MATCH_MODIFIER_KEYPAD(VK_DOWN,  CSI "B", '2');
2888
2889                MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2890                MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2891                    _get_decimal_char());
2892
2893                case 0x30:          // 0
2894                case 0x31:          // 1
2895                case 0x39:          // 9
2896                case VK_OEM_1:      // ;:
2897                case VK_OEM_PLUS:   // =+
2898                case VK_OEM_COMMA:  // ,<
2899                case VK_OEM_PERIOD: // .>
2900                case VK_OEM_7:      // '"
2901                case VK_OEM_102:    // depends on keyboard, could be <> or \|
2902                case VK_OEM_2:      // /?
2903                case VK_OEM_3:      // `~
2904                case VK_OEM_4:      // [{
2905                case VK_OEM_5:      // \|
2906                case VK_OEM_6:      // ]}
2907                {
2908                    seqbuflen = _get_control_character(seqbuf, key_event,
2909                        control_key_state);
2910
2911                    if (_is_alt_pressed(control_key_state)) {
2912                        seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2913                    }
2914                }
2915                break;
2916
2917                case 0x32:          // 2
2918                case 0x36:          // 6
2919                case VK_OEM_MINUS:  // -_
2920                {
2921                    seqbuflen = _get_control_character(seqbuf, key_event,
2922                        control_key_state);
2923
2924                    // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2925                    // prefix with escape.
2926                    if (_is_alt_pressed(control_key_state) &&
2927                        !(_is_ctrl_pressed(control_key_state) &&
2928                        !_is_shift_pressed(control_key_state))) {
2929                        seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2930                    }
2931                }
2932                break;
2933
2934                case 0x33:  // 3
2935                case 0x34:  // 4
2936                case 0x35:  // 5
2937                case 0x37:  // 7
2938                case 0x38:  // 8
2939                {
2940                    seqbuflen = _get_control_character(seqbuf, key_event,
2941                        control_key_state);
2942
2943                    // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2944                    // prefix with escape.
2945                    if (_is_alt_pressed(control_key_state) &&
2946                        !(_is_ctrl_pressed(control_key_state) &&
2947                        !_is_shift_pressed(control_key_state))) {
2948                        seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2949                    }
2950                }
2951                break;
2952
2953                case 0x41:  // a
2954                case 0x42:  // b
2955                case 0x43:  // c
2956                case 0x44:  // d
2957                case 0x45:  // e
2958                case 0x46:  // f
2959                case 0x47:  // g
2960                case 0x48:  // h
2961                case 0x49:  // i
2962                case 0x4a:  // j
2963                case 0x4b:  // k
2964                case 0x4c:  // l
2965                case 0x4d:  // m
2966                case 0x4e:  // n
2967                case 0x4f:  // o
2968                case 0x50:  // p
2969                case 0x51:  // q
2970                case 0x52:  // r
2971                case 0x53:  // s
2972                case 0x54:  // t
2973                case 0x55:  // u
2974                case 0x56:  // v
2975                case 0x57:  // w
2976                case 0x58:  // x
2977                case 0x59:  // y
2978                case 0x5a:  // z
2979                {
2980                    seqbuflen = _get_non_alt_char(seqbuf, key_event,
2981                        control_key_state);
2982
2983                    // If Alt is pressed, then prefix with escape.
2984                    if (_is_alt_pressed(control_key_state)) {
2985                        seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2986                    }
2987                }
2988                break;
2989
2990                // These virtual key codes are generated by the keys on the
2991                // keypad *when NumLock is on* and *Shift is up*.
2992                MATCH(VK_NUMPAD0, "0");
2993                MATCH(VK_NUMPAD1, "1");
2994                MATCH(VK_NUMPAD2, "2");
2995                MATCH(VK_NUMPAD3, "3");
2996                MATCH(VK_NUMPAD4, "4");
2997                MATCH(VK_NUMPAD5, "5");
2998                MATCH(VK_NUMPAD6, "6");
2999                MATCH(VK_NUMPAD7, "7");
3000                MATCH(VK_NUMPAD8, "8");
3001                MATCH(VK_NUMPAD9, "9");
3002
3003                MATCH(VK_MULTIPLY, "*");
3004                MATCH(VK_ADD,      "+");
3005                MATCH(VK_SUBTRACT, "-");
3006                // VK_DECIMAL is generated by the . key on the keypad *when
3007                // NumLock is on* and *Shift is up* and the sequence is not
3008                // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3009                // Windows Security screen to come up).
3010                case VK_DECIMAL:
3011                    // U.S. English uses '.', Germany German uses ','.
3012                    seqbuflen = _get_non_control_char(seqbuf, key_event,
3013                        control_key_state);
3014                    break;
3015
3016                MATCH_MODIFIER(VK_F1,  SS3 "P");
3017                MATCH_MODIFIER(VK_F2,  SS3 "Q");
3018                MATCH_MODIFIER(VK_F3,  SS3 "R");
3019                MATCH_MODIFIER(VK_F4,  SS3 "S");
3020                MATCH_MODIFIER(VK_F5,  CSI "15~");
3021                MATCH_MODIFIER(VK_F6,  CSI "17~");
3022                MATCH_MODIFIER(VK_F7,  CSI "18~");
3023                MATCH_MODIFIER(VK_F8,  CSI "19~");
3024                MATCH_MODIFIER(VK_F9,  CSI "20~");
3025                MATCH_MODIFIER(VK_F10, CSI "21~");
3026                MATCH_MODIFIER(VK_F11, CSI "23~");
3027                MATCH_MODIFIER(VK_F12, CSI "24~");
3028
3029                MATCH_MODIFIER(VK_F13, CSI "25~");
3030                MATCH_MODIFIER(VK_F14, CSI "26~");
3031                MATCH_MODIFIER(VK_F15, CSI "28~");
3032                MATCH_MODIFIER(VK_F16, CSI "29~");
3033                MATCH_MODIFIER(VK_F17, CSI "31~");
3034                MATCH_MODIFIER(VK_F18, CSI "32~");
3035                MATCH_MODIFIER(VK_F19, CSI "33~");
3036                MATCH_MODIFIER(VK_F20, CSI "34~");
3037
3038                // MATCH_MODIFIER(VK_F21, ???);
3039                // MATCH_MODIFIER(VK_F22, ???);
3040                // MATCH_MODIFIER(VK_F23, ???);
3041                // MATCH_MODIFIER(VK_F24, ???);
3042            }
3043        }
3044
3045#undef MATCH
3046#undef MATCH_MODIFIER
3047#undef MATCH_KEYPAD
3048#undef MATCH_MODIFIER_KEYPAD
3049#undef ESC
3050#undef CSI
3051#undef SS3
3052
3053        const char* out;
3054        size_t outlen;
3055
3056        // Check for output in any of:
3057        // * seqstr is set (and strlen can be used to determine the length).
3058        // * seqbuf and seqbuflen are set
3059        // Fallback to ch from Windows.
3060        if (seqstr != NULL) {
3061            out = seqstr;
3062            outlen = strlen(seqstr);
3063        } else if (seqbuflen > 0) {
3064            out = seqbuf;
3065            outlen = seqbuflen;
3066        } else if (ch != '\0') {
3067            // Use whatever Windows told us it is.
3068            seqbuf[0] = ch;
3069            seqbuflen = 1;
3070            out = seqbuf;
3071            outlen = seqbuflen;
3072        } else {
3073            // No special handling for the virtual key code and Windows isn't
3074            // telling us a character code, then we don't know how to translate
3075            // the key press.
3076            //
3077            // Consume the input and 'continue' to cause us to get a new key
3078            // event.
3079            D("_console_read: unknown virtual key code: %d, enhanced: %s\n",
3080                vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3081            key_event->wRepeatCount = 0;
3082            continue;
3083        }
3084
3085        int bytesRead = 0;
3086
3087        // put output wRepeatCount times into buf/len
3088        while (key_event->wRepeatCount > 0) {
3089            if (len >= outlen) {
3090                // Write to buf/len
3091                memcpy(buf, out, outlen);
3092                buf = (void*)((char*)buf + outlen);
3093                len -= outlen;
3094                bytesRead += outlen;
3095
3096                // consume the input
3097                --key_event->wRepeatCount;
3098            } else {
3099                // Not enough space, so just leave it in _win32_input_record
3100                // for a subsequent retrieval.
3101                if (bytesRead == 0) {
3102                    // We didn't write anything because there wasn't enough
3103                    // space to even write one sequence. This should never
3104                    // happen if the caller uses sensible buffer sizes
3105                    // (i.e. >= maximum sequence length which is probably a
3106                    // few bytes long).
3107                    D("_console_read: no buffer space to write one sequence; "
3108                        "buffer: %ld, sequence: %ld\n", (long)len,
3109                        (long)outlen);
3110                    errno = ENOMEM;
3111                    return -1;
3112                } else {
3113                    // Stop trying to write to buf/len, just return whatever
3114                    // we wrote so far.
3115                    break;
3116                }
3117            }
3118        }
3119
3120        return bytesRead;
3121    }
3122}
3123
3124static DWORD _old_console_mode; // previous GetConsoleMode() result
3125static HANDLE _console_handle;  // when set, console mode should be restored
3126
3127void stdin_raw_init(const int fd) {
3128    if (STDIN_FILENO == fd) {
3129        const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3130        if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3131            return;
3132        }
3133
3134        if (GetFileType(in) != FILE_TYPE_CHAR) {
3135            // stdin might be a file or pipe.
3136            return;
3137        }
3138
3139        if (!GetConsoleMode(in, &_old_console_mode)) {
3140            // If GetConsoleMode() fails, stdin is probably is not a console.
3141            return;
3142        }
3143
3144        // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3145        // calling the process Ctrl-C routine (configured by
3146        // SetConsoleCtrlHandler()).
3147        // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3148        // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3149        // flag also seems necessary to have proper line-ending processing.
3150        if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3151            ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3152            // This really should not fail.
3153            D("stdin_raw_init: SetConsoleMode() failed: %s\n",
3154              SystemErrorCodeToString(GetLastError()).c_str());
3155        }
3156
3157        // Once this is set, it means that stdin has been configured for
3158        // reading from and that the old console mode should be restored later.
3159        _console_handle = in;
3160
3161        // Note that we don't need to configure C Runtime line-ending
3162        // translation because _console_read() does not call the C Runtime to
3163        // read from the console.
3164    }
3165}
3166
3167void stdin_raw_restore(const int fd) {
3168    if (STDIN_FILENO == fd) {
3169        if (_console_handle != NULL) {
3170            const HANDLE in = _console_handle;
3171            _console_handle = NULL;  // clear state
3172
3173            if (!SetConsoleMode(in, _old_console_mode)) {
3174                // This really should not fail.
3175                D("stdin_raw_restore: SetConsoleMode() failed: %s\n",
3176                  SystemErrorCodeToString(GetLastError()).c_str());
3177            }
3178        }
3179    }
3180}
3181
3182// Called by 'adb shell' and 'adb exec-in' to read from stdin.
3183int unix_read(int fd, void* buf, size_t len) {
3184    if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3185        // If it is a request to read from stdin, and stdin_raw_init() has been
3186        // called, and it successfully configured the console, then read from
3187        // the console using Win32 console APIs and partially emulate a unix
3188        // terminal.
3189        return _console_read(_console_handle, buf, len);
3190    } else {
3191        // Just call into C Runtime which can read from pipes/files and which
3192        // can do LF/CR translation (which is overridable with _setmode()).
3193        // Undefine the macro that is set in sysdeps.h which bans calls to
3194        // plain read() in favor of unix_read() or adb_read().
3195#pragma push_macro("read")
3196#undef read
3197        return read(fd, buf, len);
3198#pragma pop_macro("read")
3199    }
3200}
3201
3202/**************************************************************************/
3203/**************************************************************************/
3204/*****                                                                *****/
3205/*****      Unicode support                                           *****/
3206/*****                                                                *****/
3207/**************************************************************************/
3208/**************************************************************************/
3209
3210// This implements support for using files with Unicode filenames and for
3211// outputting Unicode text to a Win32 console window. This is inspired from
3212// http://utf8everywhere.org/.
3213//
3214// Background
3215// ----------
3216//
3217// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3218// filenames to APIs such as open(). This works because filenames are largely
3219// opaque 'cookies' (perhaps excluding path separators).
3220//
3221// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3222// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3223// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3224// CreateFile() API is really just a macro that adds the W/A based on whether
3225// the UNICODE preprocessor symbol is defined).
3226//
3227// Options
3228// -------
3229//
3230// Thus, to write a portable program, there are a few options:
3231//
3232// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3233//    For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3234//    that takes a wchar_t string, converts it to UTF-8 and then calls the real
3235//    open() API.
3236//
3237// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3238//    1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3239//    potentially touching a lot of code.
3240//
3241// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3242//    UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3243//    takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3244//    or C Runtime API.
3245//
3246// The Choice
3247// ----------
3248//
3249// The code below chooses option 3, the UTF-8 everywhere strategy. It
3250// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3251// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3252// args that are passed to main() at the beginning of program startup. We also
3253// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3254// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3255//
3256// Unicode console output
3257// ----------------------
3258//
3259// The way to output Unicode to a Win32 console window is to call
3260// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
3261// such as Lucida Console or Consolas, and in the case of East Asian languages
3262// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3263// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3264// font to be used in console windows.)
3265//
3266// The problem is getting the C Runtime to make fprintf and related APIs call
3267// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3268// promising, but the various modes have issues:
3269//
3270// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3271//    UTF-16 do not display properly.
3272// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3273//    totally wrong.
3274// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3275//    handler to be called (upon a later I/O call), aborting the process.
3276// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3277//    to output nothing.
3278//
3279// So the only solution is to write our own adb_fprintf() that converts UTF-8
3280// to UTF-16 and then calls WriteConsoleW().
3281
3282
3283// Function prototype because attributes cannot be placed on func definitions.
3284static void _widen_fatal(const char *fmt, ...)
3285    __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3286
3287// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3288// called from those functions.
3289static void _widen_fatal(const char *fmt, ...) {
3290    va_list ap;
3291    va_start(ap, fmt);
3292    // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3293    // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3294    // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3295    // By directly calling real C Runtime APIs that don't properly output
3296    // Unicode, but will be able to get a comprehendible message out. To do
3297    // this, make sure we don't call (v)fprintf macros by undefining them.
3298#pragma push_macro("fprintf")
3299#pragma push_macro("vfprintf")
3300#undef fprintf
3301#undef vfprintf
3302    fprintf(stderr, "error: ");
3303    vfprintf(stderr, fmt, ap);
3304    fprintf(stderr, "\n");
3305#pragma pop_macro("vfprintf")
3306#pragma pop_macro("fprintf")
3307    va_end(ap);
3308    exit(-1);
3309}
3310
3311// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3312// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3313
3314// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3315// string. Any other size specifies the number of chars to convert, excluding
3316// any NULL terminator (if you're passing an explicit size, you probably don't
3317// have a NULL terminated string in the first place).
3318std::wstring widen(const char* utf8, const int size) {
3319    // Note: Do not call SystemErrorCodeToString() from widen() because
3320    // SystemErrorCodeToString() calls narrow() which may call fatal() which
3321    // calls adb_vfprintf() which calls widen(), potentially causing infinite
3322    // recursion.
3323    const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3324                                                     NULL, 0);
3325    if (chars_to_convert <= 0) {
3326        // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3327        _widen_fatal("MultiByteToWideChar failed counting: %d, "
3328                     "GetLastError: %lu", chars_to_convert, GetLastError());
3329    }
3330
3331    std::wstring utf16;
3332    size_t chars_to_allocate = chars_to_convert;
3333    if (size == -1) {
3334        // chars_to_convert includes a NULL terminator, so subtract space
3335        // for that because resize() includes that itself.
3336        --chars_to_allocate;
3337    }
3338    utf16.resize(chars_to_allocate);
3339
3340    // This uses &string[0] to get write-access to the entire string buffer
3341    // which may be assuming that the chars are all contiguous, but it seems
3342    // to work and saves us the hassle of using a temporary
3343    // std::vector<wchar_t>.
3344    const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3345                                           chars_to_convert);
3346    if (result != chars_to_convert) {
3347        // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3348        _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3349                     "GetLastError: %lu", result, GetLastError());
3350    }
3351
3352    // If a size was passed in (size != -1), then the string is NULL terminated
3353    // by a NULL char that was written by std::string::resize(). If size == -1,
3354    // then MultiByteToWideChar() read a NULL terminator from the original
3355    // string and converted it to a NULL UTF-16 char in the output.
3356
3357    return utf16;
3358}
3359
3360// Convert a NULL terminated string from UTF-8 to UTF-16.
3361std::wstring widen(const char* utf8) {
3362    // Pass -1 to let widen() determine the string length.
3363    return widen(utf8, -1);
3364}
3365
3366// Convert from UTF-8 to UTF-16.
3367std::wstring widen(const std::string& utf8) {
3368    return widen(utf8.c_str(), utf8.length());
3369}
3370
3371// Convert from UTF-16 to UTF-8.
3372std::string narrow(const std::wstring& utf16) {
3373    return narrow(utf16.c_str());
3374}
3375
3376// Convert from UTF-16 to UTF-8.
3377std::string narrow(const wchar_t* utf16) {
3378    // Note: Do not call SystemErrorCodeToString() from narrow() because
3379    // SystemErrorCodeToString() calls narrow() and we don't want potential
3380    // infinite recursion.
3381    const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3382                                                   0, NULL, NULL);
3383    if (chars_required <= 0) {
3384        // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
3385        fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
3386              chars_required, GetLastError());
3387    }
3388
3389    std::string utf8;
3390    // Subtract space for the NULL terminator because resize() includes
3391    // that itself. Note that this could potentially throw a std::bad_alloc
3392    // exception.
3393    utf8.resize(chars_required - 1);
3394
3395    // This uses &string[0] to get write-access to the entire string buffer
3396    // which may be assuming that the chars are all contiguous, but it seems
3397    // to work and saves us the hassle of using a temporary
3398    // std::vector<char>.
3399    const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3400                                           chars_required, NULL, NULL);
3401    if (result != chars_required) {
3402        // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
3403        fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
3404              result, GetLastError());
3405    }
3406
3407    return utf8;
3408}
3409
3410// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3411// be passed to main().
3412NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3413    narrow_args = new char*[argc + 1];
3414
3415    for (int i = 0; i < argc; ++i) {
3416        narrow_args[i] = strdup(narrow(argv[i]).c_str());
3417    }
3418    narrow_args[argc] = nullptr;   // terminate
3419}
3420
3421NarrowArgs::~NarrowArgs() {
3422    if (narrow_args != nullptr) {
3423        for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3424            free(*argp);
3425        }
3426        delete[] narrow_args;
3427        narrow_args = nullptr;
3428    }
3429}
3430
3431int unix_open(const char* path, int options, ...) {
3432    if ((options & O_CREAT) == 0) {
3433        return _wopen(widen(path).c_str(), options);
3434    } else {
3435        int      mode;
3436        va_list  args;
3437        va_start(args, options);
3438        mode = va_arg(args, int);
3439        va_end(args);
3440        return _wopen(widen(path).c_str(), options, mode);
3441    }
3442}
3443
3444// Version of stat() that takes a UTF-8 path.
3445int adb_stat(const char* f, struct adb_stat* s) {
3446#pragma push_macro("wstat")
3447// This definition of wstat seems to be missing from <sys/stat.h>.
3448#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3449#ifdef _USE_32BIT_TIME_T
3450#define wstat _wstat32i64
3451#else
3452#define wstat _wstat64
3453#endif
3454#else
3455// <sys/stat.h> has a function prototype for wstat() that should be available.
3456#endif
3457
3458    return wstat(widen(f).c_str(), s);
3459
3460#pragma pop_macro("wstat")
3461}
3462
3463// Version of opendir() that takes a UTF-8 path.
3464DIR* adb_opendir(const char* name) {
3465    // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3466    // the fields, but right now all the callers treat the structure as
3467    // opaque.
3468    return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3469}
3470
3471// Version of readdir() that returns UTF-8 paths.
3472struct dirent* adb_readdir(DIR* dir) {
3473    _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3474    struct _wdirent* const went = _wreaddir(wdir);
3475    if (went == nullptr) {
3476        return nullptr;
3477    }
3478    // Convert from UTF-16 to UTF-8.
3479    const std::string name_utf8(narrow(went->d_name));
3480
3481    // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3482    // space for UTF-16 wchar_t's) with UTF-8 char's.
3483    struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3484
3485    if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3486        // Name too big to fit in existing buffer.
3487        errno = ENOMEM;
3488        return nullptr;
3489    }
3490
3491    // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3492    // because _wdirent contains wchar_t instead of char. So even if name_utf8
3493    // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3494    // bigger than the caller expects because they expect a dirent structure
3495    // which has a smaller d_name field. Ignore this since the caller should be
3496    // resilient.
3497
3498    // Rewrite the UTF-16 d_name field to UTF-8.
3499    strcpy(ent->d_name, name_utf8.c_str());
3500
3501    return ent;
3502}
3503
3504// Version of closedir() to go with our version of adb_opendir().
3505int adb_closedir(DIR* dir) {
3506    return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3507}
3508
3509// Version of unlink() that takes a UTF-8 path.
3510int adb_unlink(const char* path) {
3511    const std::wstring wpath(widen(path));
3512
3513    int  rc = _wunlink(wpath.c_str());
3514
3515    if (rc == -1 && errno == EACCES) {
3516        /* unlink returns EACCES when the file is read-only, so we first */
3517        /* try to make it writable, then unlink again...                 */
3518        rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3519        if (rc == 0)
3520            rc = _wunlink(wpath.c_str());
3521    }
3522    return rc;
3523}
3524
3525// Version of mkdir() that takes a UTF-8 path.
3526int adb_mkdir(const std::string& path, int mode) {
3527    return _wmkdir(widen(path.c_str()).c_str());
3528}
3529
3530// Version of utime() that takes a UTF-8 path.
3531int adb_utime(const char* path, struct utimbuf* u) {
3532    static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3533        "utimbuf and _utimbuf should be the same size because they both "
3534        "contain the same types, namely time_t");
3535    return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3536}
3537
3538// Version of chmod() that takes a UTF-8 path.
3539int adb_chmod(const char* path, int mode) {
3540    return _wchmod(widen(path).c_str(), mode);
3541}
3542
3543// Internal function to get a Win32 console HANDLE from a C Runtime FILE*.
3544static HANDLE _get_console_handle(FILE* const stream) {
3545    // Get a C Runtime file descriptor number from the FILE* structure.
3546    const int fd = fileno(stream);
3547    if (fd < 0) {
3548        return NULL;
3549    }
3550
3551    // If it is not a "character device", it is probably a file and not a
3552    // console. Do this check early because it is probably cheap. Still do more
3553    // checks after this since there are devices that pass this test, but are
3554    // not a console, such as NUL, the Windows /dev/null equivalent (I think).
3555    if (!isatty(fd)) {
3556        return NULL;
3557    }
3558
3559    // Given a C Runtime file descriptor number, get the underlying OS
3560    // file handle.
3561    const intptr_t osfh = _get_osfhandle(fd);
3562    if (osfh == -1) {
3563        return NULL;
3564    }
3565
3566    const HANDLE h = reinterpret_cast<const HANDLE>(osfh);
3567
3568    DWORD old_mode = 0;
3569    if (!GetConsoleMode(h, &old_mode)) {
3570        return NULL;
3571    }
3572
3573    // If GetConsoleMode() was successful, assume this is a console.
3574    return h;
3575}
3576
3577// Internal helper function to write UTF-8 bytes to a console. Returns -1
3578// on error.
3579static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3580                               HANDLE console) {
3581    // Convert from UTF-8 to UTF-16.
3582    // This could throw std::bad_alloc.
3583    const std::wstring output(widen(buf, size));
3584
3585    // Note that this does not do \n => \r\n translation because that
3586    // doesn't seem necessary for the Windows console. For the Windows
3587    // console \r moves to the beginning of the line and \n moves to a new
3588    // line.
3589
3590    // Flush any stream buffering so that our output is afterwards which
3591    // makes sense because our call is afterwards.
3592    (void)fflush(stream);
3593
3594    // Write UTF-16 to the console.
3595    DWORD written = 0;
3596    if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3597                       NULL)) {
3598        errno = EIO;
3599        return -1;
3600    }
3601
3602    // This is the number of UTF-16 chars written, which might be different
3603    // than the number of UTF-8 chars passed in. It doesn't seem practical to
3604    // get this count correct.
3605    return written;
3606}
3607
3608// Function prototype because attributes cannot be placed on func definitions.
3609static int _console_vfprintf(const HANDLE console, FILE* stream,
3610                             const char *format, va_list ap)
3611    __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3612
3613// Internal function to format a UTF-8 string and write it to a Win32 console.
3614// Returns -1 on error.
3615static int _console_vfprintf(const HANDLE console, FILE* stream,
3616                             const char *format, va_list ap) {
3617    std::string output_utf8;
3618
3619    // Format the string.
3620    // This could throw std::bad_alloc.
3621    android::base::StringAppendV(&output_utf8, format, ap);
3622
3623    return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3624                               stream, console);
3625}
3626
3627// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3628// Windows console.
3629int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3630    const HANDLE console = _get_console_handle(stream);
3631
3632    // If there is an associated Win32 console, write to it specially,
3633    // otherwise defer to the regular C Runtime, passing it UTF-8.
3634    if (console != NULL) {
3635        return _console_vfprintf(console, stream, format, ap);
3636    } else {
3637        // If vfprintf is a macro, undefine it, so we can call the real
3638        // C Runtime API.
3639#pragma push_macro("vfprintf")
3640#undef vfprintf
3641        return vfprintf(stream, format, ap);
3642#pragma pop_macro("vfprintf")
3643    }
3644}
3645
3646// Version of fprintf() that takes UTF-8 and can write Unicode to a
3647// Windows console.
3648int adb_fprintf(FILE *stream, const char *format, ...) {
3649    va_list ap;
3650    va_start(ap, format);
3651    const int result = adb_vfprintf(stream, format, ap);
3652    va_end(ap);
3653
3654    return result;
3655}
3656
3657// Version of printf() that takes UTF-8 and can write Unicode to a
3658// Windows console.
3659int adb_printf(const char *format, ...) {
3660    va_list ap;
3661    va_start(ap, format);
3662    const int result = adb_vfprintf(stdout, format, ap);
3663    va_end(ap);
3664
3665    return result;
3666}
3667
3668// Version of fputs() that takes UTF-8 and can write Unicode to a
3669// Windows console.
3670int adb_fputs(const char* buf, FILE* stream) {
3671    // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3672    // which fputs (and hence adb_fputs) should return on error.
3673    return adb_fprintf(stream, "%s", buf);
3674}
3675
3676// Version of fputc() that takes UTF-8 and can write Unicode to a
3677// Windows console.
3678int adb_fputc(int ch, FILE* stream) {
3679    const int result = adb_fprintf(stream, "%c", ch);
3680    if (result <= 0) {
3681        // If there was an error, or if nothing was printed (which should be an
3682        // error), return an error, which fprintf signifies with EOF.
3683        return EOF;
3684    }
3685    // For success, fputc returns the char, cast to unsigned char, then to int.
3686    return static_cast<unsigned char>(ch);
3687}
3688
3689// Internal function to write UTF-8 to a Win32 console. Returns the number of
3690// items (of length size) written. On error, returns a short item count or 0.
3691static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3692                              FILE* stream, HANDLE console) {
3693    // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3694    // if we're passed only some of the bytes of a character (for example, from
3695    // the network socket for adb shell), we won't be able to convert the char
3696    // to a complete UTF-16 char (or surrogate pair), so the output won't look
3697    // right.
3698    //
3699    // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3700    //
3701    // For now we ignore this problem because the alternative is that we'd have
3702    // to parse UTF-8 and buffer things up (doable). At least this is better
3703    // than what we had before -- always incorrect multi-byte UTF-8 output.
3704    int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3705                                     size * nmemb, stream, console);
3706    if (result == -1) {
3707        return 0;
3708    }
3709    return result / size;
3710}
3711
3712// Version of fwrite() that takes UTF-8 and can write Unicode to a
3713// Windows console.
3714size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3715    const HANDLE console = _get_console_handle(stream);
3716
3717    // If there is an associated Win32 console, write to it specially,
3718    // otherwise defer to the regular C Runtime, passing it UTF-8.
3719    if (console != NULL) {
3720        return _console_fwrite(ptr, size, nmemb, stream, console);
3721    } else {
3722        // If fwrite is a macro, undefine it, so we can call the real
3723        // C Runtime API.
3724#pragma push_macro("fwrite")
3725#undef fwrite
3726        return fwrite(ptr, size, nmemb, stream);
3727#pragma pop_macro("fwrite")
3728    }
3729}
3730
3731// Version of fopen() that takes a UTF-8 filename and can access a file with
3732// a Unicode filename.
3733FILE* adb_fopen(const char* f, const char* m) {
3734    return _wfopen(widen(f).c_str(), widen(m).c_str());
3735}
3736
3737// Shadow UTF-8 environment variable name/value pairs that are created from
3738// _wenviron the first time that adb_getenv() is called. Note that this is not
3739// currently updated if putenv, setenv, unsetenv are called. Note that no
3740// thread synchronization is done, but we're called early enough in
3741// single-threaded startup that things work ok.
3742static std::unordered_map<std::string, char*> g_environ_utf8;
3743
3744// Make sure that shadow UTF-8 environment variables are setup.
3745static void _ensure_env_setup() {
3746    // If some name/value pairs exist, then we've already done the setup below.
3747    if (g_environ_utf8.size() != 0) {
3748        return;
3749    }
3750
3751    // Read name/value pairs from UTF-16 _wenviron and write new name/value
3752    // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3753    // to use the D() macro here because that tracing only works if the
3754    // ADB_TRACE environment variable is setup, but that env var can't be read
3755    // until this code completes.
3756    for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3757        wchar_t* const equal = wcschr(*env, L'=');
3758        if (equal == nullptr) {
3759            // Malformed environment variable with no equal sign. Shouldn't
3760            // really happen, but we should be resilient to this.
3761            continue;
3762        }
3763
3764        const std::string name_utf8(narrow(std::wstring(*env, equal - *env)));
3765        char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3766
3767        // Overwrite any duplicate name, but there shouldn't be a dup in the
3768        // first place.
3769        g_environ_utf8[name_utf8] = value_utf8;
3770    }
3771}
3772
3773// Version of getenv() that takes a UTF-8 environment variable name and
3774// retrieves a UTF-8 value.
3775char* adb_getenv(const char* name) {
3776    _ensure_env_setup();
3777
3778    const auto it = g_environ_utf8.find(std::string(name));
3779    if (it == g_environ_utf8.end()) {
3780        return nullptr;
3781    }
3782
3783    return it->second;
3784}
3785
3786// Version of getcwd() that returns the current working directory in UTF-8.
3787char* adb_getcwd(char* buf, int size) {
3788    wchar_t* wbuf = _wgetcwd(nullptr, 0);
3789    if (wbuf == nullptr) {
3790        return nullptr;
3791    }
3792
3793    const std::string buf_utf8(narrow(wbuf));
3794    free(wbuf);
3795    wbuf = nullptr;
3796
3797    // If size was specified, make sure all the chars will fit.
3798    if (size != 0) {
3799        if (size < static_cast<int>(buf_utf8.length() + 1)) {
3800            errno = ERANGE;
3801            return nullptr;
3802        }
3803    }
3804
3805    // If buf was not specified, allocate storage.
3806    if (buf == nullptr) {
3807        if (size == 0) {
3808            size = buf_utf8.length() + 1;
3809        }
3810        buf = reinterpret_cast<char*>(malloc(size));
3811        if (buf == nullptr) {
3812            return nullptr;
3813        }
3814    }
3815
3816    // Destination buffer was allocated with enough space, or we've already
3817    // checked an existing buffer size for enough space.
3818    strcpy(buf, buf_utf8.c_str());
3819
3820    return buf;
3821}
3822