GoogleGit

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