Home | History | Annotate | Download | only in adb
      1 #include "sysdeps.h"
      2 #include <winsock2.h>
      3 #include <windows.h>
      4 #include <stdio.h>
      5 #include <errno.h>
      6 #define  TRACE_TAG  TRACE_SYSDEPS
      7 #include "adb.h"
      8 
      9 extern void fatal(const char *fmt, ...);
     10 
     11 #define assert(cond)  do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
     12 
     13 /**************************************************************************/
     14 /**************************************************************************/
     15 /*****                                                                *****/
     16 /*****      replaces libs/cutils/load_file.c                          *****/
     17 /*****                                                                *****/
     18 /**************************************************************************/
     19 /**************************************************************************/
     20 
     21 void *load_file(const char *fn, unsigned *_sz)
     22 {
     23     HANDLE    file;
     24     char     *data;
     25     DWORD     file_size;
     26 
     27     file = CreateFile( fn,
     28                        GENERIC_READ,
     29                        FILE_SHARE_READ,
     30                        NULL,
     31                        OPEN_EXISTING,
     32                        0,
     33                        NULL );
     34 
     35     if (file == INVALID_HANDLE_VALUE)
     36         return NULL;
     37 
     38     file_size = GetFileSize( file, NULL );
     39     data      = NULL;
     40 
     41     if (file_size > 0) {
     42         data = (char*) malloc( file_size + 1 );
     43         if (data == NULL) {
     44             D("load_file: could not allocate %ld bytes\n", file_size );
     45             file_size = 0;
     46         } else {
     47             DWORD  out_bytes;
     48 
     49             if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
     50                  out_bytes != file_size )
     51             {
     52                 D("load_file: could not read %ld bytes from '%s'\n", file_size, fn);
     53                 free(data);
     54                 data      = NULL;
     55                 file_size = 0;
     56             }
     57         }
     58     }
     59     CloseHandle( file );
     60 
     61     *_sz = (unsigned) file_size;
     62     return  data;
     63 }
     64 
     65 /**************************************************************************/
     66 /**************************************************************************/
     67 /*****                                                                *****/
     68 /*****    common file descriptor handling                             *****/
     69 /*****                                                                *****/
     70 /**************************************************************************/
     71 /**************************************************************************/
     72 
     73 typedef const struct FHClassRec_*   FHClass;
     74 
     75 typedef struct FHRec_*          FH;
     76 
     77 typedef struct EventHookRec_*  EventHook;
     78 
     79 typedef struct FHClassRec_
     80 {
     81     void (*_fh_init) ( FH  f );
     82     int  (*_fh_close)( FH  f );
     83     int  (*_fh_lseek)( FH  f, int  pos, int  origin );
     84     int  (*_fh_read) ( FH  f, void*  buf, int  len );
     85     int  (*_fh_write)( FH  f, const void*  buf, int  len );
     86     void (*_fh_hook) ( FH  f, int  events, EventHook  hook );
     87 
     88 } FHClassRec;
     89 
     90 /* used to emulate unix-domain socket pairs */
     91 typedef struct SocketPairRec_*  SocketPair;
     92 
     93 typedef struct FHRec_
     94 {
     95     FHClass    clazz;
     96     int        used;
     97     int        eof;
     98     union {
     99         HANDLE      handle;
    100         SOCKET      socket;
    101         SocketPair  pair;
    102     } u;
    103 
    104     HANDLE    event;
    105     int       mask;
    106 
    107     char  name[32];
    108 
    109 } FHRec;
    110 
    111 #define  fh_handle  u.handle
    112 #define  fh_socket  u.socket
    113 #define  fh_pair    u.pair
    114 
    115 #define  WIN32_FH_BASE    100
    116 
    117 #define  WIN32_MAX_FHS    128
    118 
    119 static adb_mutex_t   _win32_lock;
    120 static  FHRec        _win32_fhs[ WIN32_MAX_FHS ];
    121 static  int          _win32_fh_count;
    122 
    123 static FH
    124 _fh_from_int( int   fd )
    125 {
    126     FH  f;
    127 
    128     fd -= WIN32_FH_BASE;
    129 
    130     if (fd < 0 || fd >= _win32_fh_count) {
    131         D( "_fh_from_int: invalid fd %d\n", fd + WIN32_FH_BASE );
    132         errno = EBADF;
    133         return NULL;
    134     }
    135 
    136     f = &_win32_fhs[fd];
    137 
    138     if (f->used == 0) {
    139         D( "_fh_from_int: invalid fd %d\n", fd + WIN32_FH_BASE );
    140         errno = EBADF;
    141         return NULL;
    142     }
    143 
    144     return f;
    145 }
    146 
    147 
    148 static int
    149 _fh_to_int( FH  f )
    150 {
    151     if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
    152         return (int)(f - _win32_fhs) + WIN32_FH_BASE;
    153 
    154     return -1;
    155 }
    156 
    157 static FH
    158 _fh_alloc( FHClass  clazz )
    159 {
    160     int  nn;
    161     FH   f = NULL;
    162 
    163     adb_mutex_lock( &_win32_lock );
    164 
    165     if (_win32_fh_count < WIN32_MAX_FHS) {
    166         f = &_win32_fhs[ _win32_fh_count++ ];
    167         goto Exit;
    168     }
    169 
    170     for (nn = 0; nn < WIN32_MAX_FHS; nn++) {
    171         if ( _win32_fhs[nn].clazz == NULL) {
    172             f = &_win32_fhs[nn];
    173             goto Exit;
    174         }
    175     }
    176     D( "_fh_alloc: no more free file descriptors\n" );
    177 Exit:
    178     if (f) {
    179         f->clazz = clazz;
    180         f->used  = 1;
    181         f->eof   = 0;
    182         clazz->_fh_init(f);
    183     }
    184     adb_mutex_unlock( &_win32_lock );
    185     return f;
    186 }
    187 
    188 
    189 static int
    190 _fh_close( FH   f )
    191 {
    192     if ( f->used ) {
    193         f->clazz->_fh_close( f );
    194         f->used = 0;
    195         f->eof  = 0;
    196         f->clazz = NULL;
    197     }
    198     return 0;
    199 }
    200 
    201 /* forward definitions */
    202 static const FHClassRec   _fh_file_class;
    203 static const FHClassRec   _fh_socket_class;
    204 
    205 /**************************************************************************/
    206 /**************************************************************************/
    207 /*****                                                                *****/
    208 /*****    file-based descriptor handling                              *****/
    209 /*****                                                                *****/
    210 /**************************************************************************/
    211 /**************************************************************************/
    212 
    213 static void
    214 _fh_file_init( FH  f )
    215 {
    216     f->fh_handle = INVALID_HANDLE_VALUE;
    217 }
    218 
    219 static int
    220 _fh_file_close( FH  f )
    221 {
    222     CloseHandle( f->fh_handle );
    223     f->fh_handle = INVALID_HANDLE_VALUE;
    224     return 0;
    225 }
    226 
    227 static int
    228 _fh_file_read( FH  f,  void*  buf, int   len )
    229 {
    230     DWORD  read_bytes;
    231 
    232     if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
    233         D( "adb_read: could not read %d bytes from %s\n", len, f->name );
    234         errno = EIO;
    235         return -1;
    236     } else if (read_bytes < (DWORD)len) {
    237         f->eof = 1;
    238     }
    239     return (int)read_bytes;
    240 }
    241 
    242 static int
    243 _fh_file_write( FH  f,  const void*  buf, int   len )
    244 {
    245     DWORD  wrote_bytes;
    246 
    247     if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
    248         D( "adb_file_write: could not write %d bytes from %s\n", len, f->name );
    249         errno = EIO;
    250         return -1;
    251     } else if (wrote_bytes < (DWORD)len) {
    252         f->eof = 1;
    253     }
    254     return  (int)wrote_bytes;
    255 }
    256 
    257 static int
    258 _fh_file_lseek( FH  f, int  pos, int  origin )
    259 {
    260     DWORD  method;
    261     DWORD  result;
    262 
    263     switch (origin)
    264     {
    265         case SEEK_SET:  method = FILE_BEGIN; break;
    266         case SEEK_CUR:  method = FILE_CURRENT; break;
    267         case SEEK_END:  method = FILE_END; break;
    268         default:
    269             errno = EINVAL;
    270             return -1;
    271     }
    272 
    273     result = SetFilePointer( f->fh_handle, pos, NULL, method );
    274     if (result == INVALID_SET_FILE_POINTER) {
    275         errno = EIO;
    276         return -1;
    277     } else {
    278         f->eof = 0;
    279     }
    280     return (int)result;
    281 }
    282 
    283 static void  _fh_file_hook( FH  f, int  event, EventHook  eventhook );  /* forward */
    284 
    285 static const FHClassRec  _fh_file_class =
    286 {
    287     _fh_file_init,
    288     _fh_file_close,
    289     _fh_file_lseek,
    290     _fh_file_read,
    291     _fh_file_write,
    292     _fh_file_hook
    293 };
    294 
    295 /**************************************************************************/
    296 /**************************************************************************/
    297 /*****                                                                *****/
    298 /*****    file-based descriptor handling                              *****/
    299 /*****                                                                *****/
    300 /**************************************************************************/
    301 /**************************************************************************/
    302 
    303 int  adb_open(const char*  path, int  options)
    304 {
    305     FH  f;
    306 
    307     DWORD  desiredAccess       = 0;
    308     DWORD  shareMode           = FILE_SHARE_READ | FILE_SHARE_WRITE;
    309 
    310     switch (options) {
    311         case O_RDONLY:
    312             desiredAccess = GENERIC_READ;
    313             break;
    314         case O_WRONLY:
    315             desiredAccess = GENERIC_WRITE;
    316             break;
    317         case O_RDWR:
    318             desiredAccess = GENERIC_READ | GENERIC_WRITE;
    319             break;
    320         default:
    321             D("adb_open: invalid options (0x%0x)\n", options);
    322             errno = EINVAL;
    323             return -1;
    324     }
    325 
    326     f = _fh_alloc( &_fh_file_class );
    327     if ( !f ) {
    328         errno = ENOMEM;
    329         return -1;
    330     }
    331 
    332     f->fh_handle = CreateFile( path, desiredAccess, shareMode, NULL, OPEN_EXISTING,
    333                                0, NULL );
    334 
    335     if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
    336         _fh_close(f);
    337         D( "adb_open: could not open '%s':", path );
    338         switch (GetLastError()) {
    339             case ERROR_FILE_NOT_FOUND:
    340                 D( "file not found\n" );
    341                 errno = ENOENT;
    342                 return -1;
    343 
    344             case ERROR_PATH_NOT_FOUND:
    345                 D( "path not found\n" );
    346                 errno = ENOTDIR;
    347                 return -1;
    348 
    349             default:
    350                 D( "unknown error\n" );
    351                 errno = ENOENT;
    352                 return -1;
    353         }
    354     }
    355 
    356     snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
    357     D( "adb_open: '%s' => fd %d\n", path, _fh_to_int(f) );
    358     return _fh_to_int(f);
    359 }
    360 
    361 /* ignore mode on Win32 */
    362 int  adb_creat(const char*  path, int  mode)
    363 {
    364     FH  f;
    365 
    366     f = _fh_alloc( &_fh_file_class );
    367     if ( !f ) {
    368         errno = ENOMEM;
    369         return -1;
    370     }
    371 
    372     f->fh_handle = CreateFile( path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
    373                                NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
    374                                NULL );
    375 
    376     if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
    377         _fh_close(f);
    378         D( "adb_creat: could not open '%s':", path );
    379         switch (GetLastError()) {
    380             case ERROR_FILE_NOT_FOUND:
    381                 D( "file not found\n" );
    382                 errno = ENOENT;
    383                 return -1;
    384 
    385             case ERROR_PATH_NOT_FOUND:
    386                 D( "path not found\n" );
    387                 errno = ENOTDIR;
    388                 return -1;
    389 
    390             default:
    391                 D( "unknown error\n" );
    392                 errno = ENOENT;
    393                 return -1;
    394         }
    395     }
    396     snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
    397     D( "adb_creat: '%s' => fd %d\n", path, _fh_to_int(f) );
    398     return _fh_to_int(f);
    399 }
    400 
    401 
    402 int  adb_read(int  fd, void* buf, int len)
    403 {
    404     FH     f = _fh_from_int(fd);
    405 
    406     if (f == NULL) {
    407         return -1;
    408     }
    409 
    410     return f->clazz->_fh_read( f, buf, len );
    411 }
    412 
    413 
    414 int  adb_write(int  fd, const void*  buf, int  len)
    415 {
    416     FH     f = _fh_from_int(fd);
    417 
    418     if (f == NULL) {
    419         return -1;
    420     }
    421 
    422     return f->clazz->_fh_write(f, buf, len);
    423 }
    424 
    425 
    426 int  adb_lseek(int  fd, int  pos, int  where)
    427 {
    428     FH     f = _fh_from_int(fd);
    429 
    430     if (!f) {
    431         return -1;
    432     }
    433 
    434     return f->clazz->_fh_lseek(f, pos, where);
    435 }
    436 
    437 
    438 int  adb_shutdown(int  fd)
    439 {
    440     FH   f = _fh_from_int(fd);
    441 
    442     if (!f) {
    443         return -1;
    444     }
    445 
    446     D( "adb_shutdown: %s\n", f->name);
    447     shutdown( f->fh_socket, SD_BOTH );
    448     return 0;
    449 }
    450 
    451 
    452 int  adb_close(int  fd)
    453 {
    454     FH   f = _fh_from_int(fd);
    455 
    456     if (!f) {
    457         return -1;
    458     }
    459 
    460     D( "adb_close: %s\n", f->name);
    461     _fh_close(f);
    462     return 0;
    463 }
    464 
    465 /**************************************************************************/
    466 /**************************************************************************/
    467 /*****                                                                *****/
    468 /*****    socket-based file descriptors                               *****/
    469 /*****                                                                *****/
    470 /**************************************************************************/
    471 /**************************************************************************/
    472 
    473 static void
    474 _socket_set_errno( void )
    475 {
    476     switch (WSAGetLastError()) {
    477     case 0:              errno = 0; break;
    478     case WSAEWOULDBLOCK: errno = EAGAIN; break;
    479     case WSAEINTR:       errno = EINTR; break;
    480     default:
    481         D( "_socket_set_errno: unhandled value %d\n", WSAGetLastError() );
    482         errno = EINVAL;
    483     }
    484 }
    485 
    486 static void
    487 _fh_socket_init( FH  f )
    488 {
    489     f->fh_socket = INVALID_SOCKET;
    490     f->event     = WSACreateEvent();
    491     f->mask      = 0;
    492 }
    493 
    494 static int
    495 _fh_socket_close( FH  f )
    496 {
    497     /* gently tell any peer that we're closing the socket */
    498     shutdown( f->fh_socket, SD_BOTH );
    499     closesocket( f->fh_socket );
    500     f->fh_socket = INVALID_SOCKET;
    501     CloseHandle( f->event );
    502     f->mask = 0;
    503     return 0;
    504 }
    505 
    506 static int
    507 _fh_socket_lseek( FH  f, int pos, int origin )
    508 {
    509     errno = EPIPE;
    510     return -1;
    511 }
    512 
    513 static int
    514 _fh_socket_read( FH  f, void*  buf, int  len )
    515 {
    516     int  result = recv( f->fh_socket, buf, len, 0 );
    517     if (result == SOCKET_ERROR) {
    518         _socket_set_errno();
    519         result = -1;
    520     }
    521     return  result;
    522 }
    523 
    524 static int
    525 _fh_socket_write( FH  f, const void*  buf, int  len )
    526 {
    527     int  result = send( f->fh_socket, buf, len, 0 );
    528     if (result == SOCKET_ERROR) {
    529         _socket_set_errno();
    530         result = -1;
    531     }
    532     return result;
    533 }
    534 
    535 static void  _fh_socket_hook( FH  f, int  event, EventHook  hook );  /* forward */
    536 
    537 static const FHClassRec  _fh_socket_class =
    538 {
    539     _fh_socket_init,
    540     _fh_socket_close,
    541     _fh_socket_lseek,
    542     _fh_socket_read,
    543     _fh_socket_write,
    544     _fh_socket_hook
    545 };
    546 
    547 /**************************************************************************/
    548 /**************************************************************************/
    549 /*****                                                                *****/
    550 /*****    replacement for libs/cutils/socket_xxxx.c                   *****/
    551 /*****                                                                *****/
    552 /**************************************************************************/
    553 /**************************************************************************/
    554 
    555 #include <winsock2.h>
    556 
    557 static int  _winsock_init;
    558 
    559 static void
    560 _cleanup_winsock( void )
    561 {
    562     WSACleanup();
    563 }
    564 
    565 static void
    566 _init_winsock( void )
    567 {
    568     if (!_winsock_init) {
    569         WSADATA  wsaData;
    570         int      rc = WSAStartup( MAKEWORD(2,2), &wsaData);
    571         if (rc != 0) {
    572             fatal( "adb: could not initialize Winsock\n" );
    573         }
    574         atexit( _cleanup_winsock );
    575         _winsock_init = 1;
    576     }
    577 }
    578 
    579 int socket_loopback_client(int port, int type)
    580 {
    581     FH  f = _fh_alloc( &_fh_socket_class );
    582     struct sockaddr_in addr;
    583     SOCKET  s;
    584 
    585     if (!f)
    586         return -1;
    587 
    588     if (!_winsock_init)
    589         _init_winsock();
    590 
    591     memset(&addr, 0, sizeof(addr));
    592     addr.sin_family = AF_INET;
    593     addr.sin_port = htons(port);
    594     addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    595 
    596     s = socket(AF_INET, type, 0);
    597     if(s == INVALID_SOCKET) {
    598         D("socket_loopback_client: could not create socket\n" );
    599         _fh_close(f);
    600         return -1;
    601     }
    602 
    603     f->fh_socket = s;
    604     if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
    605         D("socket_loopback_client: could not connect to %s:%d\n", type != SOCK_STREAM ? "udp" : "tcp", port );
    606         _fh_close(f);
    607         return -1;
    608     }
    609     snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
    610     D( "socket_loopback_client: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
    611     return _fh_to_int(f);
    612 }
    613 
    614 #define LISTEN_BACKLOG 4
    615 
    616 int socket_loopback_server(int port, int type)
    617 {
    618     FH   f = _fh_alloc( &_fh_socket_class );
    619     struct sockaddr_in addr;
    620     SOCKET  s;
    621     int  n;
    622 
    623     if (!f) {
    624         return -1;
    625     }
    626 
    627     if (!_winsock_init)
    628         _init_winsock();
    629 
    630     memset(&addr, 0, sizeof(addr));
    631     addr.sin_family = AF_INET;
    632     addr.sin_port = htons(port);
    633     addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    634 
    635     s = socket(AF_INET, type, 0);
    636     if(s == INVALID_SOCKET) return -1;
    637 
    638     f->fh_socket = s;
    639 
    640     n = 1;
    641     setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n));
    642 
    643     if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
    644         _fh_close(f);
    645         return -1;
    646     }
    647     if (type == SOCK_STREAM) {
    648         int ret;
    649 
    650         ret = listen(s, LISTEN_BACKLOG);
    651         if (ret < 0) {
    652             _fh_close(f);
    653             return -1;
    654         }
    655     }
    656     snprintf( f->name, sizeof(f->name), "%d(lo-server:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
    657     D( "socket_loopback_server: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
    658     return _fh_to_int(f);
    659 }
    660 
    661 
    662 int socket_network_client(const char *host, int port, int type)
    663 {
    664     FH  f = _fh_alloc( &_fh_socket_class );
    665     struct hostent *hp;
    666     struct sockaddr_in addr;
    667     SOCKET s;
    668 
    669     if (!f)
    670         return -1;
    671 
    672     if (!_winsock_init)
    673         _init_winsock();
    674 
    675     hp = gethostbyname(host);
    676     if(hp == 0) {
    677         _fh_close(f);
    678         return -1;
    679     }
    680 
    681     memset(&addr, 0, sizeof(addr));
    682     addr.sin_family = hp->h_addrtype;
    683     addr.sin_port = htons(port);
    684     memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
    685 
    686     s = socket(hp->h_addrtype, type, 0);
    687     if(s == INVALID_SOCKET) {
    688         _fh_close(f);
    689         return -1;
    690     }
    691     f->fh_socket = s;
    692 
    693     if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
    694         _fh_close(f);
    695         return -1;
    696     }
    697 
    698     snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
    699     D( "socket_network_client: host '%s' port %d type %s => fd %d\n", host, port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
    700     return _fh_to_int(f);
    701 }
    702 
    703 
    704 int socket_network_client_timeout(const char *host, int port, int type, int timeout)
    705 {
    706     // TODO: implement timeouts for Windows.
    707     return socket_network_client(host, port, type);
    708 }
    709 
    710 
    711 int socket_inaddr_any_server(int port, int type)
    712 {
    713     FH  f = _fh_alloc( &_fh_socket_class );
    714     struct sockaddr_in addr;
    715     SOCKET  s;
    716     int n;
    717 
    718     if (!f)
    719         return -1;
    720 
    721     if (!_winsock_init)
    722         _init_winsock();
    723 
    724     memset(&addr, 0, sizeof(addr));
    725     addr.sin_family = AF_INET;
    726     addr.sin_port = htons(port);
    727     addr.sin_addr.s_addr = htonl(INADDR_ANY);
    728 
    729     s = socket(AF_INET, type, 0);
    730     if(s == INVALID_SOCKET) {
    731         _fh_close(f);
    732         return -1;
    733     }
    734 
    735     f->fh_socket = s;
    736     n = 1;
    737     setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n));
    738 
    739     if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
    740         _fh_close(f);
    741         return -1;
    742     }
    743 
    744     if (type == SOCK_STREAM) {
    745         int ret;
    746 
    747         ret = listen(s, LISTEN_BACKLOG);
    748         if (ret < 0) {
    749             _fh_close(f);
    750             return -1;
    751         }
    752     }
    753     snprintf( f->name, sizeof(f->name), "%d(any-server:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
    754     D( "socket_inaddr_server: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
    755     return _fh_to_int(f);
    756 }
    757 
    758 #undef accept
    759 int  adb_socket_accept(int  serverfd, struct sockaddr*  addr, socklen_t  *addrlen)
    760 {
    761     FH   serverfh = _fh_from_int(serverfd);
    762     FH   fh;
    763 
    764     if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
    765         D( "adb_socket_accept: invalid fd %d\n", serverfd );
    766         return -1;
    767     }
    768 
    769     fh = _fh_alloc( &_fh_socket_class );
    770     if (!fh) {
    771         D( "adb_socket_accept: not enough memory to allocate accepted socket descriptor\n" );
    772         return -1;
    773     }
    774 
    775     fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
    776     if (fh->fh_socket == INVALID_SOCKET) {
    777         _fh_close( fh );
    778         D( "adb_socket_accept: accept on fd %d return error %ld\n", serverfd, GetLastError() );
    779         return -1;
    780     }
    781 
    782     snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", _fh_to_int(fh), serverfh->name );
    783     D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, _fh_to_int(fh) );
    784     return  _fh_to_int(fh);
    785 }
    786 
    787 
    788 void  disable_tcp_nagle(int fd)
    789 {
    790     FH   fh = _fh_from_int(fd);
    791     int  on = 1;
    792 
    793     if ( !fh || fh->clazz != &_fh_socket_class )
    794         return;
    795 
    796     setsockopt( fh->fh_socket, IPPROTO_TCP, TCP_NODELAY, (const char*)&on, sizeof(on) );
    797 }
    798 
    799 /**************************************************************************/
    800 /**************************************************************************/
    801 /*****                                                                *****/
    802 /*****    emulated socketpairs                                       *****/
    803 /*****                                                                *****/
    804 /**************************************************************************/
    805 /**************************************************************************/
    806 
    807 /* we implement socketpairs directly in use space for the following reasons:
    808  *   - it avoids copying data from/to the Nt kernel
    809  *   - it allows us to implement fdevent hooks easily and cheaply, something
    810  *     that is not possible with standard Win32 pipes !!
    811  *
    812  * basically, we use two circular buffers, each one corresponding to a given
    813  * direction.
    814  *
    815  * each buffer is implemented as two regions:
    816  *
    817  *   region A which is (a_start,a_end)
    818  *   region B which is (0, b_end)  with b_end <= a_start
    819  *
    820  * an empty buffer has:  a_start = a_end = b_end = 0
    821  *
    822  * a_start is the pointer where we start reading data
    823  * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
    824  * then you start writing at b_end
    825  *
    826  * the buffer is full when  b_end == a_start && a_end == BUFFER_SIZE
    827  *
    828  * there is room when b_end < a_start || a_end < BUFER_SIZE
    829  *
    830  * when reading, a_start is incremented, it a_start meets a_end, then
    831  * we do:  a_start = 0, a_end = b_end, b_end = 0, and keep going on..
    832  */
    833 
    834 #define  BIP_BUFFER_SIZE   4096
    835 
    836 #if 0
    837 #include <stdio.h>
    838 #  define  BIPD(x)      D x
    839 #  define  BIPDUMP   bip_dump_hex
    840 
    841 static void  bip_dump_hex( const unsigned char*  ptr, size_t  len )
    842 {
    843     int  nn, len2 = len;
    844 
    845     if (len2 > 8) len2 = 8;
    846 
    847     for (nn = 0; nn < len2; nn++)
    848         printf("%02x", ptr[nn]);
    849     printf("  ");
    850 
    851     for (nn = 0; nn < len2; nn++) {
    852         int  c = ptr[nn];
    853         if (c < 32 || c > 127)
    854             c = '.';
    855         printf("%c", c);
    856     }
    857     printf("\n");
    858     fflush(stdout);
    859 }
    860 
    861 #else
    862 #  define  BIPD(x)        do {} while (0)
    863 #  define  BIPDUMP(p,l)   BIPD(p)
    864 #endif
    865 
    866 typedef struct BipBufferRec_
    867 {
    868     int                a_start;
    869     int                a_end;
    870     int                b_end;
    871     int                fdin;
    872     int                fdout;
    873     int                closed;
    874     int                can_write;  /* boolean */
    875     HANDLE             evt_write;  /* event signaled when one can write to a buffer  */
    876     int                can_read;   /* boolean */
    877     HANDLE             evt_read;   /* event signaled when one can read from a buffer */
    878     CRITICAL_SECTION  lock;
    879     unsigned char      buff[ BIP_BUFFER_SIZE ];
    880 
    881 } BipBufferRec, *BipBuffer;
    882 
    883 static void
    884 bip_buffer_init( BipBuffer  buffer )
    885 {
    886     D( "bit_buffer_init %p\n", buffer );
    887     buffer->a_start   = 0;
    888     buffer->a_end     = 0;
    889     buffer->b_end     = 0;
    890     buffer->can_write = 1;
    891     buffer->can_read  = 0;
    892     buffer->fdin      = 0;
    893     buffer->fdout     = 0;
    894     buffer->closed    = 0;
    895     buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
    896     buffer->evt_read  = CreateEvent( NULL, TRUE, FALSE, NULL );
    897     InitializeCriticalSection( &buffer->lock );
    898 }
    899 
    900 static void
    901 bip_buffer_close( BipBuffer  bip )
    902 {
    903     bip->closed = 1;
    904 
    905     if (!bip->can_read) {
    906         SetEvent( bip->evt_read );
    907     }
    908     if (!bip->can_write) {
    909         SetEvent( bip->evt_write );
    910     }
    911 }
    912 
    913 static void
    914 bip_buffer_done( BipBuffer  bip )
    915 {
    916     BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
    917     CloseHandle( bip->evt_read );
    918     CloseHandle( bip->evt_write );
    919     DeleteCriticalSection( &bip->lock );
    920 }
    921 
    922 static int
    923 bip_buffer_write( BipBuffer  bip, const void* src, int  len )
    924 {
    925     int  avail, count = 0;
    926 
    927     if (len <= 0)
    928         return 0;
    929 
    930     BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
    931     BIPDUMP( src, len );
    932 
    933     EnterCriticalSection( &bip->lock );
    934 
    935     while (!bip->can_write) {
    936         int  ret;
    937         LeaveCriticalSection( &bip->lock );
    938 
    939         if (bip->closed) {
    940             errno = EPIPE;
    941             return -1;
    942         }
    943         /* spinlocking here is probably unfair, but let's live with it */
    944         ret = WaitForSingleObject( bip->evt_write, INFINITE );
    945         if (ret != WAIT_OBJECT_0) {  /* buffer probably closed */
    946             D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
    947             return 0;
    948         }
    949         if (bip->closed) {
    950             errno = EPIPE;
    951             return -1;
    952         }
    953         EnterCriticalSection( &bip->lock );
    954     }
    955 
    956     BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
    957 
    958     avail = BIP_BUFFER_SIZE - bip->a_end;
    959     if (avail > 0)
    960     {
    961         /* we can append to region A */
    962         if (avail > len)
    963             avail = len;
    964 
    965         memcpy( bip->buff + bip->a_end, src, avail );
    966         src   = (const char *)src + avail;
    967         count += avail;
    968         len   -= avail;
    969 
    970         bip->a_end += avail;
    971         if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
    972             bip->can_write = 0;
    973             ResetEvent( bip->evt_write );
    974             goto Exit;
    975         }
    976     }
    977 
    978     if (len == 0)
    979         goto Exit;
    980 
    981     avail = bip->a_start - bip->b_end;
    982     assert( avail > 0 );  /* since can_write is TRUE */
    983 
    984     if (avail > len)
    985         avail = len;
    986 
    987     memcpy( bip->buff + bip->b_end, src, avail );
    988     count += avail;
    989     bip->b_end += avail;
    990 
    991     if (bip->b_end == bip->a_start) {
    992         bip->can_write = 0;
    993         ResetEvent( bip->evt_write );
    994     }
    995 
    996 Exit:
    997     assert( count > 0 );
    998 
    999     if ( !bip->can_read ) {
   1000         bip->can_read = 1;
   1001         SetEvent( bip->evt_read );
   1002     }
   1003 
   1004     BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
   1005             bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
   1006     LeaveCriticalSection( &bip->lock );
   1007 
   1008     return count;
   1009  }
   1010 
   1011 static int
   1012 bip_buffer_read( BipBuffer  bip, void*  dst, int  len )
   1013 {
   1014     int  avail, count = 0;
   1015 
   1016     if (len <= 0)
   1017         return 0;
   1018 
   1019     BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
   1020 
   1021     EnterCriticalSection( &bip->lock );
   1022     while ( !bip->can_read )
   1023     {
   1024 #if 0
   1025         LeaveCriticalSection( &bip->lock );
   1026         errno = EAGAIN;
   1027         return -1;
   1028 #else
   1029         int  ret;
   1030         LeaveCriticalSection( &bip->lock );
   1031 
   1032         if (bip->closed) {
   1033             errno = EPIPE;
   1034             return -1;
   1035         }
   1036 
   1037         ret = WaitForSingleObject( bip->evt_read, INFINITE );
   1038         if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
   1039             D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
   1040             return 0;
   1041         }
   1042         if (bip->closed) {
   1043             errno = EPIPE;
   1044             return -1;
   1045         }
   1046         EnterCriticalSection( &bip->lock );
   1047 #endif
   1048     }
   1049 
   1050     BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
   1051 
   1052     avail = bip->a_end - bip->a_start;
   1053     assert( avail > 0 );  /* since can_read is TRUE */
   1054 
   1055     if (avail > len)
   1056         avail = len;
   1057 
   1058     memcpy( dst, bip->buff + bip->a_start, avail );
   1059     dst   = (char *)dst + avail;
   1060     count += avail;
   1061     len   -= avail;
   1062 
   1063     bip->a_start += avail;
   1064     if (bip->a_start < bip->a_end)
   1065         goto Exit;
   1066 
   1067     bip->a_start = 0;
   1068     bip->a_end   = bip->b_end;
   1069     bip->b_end   = 0;
   1070 
   1071     avail = bip->a_end;
   1072     if (avail > 0) {
   1073         if (avail > len)
   1074             avail = len;
   1075         memcpy( dst, bip->buff, avail );
   1076         count += avail;
   1077         bip->a_start += avail;
   1078 
   1079         if ( bip->a_start < bip->a_end )
   1080             goto Exit;
   1081 
   1082         bip->a_start = bip->a_end = 0;
   1083     }
   1084 
   1085     bip->can_read = 0;
   1086     ResetEvent( bip->evt_read );
   1087 
   1088 Exit:
   1089     assert( count > 0 );
   1090 
   1091     if (!bip->can_write ) {
   1092         bip->can_write = 1;
   1093         SetEvent( bip->evt_write );
   1094     }
   1095 
   1096     BIPDUMP( (const unsigned char*)dst - count, count );
   1097     BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
   1098             bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
   1099     LeaveCriticalSection( &bip->lock );
   1100 
   1101     return count;
   1102 }
   1103 
   1104 typedef struct SocketPairRec_
   1105 {
   1106     BipBufferRec  a2b_bip;
   1107     BipBufferRec  b2a_bip;
   1108     FH            a_fd;
   1109     int           used;
   1110 
   1111 } SocketPairRec;
   1112 
   1113 void _fh_socketpair_init( FH  f )
   1114 {
   1115     f->fh_pair = NULL;
   1116 }
   1117 
   1118 static int
   1119 _fh_socketpair_close( FH  f )
   1120 {
   1121     if ( f->fh_pair ) {
   1122         SocketPair  pair = f->fh_pair;
   1123 
   1124         if ( f == pair->a_fd ) {
   1125             pair->a_fd = NULL;
   1126         }
   1127 
   1128         bip_buffer_close( &pair->b2a_bip );
   1129         bip_buffer_close( &pair->a2b_bip );
   1130 
   1131         if ( --pair->used == 0 ) {
   1132             bip_buffer_done( &pair->b2a_bip );
   1133             bip_buffer_done( &pair->a2b_bip );
   1134             free( pair );
   1135         }
   1136         f->fh_pair = NULL;
   1137     }
   1138     return 0;
   1139 }
   1140 
   1141 static int
   1142 _fh_socketpair_lseek( FH  f, int pos, int  origin )
   1143 {
   1144     errno = ESPIPE;
   1145     return -1;
   1146 }
   1147 
   1148 static int
   1149 _fh_socketpair_read( FH  f, void* buf, int  len )
   1150 {
   1151     SocketPair  pair = f->fh_pair;
   1152     BipBuffer   bip;
   1153 
   1154     if (!pair)
   1155         return -1;
   1156 
   1157     if ( f == pair->a_fd )
   1158         bip = &pair->b2a_bip;
   1159     else
   1160         bip = &pair->a2b_bip;
   1161 
   1162     return bip_buffer_read( bip, buf, len );
   1163 }
   1164 
   1165 static int
   1166 _fh_socketpair_write( FH  f, const void*  buf, int  len )
   1167 {
   1168     SocketPair  pair = f->fh_pair;
   1169     BipBuffer   bip;
   1170 
   1171     if (!pair)
   1172         return -1;
   1173 
   1174     if ( f == pair->a_fd )
   1175         bip = &pair->a2b_bip;
   1176     else
   1177         bip = &pair->b2a_bip;
   1178 
   1179     return bip_buffer_write( bip, buf, len );
   1180 }
   1181 
   1182 
   1183 static void  _fh_socketpair_hook( FH  f, int  event, EventHook  hook );  /* forward */
   1184 
   1185 static const FHClassRec  _fh_socketpair_class =
   1186 {
   1187     _fh_socketpair_init,
   1188     _fh_socketpair_close,
   1189     _fh_socketpair_lseek,
   1190     _fh_socketpair_read,
   1191     _fh_socketpair_write,
   1192     _fh_socketpair_hook
   1193 };
   1194 
   1195 
   1196 int  adb_socketpair( int  sv[2] )
   1197 {
   1198     FH          fa, fb;
   1199     SocketPair  pair;
   1200 
   1201     fa = _fh_alloc( &_fh_socketpair_class );
   1202     fb = _fh_alloc( &_fh_socketpair_class );
   1203 
   1204     if (!fa || !fb)
   1205         goto Fail;
   1206 
   1207     pair = malloc( sizeof(*pair) );
   1208     if (pair == NULL) {
   1209         D("adb_socketpair: not enough memory to allocate pipes\n" );
   1210         goto Fail;
   1211     }
   1212 
   1213     bip_buffer_init( &pair->a2b_bip );
   1214     bip_buffer_init( &pair->b2a_bip );
   1215 
   1216     fa->fh_pair = pair;
   1217     fb->fh_pair = pair;
   1218     pair->used  = 2;
   1219     pair->a_fd  = fa;
   1220 
   1221     sv[0] = _fh_to_int(fa);
   1222     sv[1] = _fh_to_int(fb);
   1223 
   1224     pair->a2b_bip.fdin  = sv[0];
   1225     pair->a2b_bip.fdout = sv[1];
   1226     pair->b2a_bip.fdin  = sv[1];
   1227     pair->b2a_bip.fdout = sv[0];
   1228 
   1229     snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
   1230     snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
   1231     D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
   1232     return 0;
   1233 
   1234 Fail:
   1235     _fh_close(fb);
   1236     _fh_close(fa);
   1237     return -1;
   1238 }
   1239 
   1240 /**************************************************************************/
   1241 /**************************************************************************/
   1242 /*****                                                                *****/
   1243 /*****    fdevents emulation                                          *****/
   1244 /*****                                                                *****/
   1245 /*****   this is a very simple implementation, we rely on the fact    *****/
   1246 /*****   that ADB doesn't use FDE_ERROR.                              *****/
   1247 /*****                                                                *****/
   1248 /**************************************************************************/
   1249 /**************************************************************************/
   1250 
   1251 #define FATAL(x...) fatal(__FUNCTION__, x)
   1252 
   1253 #if DEBUG
   1254 static void dump_fde(fdevent *fde, const char *info)
   1255 {
   1256     fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
   1257             fde->state & FDE_READ ? 'R' : ' ',
   1258             fde->state & FDE_WRITE ? 'W' : ' ',
   1259             fde->state & FDE_ERROR ? 'E' : ' ',
   1260             info);
   1261 }
   1262 #else
   1263 #define dump_fde(fde, info) do { } while(0)
   1264 #endif
   1265 
   1266 #define FDE_EVENTMASK  0x00ff
   1267 #define FDE_STATEMASK  0xff00
   1268 
   1269 #define FDE_ACTIVE     0x0100
   1270 #define FDE_PENDING    0x0200
   1271 #define FDE_CREATED    0x0400
   1272 
   1273 static void fdevent_plist_enqueue(fdevent *node);
   1274 static void fdevent_plist_remove(fdevent *node);
   1275 static fdevent *fdevent_plist_dequeue(void);
   1276 
   1277 static fdevent list_pending = {
   1278     .next = &list_pending,
   1279     .prev = &list_pending,
   1280 };
   1281 
   1282 static fdevent **fd_table = 0;
   1283 static int       fd_table_max = 0;
   1284 
   1285 typedef struct EventLooperRec_*  EventLooper;
   1286 
   1287 typedef struct EventHookRec_
   1288 {
   1289     EventHook    next;
   1290     FH           fh;
   1291     HANDLE       h;
   1292     int          wanted;   /* wanted event flags */
   1293     int          ready;    /* ready event flags  */
   1294     void*        aux;
   1295     void        (*prepare)( EventHook  hook );
   1296     int         (*start)  ( EventHook  hook );
   1297     void        (*stop)   ( EventHook  hook );
   1298     int         (*check)  ( EventHook  hook );
   1299     int         (*peek)   ( EventHook  hook );
   1300 } EventHookRec;
   1301 
   1302 static EventHook  _free_hooks;
   1303 
   1304 static EventHook
   1305 event_hook_alloc( FH  fh )
   1306 {
   1307     EventHook  hook = _free_hooks;
   1308     if (hook != NULL)
   1309         _free_hooks = hook->next;
   1310     else {
   1311         hook = malloc( sizeof(*hook) );
   1312         if (hook == NULL)
   1313             fatal( "could not allocate event hook\n" );
   1314     }
   1315     hook->next   = NULL;
   1316     hook->fh     = fh;
   1317     hook->wanted = 0;
   1318     hook->ready  = 0;
   1319     hook->h      = INVALID_HANDLE_VALUE;
   1320     hook->aux    = NULL;
   1321 
   1322     hook->prepare = NULL;
   1323     hook->start   = NULL;
   1324     hook->stop    = NULL;
   1325     hook->check   = NULL;
   1326     hook->peek    = NULL;
   1327 
   1328     return hook;
   1329 }
   1330 
   1331 static void
   1332 event_hook_free( EventHook  hook )
   1333 {
   1334     hook->fh     = NULL;
   1335     hook->wanted = 0;
   1336     hook->ready  = 0;
   1337     hook->next   = _free_hooks;
   1338     _free_hooks  = hook;
   1339 }
   1340 
   1341 
   1342 static void
   1343 event_hook_signal( EventHook  hook )
   1344 {
   1345     FH        f   = hook->fh;
   1346     int       fd  = _fh_to_int(f);
   1347     fdevent*  fde = fd_table[ fd - WIN32_FH_BASE ];
   1348 
   1349     if (fde != NULL && fde->fd == fd) {
   1350         if ((fde->state & FDE_PENDING) == 0) {
   1351             fde->state |= FDE_PENDING;
   1352             fdevent_plist_enqueue( fde );
   1353         }
   1354         fde->events |= hook->wanted;
   1355     }
   1356 }
   1357 
   1358 
   1359 #define  MAX_LOOPER_HANDLES  WIN32_MAX_FHS
   1360 
   1361 typedef struct EventLooperRec_
   1362 {
   1363     EventHook    hooks;
   1364     HANDLE       htab[ MAX_LOOPER_HANDLES ];
   1365     int          htab_count;
   1366 
   1367 } EventLooperRec;
   1368 
   1369 static EventHook*
   1370 event_looper_find_p( EventLooper  looper, FH  fh )
   1371 {
   1372     EventHook  *pnode = &looper->hooks;
   1373     EventHook   node  = *pnode;
   1374     for (;;) {
   1375         if ( node == NULL || node->fh == fh )
   1376             break;
   1377         pnode = &node->next;
   1378         node  = *pnode;
   1379     }
   1380     return  pnode;
   1381 }
   1382 
   1383 static void
   1384 event_looper_hook( EventLooper  looper, int  fd, int  events )
   1385 {
   1386     FH          f = _fh_from_int(fd);
   1387     EventHook  *pnode;
   1388     EventHook   node;
   1389 
   1390     if (f == NULL)  /* invalid arg */ {
   1391         D("event_looper_hook: invalid fd=%d\n", fd);
   1392         return;
   1393     }
   1394 
   1395     pnode = event_looper_find_p( looper, f );
   1396     node  = *pnode;
   1397     if ( node == NULL ) {
   1398         node       = event_hook_alloc( f );
   1399         node->next = *pnode;
   1400         *pnode     = node;
   1401     }
   1402 
   1403     if ( (node->wanted & events) != events ) {
   1404         /* this should update start/stop/check/peek */
   1405         D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
   1406            fd, node->wanted, events);
   1407         f->clazz->_fh_hook( f, events & ~node->wanted, node );
   1408         node->wanted |= events;
   1409     } else {
   1410         D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
   1411            events, fd, node->wanted);
   1412     }
   1413 }
   1414 
   1415 static void
   1416 event_looper_unhook( EventLooper  looper, int  fd, int  events )
   1417 {
   1418     FH          fh    = _fh_from_int(fd);
   1419     EventHook  *pnode = event_looper_find_p( looper, fh );
   1420     EventHook   node  = *pnode;
   1421 
   1422     if (node != NULL) {
   1423         int  events2 = events & node->wanted;
   1424         if ( events2 == 0 ) {
   1425             D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
   1426             return;
   1427         }
   1428         node->wanted &= ~events2;
   1429         if (!node->wanted) {
   1430             *pnode = node->next;
   1431             event_hook_free( node );
   1432         }
   1433     }
   1434 }
   1435 
   1436 /*
   1437  * A fixer for WaitForMultipleObjects on condition that there are more than 64
   1438  * handles to wait on.
   1439  *
   1440  * In cetain cases DDMS may establish more than 64 connections with ADB. For
   1441  * instance, this may happen if there are more than 64 processes running on a
   1442  * device, or there are multiple devices connected (including the emulator) with
   1443  * the combined number of running processes greater than 64. In this case using
   1444  * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
   1445  * because of the API limitations (64 handles max). So, we need to provide a way
   1446  * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
   1447  * easiest (and "Microsoft recommended") way to do that would be dividing the
   1448  * handle array into chunks with the chunk size less than 64, and fire up as many
   1449  * waiting threads as there are chunks. Then each thread would wait on a chunk of
   1450  * handles, and will report back to the caller which handle has been set.
   1451  * Here is the implementation of that algorithm.
   1452  */
   1453 
   1454 /* Number of handles to wait on in each wating thread. */
   1455 #define WAIT_ALL_CHUNK_SIZE 63
   1456 
   1457 /* Descriptor for a wating thread */
   1458 typedef struct WaitForAllParam {
   1459     /* A handle to an event to signal when waiting is over. This handle is shared
   1460      * accross all the waiting threads, so each waiting thread knows when any
   1461      * other thread has exited, so it can exit too. */
   1462     HANDLE          main_event;
   1463     /* Upon exit from a waiting thread contains the index of the handle that has
   1464      * been signaled. The index is an absolute index of the signaled handle in
   1465      * the original array. This pointer is shared accross all the waiting threads
   1466      * and it's not guaranteed (due to a race condition) that when all the
   1467      * waiting threads exit, the value contained here would indicate the first
   1468      * handle that was signaled. This is fine, because the caller cares only
   1469      * about any handle being signaled. It doesn't care about the order, nor
   1470      * about the whole list of handles that were signaled. */
   1471     LONG volatile   *signaled_index;
   1472     /* Array of handles to wait on in a waiting thread. */
   1473     HANDLE*         handles;
   1474     /* Number of handles in 'handles' array to wait on. */
   1475     int             handles_count;
   1476     /* Index inside the main array of the first handle in the 'handles' array. */
   1477     int             first_handle_index;
   1478     /* Waiting thread handle. */
   1479     HANDLE          thread;
   1480 } WaitForAllParam;
   1481 
   1482 /* Waiting thread routine. */
   1483 static unsigned __stdcall
   1484 _in_waiter_thread(void*  arg)
   1485 {
   1486     HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
   1487     int res;
   1488     WaitForAllParam* const param = (WaitForAllParam*)arg;
   1489 
   1490     /* We have to wait on the main_event in order to be notified when any of the
   1491      * sibling threads is exiting. */
   1492     wait_on[0] = param->main_event;
   1493     /* The rest of the handles go behind the main event handle. */
   1494     memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
   1495 
   1496     res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
   1497     if (res > 0 && res < (param->handles_count + 1)) {
   1498         /* One of the original handles got signaled. Save its absolute index into
   1499          * the output variable. */
   1500         InterlockedCompareExchange(param->signaled_index,
   1501                                    res - 1L + param->first_handle_index, -1L);
   1502     }
   1503 
   1504     /* Notify the caller (and the siblings) that the wait is over. */
   1505     SetEvent(param->main_event);
   1506 
   1507     _endthreadex(0);
   1508     return 0;
   1509 }
   1510 
   1511 /* WaitForMultipeObjects fixer routine.
   1512  * Param:
   1513  *  handles Array of handles to wait on.
   1514  *  handles_count Number of handles in the array.
   1515  * Return:
   1516  *  (>= 0 && < handles_count) - Index of the signaled handle in the array, or
   1517  *  WAIT_FAILED on an error.
   1518  */
   1519 static int
   1520 _wait_for_all(HANDLE* handles, int handles_count)
   1521 {
   1522     WaitForAllParam* threads;
   1523     HANDLE main_event;
   1524     int chunks, chunk, remains;
   1525 
   1526     /* This variable is going to be accessed by several threads at the same time,
   1527      * this is bound to fail randomly when the core is run on multi-core machines.
   1528      * To solve this, we need to do the following (1 _and_ 2):
   1529      * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
   1530      *    out the reads/writes in this function unexpectedly.
   1531      * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
   1532      *    all accesses inside a critical section. But we can also use
   1533      *    InterlockedCompareExchange() which always provide a full memory barrier
   1534      *    on Win32.
   1535      */
   1536     volatile LONG sig_index = -1;
   1537 
   1538     /* Calculate number of chunks, and allocate thread param array. */
   1539     chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
   1540     remains = handles_count % WAIT_ALL_CHUNK_SIZE;
   1541     threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
   1542                                         sizeof(WaitForAllParam));
   1543     if (threads == NULL) {
   1544         D("Unable to allocate thread array for %d handles.", handles_count);
   1545         return (int)WAIT_FAILED;
   1546     }
   1547 
   1548     /* Create main event to wait on for all waiting threads. This is a "manualy
   1549      * reset" event that will remain set once it was set. */
   1550     main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
   1551     if (main_event == NULL) {
   1552         D("Unable to create main event. Error: %d", (int)GetLastError());
   1553         free(threads);
   1554         return (int)WAIT_FAILED;
   1555     }
   1556 
   1557     /*
   1558      * Initialize waiting thread parameters.
   1559      */
   1560 
   1561     for (chunk = 0; chunk < chunks; chunk++) {
   1562         threads[chunk].main_event = main_event;
   1563         threads[chunk].signaled_index = &sig_index;
   1564         threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
   1565         threads[chunk].handles = handles + threads[chunk].first_handle_index;
   1566         threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
   1567     }
   1568     if (remains) {
   1569         threads[chunk].main_event = main_event;
   1570         threads[chunk].signaled_index = &sig_index;
   1571         threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
   1572         threads[chunk].handles = handles + threads[chunk].first_handle_index;
   1573         threads[chunk].handles_count = remains;
   1574         chunks++;
   1575     }
   1576 
   1577     /* Start the waiting threads. */
   1578     for (chunk = 0; chunk < chunks; chunk++) {
   1579         /* Note that using adb_thread_create is not appropriate here, since we
   1580          * need a handle to wait on for thread termination. */
   1581         threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
   1582                                                        &threads[chunk], 0, NULL);
   1583         if (threads[chunk].thread == NULL) {
   1584             /* Unable to create a waiter thread. Collapse. */
   1585             D("Unable to create a waiting thread %d of %d. errno=%d",
   1586               chunk, chunks, errno);
   1587             chunks = chunk;
   1588             SetEvent(main_event);
   1589             break;
   1590         }
   1591     }
   1592 
   1593     /* Wait on any of the threads to get signaled. */
   1594     WaitForSingleObject(main_event, INFINITE);
   1595 
   1596     /* Wait on all the waiting threads to exit. */
   1597     for (chunk = 0; chunk < chunks; chunk++) {
   1598         WaitForSingleObject(threads[chunk].thread, INFINITE);
   1599         CloseHandle(threads[chunk].thread);
   1600     }
   1601 
   1602     CloseHandle(main_event);
   1603     free(threads);
   1604 
   1605 
   1606     const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
   1607     return (ret >= 0) ? ret : (int)WAIT_FAILED;
   1608 }
   1609 
   1610 static EventLooperRec  win32_looper;
   1611 
   1612 static void fdevent_init(void)
   1613 {
   1614     win32_looper.htab_count = 0;
   1615     win32_looper.hooks      = NULL;
   1616 }
   1617 
   1618 static void fdevent_connect(fdevent *fde)
   1619 {
   1620     EventLooper  looper = &win32_looper;
   1621     int          events = fde->state & FDE_EVENTMASK;
   1622 
   1623     if (events != 0)
   1624         event_looper_hook( looper, fde->fd, events );
   1625 }
   1626 
   1627 static void fdevent_disconnect(fdevent *fde)
   1628 {
   1629     EventLooper  looper = &win32_looper;
   1630     int          events = fde->state & FDE_EVENTMASK;
   1631 
   1632     if (events != 0)
   1633         event_looper_unhook( looper, fde->fd, events );
   1634 }
   1635 
   1636 static void fdevent_update(fdevent *fde, unsigned events)
   1637 {
   1638     EventLooper  looper  = &win32_looper;
   1639     unsigned     events0 = fde->state & FDE_EVENTMASK;
   1640 
   1641     if (events != events0) {
   1642         int  removes = events0 & ~events;
   1643         int  adds    = events  & ~events0;
   1644         if (removes) {
   1645             D("fdevent_update: remove %x from %d\n", removes, fde->fd);
   1646             event_looper_unhook( looper, fde->fd, removes );
   1647         }
   1648         if (adds) {
   1649             D("fdevent_update: add %x to %d\n", adds, fde->fd);
   1650             event_looper_hook  ( looper, fde->fd, adds );
   1651         }
   1652     }
   1653 }
   1654 
   1655 static void fdevent_process()
   1656 {
   1657     EventLooper  looper = &win32_looper;
   1658     EventHook    hook;
   1659     int          gotone = 0;
   1660 
   1661     /* if we have at least one ready hook, execute it/them */
   1662     for (hook = looper->hooks; hook; hook = hook->next) {
   1663         hook->ready = 0;
   1664         if (hook->prepare) {
   1665             hook->prepare(hook);
   1666             if (hook->ready != 0) {
   1667                 event_hook_signal( hook );
   1668                 gotone = 1;
   1669             }
   1670         }
   1671     }
   1672 
   1673     /* nothing's ready yet, so wait for something to happen */
   1674     if (!gotone)
   1675     {
   1676         looper->htab_count = 0;
   1677 
   1678         for (hook = looper->hooks; hook; hook = hook->next)
   1679         {
   1680             if (hook->start && !hook->start(hook)) {
   1681                 D( "fdevent_process: error when starting a hook\n" );
   1682                 return;
   1683             }
   1684             if (hook->h != INVALID_HANDLE_VALUE) {
   1685                 int  nn;
   1686 
   1687                 for (nn = 0; nn < looper->htab_count; nn++)
   1688                 {
   1689                     if ( looper->htab[nn] == hook->h )
   1690                         goto DontAdd;
   1691                 }
   1692                 looper->htab[ looper->htab_count++ ] = hook->h;
   1693             DontAdd:
   1694                 ;
   1695             }
   1696         }
   1697 
   1698         if (looper->htab_count == 0) {
   1699             D( "fdevent_process: nothing to wait for !!\n" );
   1700             return;
   1701         }
   1702 
   1703         do
   1704         {
   1705             int   wait_ret;
   1706 
   1707             D( "adb_win32: waiting for %d events\n", looper->htab_count );
   1708             if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
   1709                 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
   1710                 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
   1711             } else {
   1712                 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
   1713             }
   1714             if (wait_ret == (int)WAIT_FAILED) {
   1715                 D( "adb_win32: wait failed, error %ld\n", GetLastError() );
   1716             } else {
   1717                 D( "adb_win32: got one (index %d)\n", wait_ret );
   1718 
   1719                 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
   1720                  * like mouse movements. we need to filter these with the "check" function
   1721                  */
   1722                 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
   1723                 {
   1724                     for (hook = looper->hooks; hook; hook = hook->next)
   1725                     {
   1726                         if ( looper->htab[wait_ret] == hook->h       &&
   1727                          (!hook->check || hook->check(hook)) )
   1728                         {
   1729                             D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
   1730                             event_hook_signal( hook );
   1731                             gotone = 1;
   1732                             break;
   1733                         }
   1734                     }
   1735                 }
   1736             }
   1737         }
   1738         while (!gotone);
   1739 
   1740         for (hook = looper->hooks; hook; hook = hook->next) {
   1741             if (hook->stop)
   1742                 hook->stop( hook );
   1743         }
   1744     }
   1745 
   1746     for (hook = looper->hooks; hook; hook = hook->next) {
   1747         if (hook->peek && hook->peek(hook))
   1748                 event_hook_signal( hook );
   1749     }
   1750 }
   1751 
   1752 
   1753 static void fdevent_register(fdevent *fde)
   1754 {
   1755     int  fd = fde->fd - WIN32_FH_BASE;
   1756 
   1757     if(fd < 0) {
   1758         FATAL("bogus negative fd (%d)\n", fde->fd);
   1759     }
   1760 
   1761     if(fd >= fd_table_max) {
   1762         int oldmax = fd_table_max;
   1763         if(fde->fd > 32000) {
   1764             FATAL("bogus huuuuge fd (%d)\n", fde->fd);
   1765         }
   1766         if(fd_table_max == 0) {
   1767             fdevent_init();
   1768             fd_table_max = 256;
   1769         }
   1770         while(fd_table_max <= fd) {
   1771             fd_table_max *= 2;
   1772         }
   1773         fd_table = realloc(fd_table, sizeof(fdevent*) * fd_table_max);
   1774         if(fd_table == 0) {
   1775             FATAL("could not expand fd_table to %d entries\n", fd_table_max);
   1776         }
   1777         memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
   1778     }
   1779 
   1780     fd_table[fd] = fde;
   1781 }
   1782 
   1783 static void fdevent_unregister(fdevent *fde)
   1784 {
   1785     int  fd = fde->fd - WIN32_FH_BASE;
   1786 
   1787     if((fd < 0) || (fd >= fd_table_max)) {
   1788         FATAL("fd out of range (%d)\n", fde->fd);
   1789     }
   1790 
   1791     if(fd_table[fd] != fde) {
   1792         FATAL("fd_table out of sync");
   1793     }
   1794 
   1795     fd_table[fd] = 0;
   1796 
   1797     if(!(fde->state & FDE_DONT_CLOSE)) {
   1798         dump_fde(fde, "close");
   1799         adb_close(fde->fd);
   1800     }
   1801 }
   1802 
   1803 static void fdevent_plist_enqueue(fdevent *node)
   1804 {
   1805     fdevent *list = &list_pending;
   1806 
   1807     node->next = list;
   1808     node->prev = list->prev;
   1809     node->prev->next = node;
   1810     list->prev = node;
   1811 }
   1812 
   1813 static void fdevent_plist_remove(fdevent *node)
   1814 {
   1815     node->prev->next = node->next;
   1816     node->next->prev = node->prev;
   1817     node->next = 0;
   1818     node->prev = 0;
   1819 }
   1820 
   1821 static fdevent *fdevent_plist_dequeue(void)
   1822 {
   1823     fdevent *list = &list_pending;
   1824     fdevent *node = list->next;
   1825 
   1826     if(node == list) return 0;
   1827 
   1828     list->next = node->next;
   1829     list->next->prev = list;
   1830     node->next = 0;
   1831     node->prev = 0;
   1832 
   1833     return node;
   1834 }
   1835 
   1836 fdevent *fdevent_create(int fd, fd_func func, void *arg)
   1837 {
   1838     fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
   1839     if(fde == 0) return 0;
   1840     fdevent_install(fde, fd, func, arg);
   1841     fde->state |= FDE_CREATED;
   1842     return fde;
   1843 }
   1844 
   1845 void fdevent_destroy(fdevent *fde)
   1846 {
   1847     if(fde == 0) return;
   1848     if(!(fde->state & FDE_CREATED)) {
   1849         FATAL("fde %p not created by fdevent_create()\n", fde);
   1850     }
   1851     fdevent_remove(fde);
   1852 }
   1853 
   1854 void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
   1855 {
   1856     memset(fde, 0, sizeof(fdevent));
   1857     fde->state = FDE_ACTIVE;
   1858     fde->fd = fd;
   1859     fde->func = func;
   1860     fde->arg = arg;
   1861 
   1862     fdevent_register(fde);
   1863     dump_fde(fde, "connect");
   1864     fdevent_connect(fde);
   1865     fde->state |= FDE_ACTIVE;
   1866 }
   1867 
   1868 void fdevent_remove(fdevent *fde)
   1869 {
   1870     if(fde->state & FDE_PENDING) {
   1871         fdevent_plist_remove(fde);
   1872     }
   1873 
   1874     if(fde->state & FDE_ACTIVE) {
   1875         fdevent_disconnect(fde);
   1876         dump_fde(fde, "disconnect");
   1877         fdevent_unregister(fde);
   1878     }
   1879 
   1880     fde->state = 0;
   1881     fde->events = 0;
   1882 }
   1883 
   1884 
   1885 void fdevent_set(fdevent *fde, unsigned events)
   1886 {
   1887     events &= FDE_EVENTMASK;
   1888 
   1889     if((fde->state & FDE_EVENTMASK) == (int)events) return;
   1890 
   1891     if(fde->state & FDE_ACTIVE) {
   1892         fdevent_update(fde, events);
   1893         dump_fde(fde, "update");
   1894     }
   1895 
   1896     fde->state = (fde->state & FDE_STATEMASK) | events;
   1897 
   1898     if(fde->state & FDE_PENDING) {
   1899             /* if we're pending, make sure
   1900             ** we don't signal an event that
   1901             ** is no longer wanted.
   1902             */
   1903         fde->events &= (~events);
   1904         if(fde->events == 0) {
   1905             fdevent_plist_remove(fde);
   1906             fde->state &= (~FDE_PENDING);
   1907         }
   1908     }
   1909 }
   1910 
   1911 void fdevent_add(fdevent *fde, unsigned events)
   1912 {
   1913     fdevent_set(
   1914         fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
   1915 }
   1916 
   1917 void fdevent_del(fdevent *fde, unsigned events)
   1918 {
   1919     fdevent_set(
   1920         fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
   1921 }
   1922 
   1923 void fdevent_loop()
   1924 {
   1925     fdevent *fde;
   1926 
   1927     for(;;) {
   1928 #if DEBUG
   1929         fprintf(stderr,"--- ---- waiting for events\n");
   1930 #endif
   1931         fdevent_process();
   1932 
   1933         while((fde = fdevent_plist_dequeue())) {
   1934             unsigned events = fde->events;
   1935             fde->events = 0;
   1936             fde->state &= (~FDE_PENDING);
   1937             dump_fde(fde, "callback");
   1938             fde->func(fde->fd, events, fde->arg);
   1939         }
   1940     }
   1941 }
   1942 
   1943 /**  FILE EVENT HOOKS
   1944  **/
   1945 
   1946 static void  _event_file_prepare( EventHook  hook )
   1947 {
   1948     if (hook->wanted & (FDE_READ|FDE_WRITE)) {
   1949         /* we can always read/write */
   1950         hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
   1951     }
   1952 }
   1953 
   1954 static int  _event_file_peek( EventHook  hook )
   1955 {
   1956     return (hook->wanted & (FDE_READ|FDE_WRITE));
   1957 }
   1958 
   1959 static void  _fh_file_hook( FH  f, int  events, EventHook  hook )
   1960 {
   1961     hook->h       = f->fh_handle;
   1962     hook->prepare = _event_file_prepare;
   1963     hook->peek    = _event_file_peek;
   1964 }
   1965 
   1966 /** SOCKET EVENT HOOKS
   1967  **/
   1968 
   1969 static void  _event_socket_verify( EventHook  hook, WSANETWORKEVENTS*  evts )
   1970 {
   1971     if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
   1972         if (hook->wanted & FDE_READ)
   1973             hook->ready |= FDE_READ;
   1974         if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
   1975             hook->ready |= FDE_ERROR;
   1976     }
   1977     if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
   1978         if (hook->wanted & FDE_WRITE)
   1979             hook->ready |= FDE_WRITE;
   1980         if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
   1981             hook->ready |= FDE_ERROR;
   1982     }
   1983     if ( evts->lNetworkEvents & FD_OOB ) {
   1984         if (hook->wanted & FDE_ERROR)
   1985             hook->ready |= FDE_ERROR;
   1986     }
   1987 }
   1988 
   1989 static void  _event_socket_prepare( EventHook  hook )
   1990 {
   1991     WSANETWORKEVENTS  evts;
   1992 
   1993     /* look if some of the events we want already happened ? */
   1994     if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
   1995         _event_socket_verify( hook, &evts );
   1996 }
   1997 
   1998 static int  _socket_wanted_to_flags( int  wanted )
   1999 {
   2000     int  flags = 0;
   2001     if (wanted & FDE_READ)
   2002         flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
   2003 
   2004     if (wanted & FDE_WRITE)
   2005         flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
   2006 
   2007     if (wanted & FDE_ERROR)
   2008         flags |= FD_OOB;
   2009 
   2010     return flags;
   2011 }
   2012 
   2013 static int _event_socket_start( EventHook  hook )
   2014 {
   2015     /* create an event which we're going to wait for */
   2016     FH    fh    = hook->fh;
   2017     long  flags = _socket_wanted_to_flags( hook->wanted );
   2018 
   2019     hook->h = fh->event;
   2020     if (hook->h == INVALID_HANDLE_VALUE) {
   2021         D( "_event_socket_start: no event for %s\n", fh->name );
   2022         return 0;
   2023     }
   2024 
   2025     if ( flags != fh->mask ) {
   2026         D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
   2027         if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
   2028             D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
   2029             CloseHandle( hook->h );
   2030             hook->h = INVALID_HANDLE_VALUE;
   2031             exit(1);
   2032             return 0;
   2033         }
   2034         fh->mask = flags;
   2035     }
   2036     return 1;
   2037 }
   2038 
   2039 static void _event_socket_stop( EventHook  hook )
   2040 {
   2041     hook->h = INVALID_HANDLE_VALUE;
   2042 }
   2043 
   2044 static int  _event_socket_check( EventHook  hook )
   2045 {
   2046     int               result = 0;
   2047     FH                fh = hook->fh;
   2048     WSANETWORKEVENTS  evts;
   2049 
   2050     if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
   2051         _event_socket_verify( hook, &evts );
   2052         result = (hook->ready != 0);
   2053         if (result) {
   2054             ResetEvent( hook->h );
   2055         }
   2056     }
   2057     D( "_event_socket_check %s returns %d\n", fh->name, result );
   2058     return  result;
   2059 }
   2060 
   2061 static int  _event_socket_peek( EventHook  hook )
   2062 {
   2063     WSANETWORKEVENTS  evts;
   2064     FH                fh = hook->fh;
   2065 
   2066     /* look if some of the events we want already happened ? */
   2067     if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
   2068         _event_socket_verify( hook, &evts );
   2069         if (hook->ready)
   2070             ResetEvent( hook->h );
   2071     }
   2072 
   2073     return hook->ready != 0;
   2074 }
   2075 
   2076 
   2077 
   2078 static void  _fh_socket_hook( FH  f, int  events, EventHook  hook )
   2079 {
   2080     hook->prepare = _event_socket_prepare;
   2081     hook->start   = _event_socket_start;
   2082     hook->stop    = _event_socket_stop;
   2083     hook->check   = _event_socket_check;
   2084     hook->peek    = _event_socket_peek;
   2085 
   2086     _event_socket_start( hook );
   2087 }
   2088 
   2089 /** SOCKETPAIR EVENT HOOKS
   2090  **/
   2091 
   2092 static void  _event_socketpair_prepare( EventHook  hook )
   2093 {
   2094     FH          fh   = hook->fh;
   2095     SocketPair  pair = fh->fh_pair;
   2096     BipBuffer   rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
   2097     BipBuffer   wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
   2098 
   2099     if (hook->wanted & FDE_READ && rbip->can_read)
   2100         hook->ready |= FDE_READ;
   2101 
   2102     if (hook->wanted & FDE_WRITE && wbip->can_write)
   2103         hook->ready |= FDE_WRITE;
   2104  }
   2105 
   2106  static int  _event_socketpair_start( EventHook  hook )
   2107  {
   2108     FH          fh   = hook->fh;
   2109     SocketPair  pair = fh->fh_pair;
   2110     BipBuffer   rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
   2111     BipBuffer   wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
   2112 
   2113     if (hook->wanted == FDE_READ)
   2114         hook->h = rbip->evt_read;
   2115 
   2116     else if (hook->wanted == FDE_WRITE)
   2117         hook->h = wbip->evt_write;
   2118 
   2119     else {
   2120         D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
   2121         return 0;
   2122     }
   2123     D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
   2124        hook->fh->name, _fh_to_int(fh), hook->wanted);
   2125     return 1;
   2126 }
   2127 
   2128 static int  _event_socketpair_peek( EventHook  hook )
   2129 {
   2130     _event_socketpair_prepare( hook );
   2131     return hook->ready != 0;
   2132 }
   2133 
   2134 static void  _fh_socketpair_hook( FH  fh, int  events, EventHook  hook )
   2135 {
   2136     hook->prepare = _event_socketpair_prepare;
   2137     hook->start   = _event_socketpair_start;
   2138     hook->peek    = _event_socketpair_peek;
   2139 }
   2140 
   2141 
   2142 void
   2143 adb_sysdeps_init( void )
   2144 {
   2145 #define  ADB_MUTEX(x)  InitializeCriticalSection( & x );
   2146 #include "mutex_list.h"
   2147     InitializeCriticalSection( &_win32_lock );
   2148 }
   2149 
   2150 /* Windows doesn't have strtok_r.  Use the one from bionic. */
   2151 
   2152 /*
   2153  * Copyright (c) 1988 Regents of the University of California.
   2154  * All rights reserved.
   2155  *
   2156  * Redistribution and use in source and binary forms, with or without
   2157  * modification, are permitted provided that the following conditions
   2158  * are met:
   2159  * 1. Redistributions of source code must retain the above copyright
   2160  *    notice, this list of conditions and the following disclaimer.
   2161  * 2. Redistributions in binary form must reproduce the above copyright
   2162  *    notice, this list of conditions and the following disclaimer in the
   2163  *    documentation and/or other materials provided with the distribution.
   2164  * 3. Neither the name of the University nor the names of its contributors
   2165  *    may be used to endorse or promote products derived from this software
   2166  *    without specific prior written permission.
   2167  *
   2168  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   2169  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   2170  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   2171  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   2172  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   2173  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   2174  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   2175  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   2176  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   2177  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   2178  * SUCH DAMAGE.
   2179  */
   2180 
   2181 char *
   2182 adb_strtok_r(char *s, const char *delim, char **last)
   2183 {
   2184 	char *spanp;
   2185 	int c, sc;
   2186 	char *tok;
   2187 
   2188 
   2189 	if (s == NULL && (s = *last) == NULL)
   2190 		return (NULL);
   2191 
   2192 	/*
   2193 	 * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
   2194 	 */
   2195 cont:
   2196 	c = *s++;
   2197 	for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
   2198 		if (c == sc)
   2199 			goto cont;
   2200 	}
   2201 
   2202 	if (c == 0) {		/* no non-delimiter characters */
   2203 		*last = NULL;
   2204 		return (NULL);
   2205 	}
   2206 	tok = s - 1;
   2207 
   2208 	/*
   2209 	 * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
   2210 	 * Note that delim must have one NUL; we stop if we see that, too.
   2211 	 */
   2212 	for (;;) {
   2213 		c = *s++;
   2214 		spanp = (char *)delim;
   2215 		do {
   2216 			if ((sc = *spanp++) == c) {
   2217 				if (c == 0)
   2218 					s = NULL;
   2219 				else
   2220 					s[-1] = 0;
   2221 				*last = s;
   2222 				return (tok);
   2223 			}
   2224 		} while (sc != 0);
   2225 	}
   2226 	/* NOTREACHED */
   2227 }
   2228