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