sysdeps_win32.c 59 KB

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