GoogleGit

blob: c2742f10b6be80885f0d62ed4ad8b91b7ce317da [file] [log] [blame]
  1. /*
  2. * Copyright (C) 2015 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #define TRACE_TAG TRACE_SYSDEPS
  17. #include "sysdeps.h"
  18. #include <winsock2.h> /* winsock.h *must* be included before windows.h. */
  19. #include <windows.h>
  20. #include <errno.h>
  21. #include <stdbool.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include "adb.h"
  25. extern void fatal(const char *fmt, ...);
  26. #define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
  27. /**************************************************************************/
  28. /**************************************************************************/
  29. /***** *****/
  30. /***** replaces libs/cutils/load_file.c *****/
  31. /***** *****/
  32. /**************************************************************************/
  33. /**************************************************************************/
  34. void *load_file(const char *fn, unsigned *_sz)
  35. {
  36. HANDLE file;
  37. char *data;
  38. DWORD file_size;
  39. file = CreateFile( fn,
  40. GENERIC_READ,
  41. FILE_SHARE_READ,
  42. NULL,
  43. OPEN_EXISTING,
  44. 0,
  45. NULL );
  46. if (file == INVALID_HANDLE_VALUE)
  47. return NULL;
  48. file_size = GetFileSize( file, NULL );
  49. data = NULL;
  50. if (file_size > 0) {
  51. data = (char*) malloc( file_size + 1 );
  52. if (data == NULL) {
  53. D("load_file: could not allocate %ld bytes\n", file_size );
  54. file_size = 0;
  55. } else {
  56. DWORD out_bytes;
  57. if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
  58. out_bytes != file_size )
  59. {
  60. D("load_file: could not read %ld bytes from '%s'\n", file_size, fn);
  61. free(data);
  62. data = NULL;
  63. file_size = 0;
  64. }
  65. }
  66. }
  67. CloseHandle( file );
  68. *_sz = (unsigned) file_size;
  69. return data;
  70. }
  71. /**************************************************************************/
  72. /**************************************************************************/
  73. /***** *****/
  74. /***** common file descriptor handling *****/
  75. /***** *****/
  76. /**************************************************************************/
  77. /**************************************************************************/
  78. typedef const struct FHClassRec_* FHClass;
  79. typedef struct FHRec_* FH;
  80. typedef struct EventHookRec_* EventHook;
  81. typedef struct FHClassRec_
  82. {
  83. void (*_fh_init) ( FH f );
  84. int (*_fh_close)( FH f );
  85. int (*_fh_lseek)( FH f, int pos, int origin );
  86. int (*_fh_read) ( FH f, void* buf, int len );
  87. int (*_fh_write)( FH f, const void* buf, int len );
  88. void (*_fh_hook) ( FH f, int events, EventHook hook );
  89. } FHClassRec;
  90. /* used to emulate unix-domain socket pairs */
  91. typedef struct SocketPairRec_* SocketPair;
  92. typedef struct FHRec_
  93. {
  94. FHClass clazz;
  95. int used;
  96. int eof;
  97. union {
  98. HANDLE handle;
  99. SOCKET socket;
  100. SocketPair pair;
  101. } u;
  102. HANDLE event;
  103. int mask;
  104. char name[32];
  105. } FHRec;
  106. #define fh_handle u.handle
  107. #define fh_socket u.socket
  108. #define fh_pair u.pair
  109. #define WIN32_FH_BASE 100
  110. #define WIN32_MAX_FHS 128
  111. static adb_mutex_t _win32_lock;
  112. static FHRec _win32_fhs[ WIN32_MAX_FHS ];
  113. static int _win32_fh_count;
  114. static FH
  115. _fh_from_int( int fd )
  116. {
  117. FH f;
  118. fd -= WIN32_FH_BASE;
  119. if (fd < 0 || fd >= _win32_fh_count) {
  120. D( "_fh_from_int: invalid fd %d\n", fd + WIN32_FH_BASE );
  121. errno = EBADF;
  122. return NULL;
  123. }
  124. f = &_win32_fhs[fd];
  125. if (f->used == 0) {
  126. D( "_fh_from_int: invalid fd %d\n", fd + WIN32_FH_BASE );
  127. errno = EBADF;
  128. return NULL;
  129. }
  130. return f;
  131. }
  132. static int
  133. _fh_to_int( FH f )
  134. {
  135. if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
  136. return (int)(f - _win32_fhs) + WIN32_FH_BASE;
  137. return -1;
  138. }
  139. static FH
  140. _fh_alloc( FHClass clazz )
  141. {
  142. int nn;
  143. FH f = NULL;
  144. adb_mutex_lock( &_win32_lock );
  145. if (_win32_fh_count < WIN32_MAX_FHS) {
  146. f = &_win32_fhs[ _win32_fh_count++ ];
  147. goto Exit;
  148. }
  149. for (nn = 0; nn < WIN32_MAX_FHS; nn++) {
  150. if ( _win32_fhs[nn].clazz == NULL) {
  151. f = &_win32_fhs[nn];
  152. goto Exit;
  153. }
  154. }
  155. D( "_fh_alloc: no more free file descriptors\n" );
  156. Exit:
  157. if (f) {
  158. f->clazz = clazz;
  159. f->used = 1;
  160. f->eof = 0;
  161. clazz->_fh_init(f);
  162. }
  163. adb_mutex_unlock( &_win32_lock );
  164. return f;
  165. }
  166. static int
  167. _fh_close( FH f )
  168. {
  169. if ( f->used ) {
  170. f->clazz->_fh_close( f );
  171. f->used = 0;
  172. f->eof = 0;
  173. f->clazz = NULL;
  174. }
  175. return 0;
  176. }
  177. /* forward definitions */
  178. static const FHClassRec _fh_file_class;
  179. static const FHClassRec _fh_socket_class;
  180. /**************************************************************************/
  181. /**************************************************************************/
  182. /***** *****/
  183. /***** file-based descriptor handling *****/
  184. /***** *****/
  185. /**************************************************************************/
  186. /**************************************************************************/
  187. static void
  188. _fh_file_init( FH f )
  189. {
  190. f->fh_handle = INVALID_HANDLE_VALUE;
  191. }
  192. static int
  193. _fh_file_close( FH f )
  194. {
  195. CloseHandle( f->fh_handle );
  196. f->fh_handle = INVALID_HANDLE_VALUE;
  197. return 0;
  198. }
  199. static int
  200. _fh_file_read( FH f, void* buf, int len )
  201. {
  202. DWORD read_bytes;
  203. if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
  204. D( "adb_read: could not read %d bytes from %s\n", len, f->name );
  205. errno = EIO;
  206. return -1;
  207. } else if (read_bytes < (DWORD)len) {
  208. f->eof = 1;
  209. }
  210. return (int)read_bytes;
  211. }
  212. static int
  213. _fh_file_write( FH f, const void* buf, int len )
  214. {
  215. DWORD wrote_bytes;
  216. if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
  217. D( "adb_file_write: could not write %d bytes from %s\n", len, f->name );
  218. errno = EIO;
  219. return -1;
  220. } else if (wrote_bytes < (DWORD)len) {
  221. f->eof = 1;
  222. }
  223. return (int)wrote_bytes;
  224. }
  225. static int
  226. _fh_file_lseek( FH f, int pos, int origin )
  227. {
  228. DWORD method;
  229. DWORD result;
  230. switch (origin)
  231. {
  232. case SEEK_SET: method = FILE_BEGIN; break;
  233. case SEEK_CUR: method = FILE_CURRENT; break;
  234. case SEEK_END: method = FILE_END; break;
  235. default:
  236. errno = EINVAL;
  237. return -1;
  238. }
  239. result = SetFilePointer( f->fh_handle, pos, NULL, method );
  240. if (result == INVALID_SET_FILE_POINTER) {
  241. errno = EIO;
  242. return -1;
  243. } else {
  244. f->eof = 0;
  245. }
  246. return (int)result;
  247. }
  248. static void _fh_file_hook( FH f, int event, EventHook eventhook ); /* forward */
  249. static const FHClassRec _fh_file_class =
  250. {
  251. _fh_file_init,
  252. _fh_file_close,
  253. _fh_file_lseek,
  254. _fh_file_read,
  255. _fh_file_write,
  256. _fh_file_hook
  257. };
  258. /**************************************************************************/
  259. /**************************************************************************/
  260. /***** *****/
  261. /***** file-based descriptor handling *****/
  262. /***** *****/
  263. /**************************************************************************/
  264. /**************************************************************************/
  265. int adb_open(const char* path, int options)
  266. {
  267. FH f;
  268. DWORD desiredAccess = 0;
  269. DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  270. switch (options) {
  271. case O_RDONLY:
  272. desiredAccess = GENERIC_READ;
  273. break;
  274. case O_WRONLY:
  275. desiredAccess = GENERIC_WRITE;
  276. break;
  277. case O_RDWR:
  278. desiredAccess = GENERIC_READ | GENERIC_WRITE;
  279. break;
  280. default:
  281. D("adb_open: invalid options (0x%0x)\n", options);
  282. errno = EINVAL;
  283. return -1;
  284. }
  285. f = _fh_alloc( &_fh_file_class );
  286. if ( !f ) {
  287. errno = ENOMEM;
  288. return -1;
  289. }
  290. f->fh_handle = CreateFile( path, desiredAccess, shareMode, NULL, OPEN_EXISTING,
  291. 0, NULL );
  292. if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
  293. _fh_close(f);
  294. D( "adb_open: could not open '%s':", path );
  295. switch (GetLastError()) {
  296. case ERROR_FILE_NOT_FOUND:
  297. D( "file not found\n" );
  298. errno = ENOENT;
  299. return -1;
  300. case ERROR_PATH_NOT_FOUND:
  301. D( "path not found\n" );
  302. errno = ENOTDIR;
  303. return -1;
  304. default:
  305. D( "unknown error\n" );
  306. errno = ENOENT;
  307. return -1;
  308. }
  309. }
  310. snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
  311. D( "adb_open: '%s' => fd %d\n", path, _fh_to_int(f) );
  312. return _fh_to_int(f);
  313. }
  314. /* ignore mode on Win32 */
  315. int adb_creat(const char* path, int mode)
  316. {
  317. FH f;
  318. f = _fh_alloc( &_fh_file_class );
  319. if ( !f ) {
  320. errno = ENOMEM;
  321. return -1;
  322. }
  323. f->fh_handle = CreateFile( path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
  324. NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
  325. NULL );
  326. if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
  327. _fh_close(f);
  328. D( "adb_creat: could not open '%s':", path );
  329. switch (GetLastError()) {
  330. case ERROR_FILE_NOT_FOUND:
  331. D( "file not found\n" );
  332. errno = ENOENT;
  333. return -1;
  334. case ERROR_PATH_NOT_FOUND:
  335. D( "path not found\n" );
  336. errno = ENOTDIR;
  337. return -1;
  338. default:
  339. D( "unknown error\n" );
  340. errno = ENOENT;
  341. return -1;
  342. }
  343. }
  344. snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
  345. D( "adb_creat: '%s' => fd %d\n", path, _fh_to_int(f) );
  346. return _fh_to_int(f);
  347. }
  348. int adb_read(int fd, void* buf, int len)
  349. {
  350. FH f = _fh_from_int(fd);
  351. if (f == NULL) {
  352. return -1;
  353. }
  354. return f->clazz->_fh_read( f, buf, len );
  355. }
  356. int adb_write(int fd, const void* buf, int len)
  357. {
  358. FH f = _fh_from_int(fd);
  359. if (f == NULL) {
  360. return -1;
  361. }
  362. return f->clazz->_fh_write(f, buf, len);
  363. }
  364. int adb_lseek(int fd, int pos, int where)
  365. {
  366. FH f = _fh_from_int(fd);
  367. if (!f) {
  368. return -1;
  369. }
  370. return f->clazz->_fh_lseek(f, pos, where);
  371. }
  372. int adb_shutdown(int fd)
  373. {
  374. FH f = _fh_from_int(fd);
  375. if (!f || f->clazz != &_fh_socket_class) {
  376. D("adb_shutdown: invalid fd %d\n", fd);
  377. return -1;
  378. }
  379. D( "adb_shutdown: %s\n", f->name);
  380. shutdown( f->fh_socket, SD_BOTH );
  381. return 0;
  382. }
  383. int adb_close(int fd)
  384. {
  385. FH f = _fh_from_int(fd);
  386. if (!f) {
  387. return -1;
  388. }
  389. D( "adb_close: %s\n", f->name);
  390. _fh_close(f);
  391. return 0;
  392. }
  393. /**************************************************************************/
  394. /**************************************************************************/
  395. /***** *****/
  396. /***** socket-based file descriptors *****/
  397. /***** *****/
  398. /**************************************************************************/
  399. /**************************************************************************/
  400. #undef setsockopt
  401. static void
  402. _socket_set_errno( void )
  403. {
  404. switch (WSAGetLastError()) {
  405. case 0: errno = 0; break;
  406. case WSAEWOULDBLOCK: errno = EAGAIN; break;
  407. case WSAEINTR: errno = EINTR; break;
  408. default:
  409. D( "_socket_set_errno: unhandled value %d\n", WSAGetLastError() );
  410. errno = EINVAL;
  411. }
  412. }
  413. static void
  414. _fh_socket_init( FH f )
  415. {
  416. f->fh_socket = INVALID_SOCKET;
  417. f->event = WSACreateEvent();
  418. f->mask = 0;
  419. }
  420. static int
  421. _fh_socket_close( FH f )
  422. {
  423. /* gently tell any peer that we're closing the socket */
  424. shutdown( f->fh_socket, SD_BOTH );
  425. closesocket( f->fh_socket );
  426. f->fh_socket = INVALID_SOCKET;
  427. CloseHandle( f->event );
  428. f->mask = 0;
  429. return 0;
  430. }
  431. static int
  432. _fh_socket_lseek( FH f, int pos, int origin )
  433. {
  434. errno = EPIPE;
  435. return -1;
  436. }
  437. static int
  438. _fh_socket_read( FH f, void* buf, int len )
  439. {
  440. int result = recv( f->fh_socket, buf, len, 0 );
  441. if (result == SOCKET_ERROR) {
  442. _socket_set_errno();
  443. result = -1;
  444. }
  445. return result;
  446. }
  447. static int
  448. _fh_socket_write( FH f, const void* buf, int len )
  449. {
  450. int result = send( f->fh_socket, buf, len, 0 );
  451. if (result == SOCKET_ERROR) {
  452. _socket_set_errno();
  453. result = -1;
  454. }
  455. return result;
  456. }
  457. static void _fh_socket_hook( FH f, int event, EventHook hook ); /* forward */
  458. static const FHClassRec _fh_socket_class =
  459. {
  460. _fh_socket_init,
  461. _fh_socket_close,
  462. _fh_socket_lseek,
  463. _fh_socket_read,
  464. _fh_socket_write,
  465. _fh_socket_hook
  466. };
  467. /**************************************************************************/
  468. /**************************************************************************/
  469. /***** *****/
  470. /***** replacement for libs/cutils/socket_xxxx.c *****/
  471. /***** *****/
  472. /**************************************************************************/
  473. /**************************************************************************/
  474. #include <winsock2.h>
  475. static int _winsock_init;
  476. static void
  477. _cleanup_winsock( void )
  478. {
  479. WSACleanup();
  480. }
  481. static void
  482. _init_winsock( void )
  483. {
  484. if (!_winsock_init) {
  485. WSADATA wsaData;
  486. int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
  487. if (rc != 0) {
  488. fatal( "adb: could not initialize Winsock\n" );
  489. }
  490. atexit( _cleanup_winsock );
  491. _winsock_init = 1;
  492. }
  493. }
  494. int socket_loopback_client(int port, int type)
  495. {
  496. FH f = _fh_alloc( &_fh_socket_class );
  497. struct sockaddr_in addr;
  498. SOCKET s;
  499. if (!f)
  500. return -1;
  501. if (!_winsock_init)
  502. _init_winsock();
  503. memset(&addr, 0, sizeof(addr));
  504. addr.sin_family = AF_INET;
  505. addr.sin_port = htons(port);
  506. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  507. s = socket(AF_INET, type, 0);
  508. if(s == INVALID_SOCKET) {
  509. D("socket_loopback_client: could not create socket\n" );
  510. _fh_close(f);
  511. return -1;
  512. }
  513. f->fh_socket = s;
  514. if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  515. D("socket_loopback_client: could not connect to %s:%d\n", type != SOCK_STREAM ? "udp" : "tcp", port );
  516. _fh_close(f);
  517. return -1;
  518. }
  519. snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
  520. D( "socket_loopback_client: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
  521. return _fh_to_int(f);
  522. }
  523. #define LISTEN_BACKLOG 4
  524. int socket_loopback_server(int port, int type)
  525. {
  526. FH f = _fh_alloc( &_fh_socket_class );
  527. struct sockaddr_in addr;
  528. SOCKET s;
  529. int n;
  530. if (!f) {
  531. return -1;
  532. }
  533. if (!_winsock_init)
  534. _init_winsock();
  535. memset(&addr, 0, sizeof(addr));
  536. addr.sin_family = AF_INET;
  537. addr.sin_port = htons(port);
  538. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  539. s = socket(AF_INET, type, 0);
  540. if(s == INVALID_SOCKET) return -1;
  541. f->fh_socket = s;
  542. n = 1;
  543. setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n));
  544. if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  545. _fh_close(f);
  546. return -1;
  547. }
  548. if (type == SOCK_STREAM) {
  549. int ret;
  550. ret = listen(s, LISTEN_BACKLOG);
  551. if (ret < 0) {
  552. _fh_close(f);
  553. return -1;
  554. }
  555. }
  556. snprintf( f->name, sizeof(f->name), "%d(lo-server:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
  557. D( "socket_loopback_server: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
  558. return _fh_to_int(f);
  559. }
  560. int socket_network_client(const char *host, int port, int type)
  561. {
  562. FH f = _fh_alloc( &_fh_socket_class );
  563. struct hostent *hp;
  564. struct sockaddr_in addr;
  565. SOCKET s;
  566. if (!f)
  567. return -1;
  568. if (!_winsock_init)
  569. _init_winsock();
  570. hp = gethostbyname(host);
  571. if(hp == 0) {
  572. _fh_close(f);
  573. return -1;
  574. }
  575. memset(&addr, 0, sizeof(addr));
  576. addr.sin_family = hp->h_addrtype;
  577. addr.sin_port = htons(port);
  578. memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
  579. s = socket(hp->h_addrtype, type, 0);
  580. if(s == INVALID_SOCKET) {
  581. _fh_close(f);
  582. return -1;
  583. }
  584. f->fh_socket = s;
  585. if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  586. _fh_close(f);
  587. return -1;
  588. }
  589. snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
  590. D( "socket_network_client: host '%s' port %d type %s => fd %d\n", host, port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
  591. return _fh_to_int(f);
  592. }
  593. int socket_network_client_timeout(const char *host, int port, int type, int timeout)
  594. {
  595. // TODO: implement timeouts for Windows.
  596. return socket_network_client(host, port, type);
  597. }
  598. int socket_inaddr_any_server(int port, int type)
  599. {
  600. FH f = _fh_alloc( &_fh_socket_class );
  601. struct sockaddr_in addr;
  602. SOCKET s;
  603. int n;
  604. if (!f)
  605. return -1;
  606. if (!_winsock_init)
  607. _init_winsock();
  608. memset(&addr, 0, sizeof(addr));
  609. addr.sin_family = AF_INET;
  610. addr.sin_port = htons(port);
  611. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  612. s = socket(AF_INET, type, 0);
  613. if(s == INVALID_SOCKET) {
  614. _fh_close(f);
  615. return -1;
  616. }
  617. f->fh_socket = s;
  618. n = 1;
  619. setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n));
  620. if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  621. _fh_close(f);
  622. return -1;
  623. }
  624. if (type == SOCK_STREAM) {
  625. int ret;
  626. ret = listen(s, LISTEN_BACKLOG);
  627. if (ret < 0) {
  628. _fh_close(f);
  629. return -1;
  630. }
  631. }
  632. snprintf( f->name, sizeof(f->name), "%d(any-server:%s%d)", _fh_to_int(f), type != SOCK_STREAM ? "udp:" : "", port );
  633. D( "socket_inaddr_server: port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp", _fh_to_int(f) );
  634. return _fh_to_int(f);
  635. }
  636. #undef accept
  637. int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
  638. {
  639. FH serverfh = _fh_from_int(serverfd);
  640. FH fh;
  641. if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
  642. D( "adb_socket_accept: invalid fd %d\n", serverfd );
  643. return -1;
  644. }
  645. fh = _fh_alloc( &_fh_socket_class );
  646. if (!fh) {
  647. D( "adb_socket_accept: not enough memory to allocate accepted socket descriptor\n" );
  648. return -1;
  649. }
  650. fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
  651. if (fh->fh_socket == INVALID_SOCKET) {
  652. _fh_close( fh );
  653. D( "adb_socket_accept: accept on fd %d return error %ld\n", serverfd, GetLastError() );
  654. return -1;
  655. }
  656. snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", _fh_to_int(fh), serverfh->name );
  657. D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, _fh_to_int(fh) );
  658. return _fh_to_int(fh);
  659. }
  660. int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
  661. {
  662. FH fh = _fh_from_int(fd);
  663. if ( !fh || fh->clazz != &_fh_socket_class ) {
  664. D("adb_setsockopt: invalid fd %d\n", fd);
  665. return -1;
  666. }
  667. return setsockopt( fh->fh_socket, level, optname, optval, optlen );
  668. }
  669. /**************************************************************************/
  670. /**************************************************************************/
  671. /***** *****/
  672. /***** emulated socketpairs *****/
  673. /***** *****/
  674. /**************************************************************************/
  675. /**************************************************************************/
  676. /* we implement socketpairs directly in use space for the following reasons:
  677. * - it avoids copying data from/to the Nt kernel
  678. * - it allows us to implement fdevent hooks easily and cheaply, something
  679. * that is not possible with standard Win32 pipes !!
  680. *
  681. * basically, we use two circular buffers, each one corresponding to a given
  682. * direction.
  683. *
  684. * each buffer is implemented as two regions:
  685. *
  686. * region A which is (a_start,a_end)
  687. * region B which is (0, b_end) with b_end <= a_start
  688. *
  689. * an empty buffer has: a_start = a_end = b_end = 0
  690. *
  691. * a_start is the pointer where we start reading data
  692. * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
  693. * then you start writing at b_end
  694. *
  695. * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
  696. *
  697. * there is room when b_end < a_start || a_end < BUFER_SIZE
  698. *
  699. * when reading, a_start is incremented, it a_start meets a_end, then
  700. * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
  701. */
  702. #define BIP_BUFFER_SIZE 4096
  703. #if 0
  704. #include <stdio.h>
  705. # define BIPD(x) D x
  706. # define BIPDUMP bip_dump_hex
  707. static void bip_dump_hex( const unsigned char* ptr, size_t len )
  708. {
  709. int nn, len2 = len;
  710. if (len2 > 8) len2 = 8;
  711. for (nn = 0; nn < len2; nn++)
  712. printf("%02x", ptr[nn]);
  713. printf(" ");
  714. for (nn = 0; nn < len2; nn++) {
  715. int c = ptr[nn];
  716. if (c < 32 || c > 127)
  717. c = '.';
  718. printf("%c", c);
  719. }
  720. printf("\n");
  721. fflush(stdout);
  722. }
  723. #else
  724. # define BIPD(x) do {} while (0)
  725. # define BIPDUMP(p,l) BIPD(p)
  726. #endif
  727. typedef struct BipBufferRec_
  728. {
  729. int a_start;
  730. int a_end;
  731. int b_end;
  732. int fdin;
  733. int fdout;
  734. int closed;
  735. int can_write; /* boolean */
  736. HANDLE evt_write; /* event signaled when one can write to a buffer */
  737. int can_read; /* boolean */
  738. HANDLE evt_read; /* event signaled when one can read from a buffer */
  739. CRITICAL_SECTION lock;
  740. unsigned char buff[ BIP_BUFFER_SIZE ];
  741. } BipBufferRec, *BipBuffer;
  742. static void
  743. bip_buffer_init( BipBuffer buffer )
  744. {
  745. D( "bit_buffer_init %p\n", buffer );
  746. buffer->a_start = 0;
  747. buffer->a_end = 0;
  748. buffer->b_end = 0;
  749. buffer->can_write = 1;
  750. buffer->can_read = 0;
  751. buffer->fdin = 0;
  752. buffer->fdout = 0;
  753. buffer->closed = 0;
  754. buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
  755. buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
  756. InitializeCriticalSection( &buffer->lock );
  757. }
  758. static void
  759. bip_buffer_close( BipBuffer bip )
  760. {
  761. bip->closed = 1;
  762. if (!bip->can_read) {
  763. SetEvent( bip->evt_read );
  764. }
  765. if (!bip->can_write) {
  766. SetEvent( bip->evt_write );
  767. }
  768. }
  769. static void
  770. bip_buffer_done( BipBuffer bip )
  771. {
  772. BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
  773. CloseHandle( bip->evt_read );
  774. CloseHandle( bip->evt_write );
  775. DeleteCriticalSection( &bip->lock );
  776. }
  777. static int
  778. bip_buffer_write( BipBuffer bip, const void* src, int len )
  779. {
  780. int avail, count = 0;
  781. if (len <= 0)
  782. return 0;
  783. BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
  784. BIPDUMP( src, len );
  785. EnterCriticalSection( &bip->lock );
  786. while (!bip->can_write) {
  787. int ret;
  788. LeaveCriticalSection( &bip->lock );
  789. if (bip->closed) {
  790. errno = EPIPE;
  791. return -1;
  792. }
  793. /* spinlocking here is probably unfair, but let's live with it */
  794. ret = WaitForSingleObject( bip->evt_write, INFINITE );
  795. if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
  796. D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
  797. return 0;
  798. }
  799. if (bip->closed) {
  800. errno = EPIPE;
  801. return -1;
  802. }
  803. EnterCriticalSection( &bip->lock );
  804. }
  805. BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
  806. avail = BIP_BUFFER_SIZE - bip->a_end;
  807. if (avail > 0)
  808. {
  809. /* we can append to region A */
  810. if (avail > len)
  811. avail = len;
  812. memcpy( bip->buff + bip->a_end, src, avail );
  813. src = (const char *)src + avail;
  814. count += avail;
  815. len -= avail;
  816. bip->a_end += avail;
  817. if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
  818. bip->can_write = 0;
  819. ResetEvent( bip->evt_write );
  820. goto Exit;
  821. }
  822. }
  823. if (len == 0)
  824. goto Exit;
  825. avail = bip->a_start - bip->b_end;
  826. assert( avail > 0 ); /* since can_write is TRUE */
  827. if (avail > len)
  828. avail = len;
  829. memcpy( bip->buff + bip->b_end, src, avail );
  830. count += avail;
  831. bip->b_end += avail;
  832. if (bip->b_end == bip->a_start) {
  833. bip->can_write = 0;
  834. ResetEvent( bip->evt_write );
  835. }
  836. Exit:
  837. assert( count > 0 );
  838. if ( !bip->can_read ) {
  839. bip->can_read = 1;
  840. SetEvent( bip->evt_read );
  841. }
  842. BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
  843. bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
  844. LeaveCriticalSection( &bip->lock );
  845. return count;
  846. }
  847. static int
  848. bip_buffer_read( BipBuffer bip, void* dst, int len )
  849. {
  850. int avail, count = 0;
  851. if (len <= 0)
  852. return 0;
  853. BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
  854. EnterCriticalSection( &bip->lock );
  855. while ( !bip->can_read )
  856. {
  857. #if 0
  858. LeaveCriticalSection( &bip->lock );
  859. errno = EAGAIN;
  860. return -1;
  861. #else
  862. int ret;
  863. LeaveCriticalSection( &bip->lock );
  864. if (bip->closed) {
  865. errno = EPIPE;
  866. return -1;
  867. }
  868. ret = WaitForSingleObject( bip->evt_read, INFINITE );
  869. if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
  870. D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
  871. return 0;
  872. }
  873. if (bip->closed) {
  874. errno = EPIPE;
  875. return -1;
  876. }
  877. EnterCriticalSection( &bip->lock );
  878. #endif
  879. }
  880. BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
  881. avail = bip->a_end - bip->a_start;
  882. assert( avail > 0 ); /* since can_read is TRUE */
  883. if (avail > len)
  884. avail = len;
  885. memcpy( dst, bip->buff + bip->a_start, avail );
  886. dst = (char *)dst + avail;
  887. count += avail;
  888. len -= avail;
  889. bip->a_start += avail;
  890. if (bip->a_start < bip->a_end)
  891. goto Exit;
  892. bip->a_start = 0;
  893. bip->a_end = bip->b_end;
  894. bip->b_end = 0;
  895. avail = bip->a_end;
  896. if (avail > 0) {
  897. if (avail > len)
  898. avail = len;
  899. memcpy( dst, bip->buff, avail );
  900. count += avail;
  901. bip->a_start += avail;
  902. if ( bip->a_start < bip->a_end )
  903. goto Exit;
  904. bip->a_start = bip->a_end = 0;
  905. }
  906. bip->can_read = 0;
  907. ResetEvent( bip->evt_read );
  908. Exit:
  909. assert( count > 0 );
  910. if (!bip->can_write ) {
  911. bip->can_write = 1;
  912. SetEvent( bip->evt_write );
  913. }
  914. BIPDUMP( (const unsigned char*)dst - count, count );
  915. BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
  916. bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
  917. LeaveCriticalSection( &bip->lock );
  918. return count;
  919. }
  920. typedef struct SocketPairRec_
  921. {
  922. BipBufferRec a2b_bip;
  923. BipBufferRec b2a_bip;
  924. FH a_fd;
  925. int used;
  926. } SocketPairRec;
  927. void _fh_socketpair_init( FH f )
  928. {
  929. f->fh_pair = NULL;
  930. }
  931. static int
  932. _fh_socketpair_close( FH f )
  933. {
  934. if ( f->fh_pair ) {
  935. SocketPair pair = f->fh_pair;
  936. if ( f == pair->a_fd ) {
  937. pair->a_fd = NULL;
  938. }
  939. bip_buffer_close( &pair->b2a_bip );
  940. bip_buffer_close( &pair->a2b_bip );
  941. if ( --pair->used == 0 ) {
  942. bip_buffer_done( &pair->b2a_bip );
  943. bip_buffer_done( &pair->a2b_bip );
  944. free( pair );
  945. }
  946. f->fh_pair = NULL;
  947. }
  948. return 0;
  949. }
  950. static int
  951. _fh_socketpair_lseek( FH f, int pos, int origin )
  952. {
  953. errno = ESPIPE;
  954. return -1;
  955. }
  956. static int
  957. _fh_socketpair_read( FH f, void* buf, int len )
  958. {
  959. SocketPair pair = f->fh_pair;
  960. BipBuffer bip;
  961. if (!pair)
  962. return -1;
  963. if ( f == pair->a_fd )
  964. bip = &pair->b2a_bip;
  965. else
  966. bip = &pair->a2b_bip;
  967. return bip_buffer_read( bip, buf, len );
  968. }
  969. static int
  970. _fh_socketpair_write( FH f, const void* buf, int len )
  971. {
  972. SocketPair pair = f->fh_pair;
  973. BipBuffer bip;
  974. if (!pair)
  975. return -1;
  976. if ( f == pair->a_fd )
  977. bip = &pair->a2b_bip;
  978. else
  979. bip = &pair->b2a_bip;
  980. return bip_buffer_write( bip, buf, len );
  981. }
  982. static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
  983. static const FHClassRec _fh_socketpair_class =
  984. {
  985. _fh_socketpair_init,
  986. _fh_socketpair_close,
  987. _fh_socketpair_lseek,
  988. _fh_socketpair_read,
  989. _fh_socketpair_write,
  990. _fh_socketpair_hook
  991. };
  992. int adb_socketpair( int sv[2] )
  993. {
  994. FH fa, fb;
  995. SocketPair pair;
  996. fa = _fh_alloc( &_fh_socketpair_class );
  997. fb = _fh_alloc( &_fh_socketpair_class );
  998. if (!fa || !fb)
  999. goto Fail;
  1000. pair = malloc( sizeof(*pair) );
  1001. if (pair == NULL) {
  1002. D("adb_socketpair: not enough memory to allocate pipes\n" );
  1003. goto Fail;
  1004. }
  1005. bip_buffer_init( &pair->a2b_bip );
  1006. bip_buffer_init( &pair->b2a_bip );
  1007. fa->fh_pair = pair;
  1008. fb->fh_pair = pair;
  1009. pair->used = 2;
  1010. pair->a_fd = fa;
  1011. sv[0] = _fh_to_int(fa);
  1012. sv[1] = _fh_to_int(fb);
  1013. pair->a2b_bip.fdin = sv[0];
  1014. pair->a2b_bip.fdout = sv[1];
  1015. pair->b2a_bip.fdin = sv[1];
  1016. pair->b2a_bip.fdout = sv[0];
  1017. snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
  1018. snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
  1019. D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
  1020. return 0;
  1021. Fail:
  1022. _fh_close(fb);
  1023. _fh_close(fa);
  1024. return -1;
  1025. }
  1026. /**************************************************************************/
  1027. /**************************************************************************/
  1028. /***** *****/
  1029. /***** fdevents emulation *****/
  1030. /***** *****/
  1031. /***** this is a very simple implementation, we rely on the fact *****/
  1032. /***** that ADB doesn't use FDE_ERROR. *****/
  1033. /***** *****/
  1034. /**************************************************************************/
  1035. /**************************************************************************/
  1036. #define FATAL(x...) fatal(__FUNCTION__, x)
  1037. #if DEBUG
  1038. static void dump_fde(fdevent *fde, const char *info)
  1039. {
  1040. fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
  1041. fde->state & FDE_READ ? 'R' : ' ',
  1042. fde->state & FDE_WRITE ? 'W' : ' ',
  1043. fde->state & FDE_ERROR ? 'E' : ' ',
  1044. info);
  1045. }
  1046. #else
  1047. #define dump_fde(fde, info) do { } while(0)
  1048. #endif
  1049. #define FDE_EVENTMASK 0x00ff
  1050. #define FDE_STATEMASK 0xff00
  1051. #define FDE_ACTIVE 0x0100
  1052. #define FDE_PENDING 0x0200
  1053. #define FDE_CREATED 0x0400
  1054. static void fdevent_plist_enqueue(fdevent *node);
  1055. static void fdevent_plist_remove(fdevent *node);
  1056. static fdevent *fdevent_plist_dequeue(void);
  1057. static fdevent list_pending = {
  1058. .next = &list_pending,
  1059. .prev = &list_pending,
  1060. };
  1061. static fdevent **fd_table = 0;
  1062. static int fd_table_max = 0;
  1063. typedef struct EventLooperRec_* EventLooper;
  1064. typedef struct EventHookRec_
  1065. {
  1066. EventHook next;
  1067. FH fh;
  1068. HANDLE h;
  1069. int wanted; /* wanted event flags */
  1070. int ready; /* ready event flags */
  1071. void* aux;
  1072. void (*prepare)( EventHook hook );
  1073. int (*start) ( EventHook hook );
  1074. void (*stop) ( EventHook hook );
  1075. int (*check) ( EventHook hook );
  1076. int (*peek) ( EventHook hook );
  1077. } EventHookRec;
  1078. static EventHook _free_hooks;
  1079. static EventHook
  1080. event_hook_alloc( FH fh )
  1081. {
  1082. EventHook hook = _free_hooks;
  1083. if (hook != NULL)
  1084. _free_hooks = hook->next;
  1085. else {
  1086. hook = malloc( sizeof(*hook) );
  1087. if (hook == NULL)
  1088. fatal( "could not allocate event hook\n" );
  1089. }
  1090. hook->next = NULL;
  1091. hook->fh = fh;
  1092. hook->wanted = 0;
  1093. hook->ready = 0;
  1094. hook->h = INVALID_HANDLE_VALUE;
  1095. hook->aux = NULL;
  1096. hook->prepare = NULL;
  1097. hook->start = NULL;
  1098. hook->stop = NULL;
  1099. hook->check = NULL;
  1100. hook->peek = NULL;
  1101. return hook;
  1102. }
  1103. static void
  1104. event_hook_free( EventHook hook )
  1105. {
  1106. hook->fh = NULL;
  1107. hook->wanted = 0;
  1108. hook->ready = 0;
  1109. hook->next = _free_hooks;
  1110. _free_hooks = hook;
  1111. }
  1112. static void
  1113. event_hook_signal( EventHook hook )
  1114. {
  1115. FH f = hook->fh;
  1116. int fd = _fh_to_int(f);
  1117. fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
  1118. if (fde != NULL && fde->fd == fd) {
  1119. if ((fde->state & FDE_PENDING) == 0) {
  1120. fde->state |= FDE_PENDING;
  1121. fdevent_plist_enqueue( fde );
  1122. }
  1123. fde->events |= hook->wanted;
  1124. }
  1125. }
  1126. #define MAX_LOOPER_HANDLES WIN32_MAX_FHS
  1127. typedef struct EventLooperRec_
  1128. {
  1129. EventHook hooks;
  1130. HANDLE htab[ MAX_LOOPER_HANDLES ];
  1131. int htab_count;
  1132. } EventLooperRec;
  1133. static EventHook*
  1134. event_looper_find_p( EventLooper looper, FH fh )
  1135. {
  1136. EventHook *pnode = &looper->hooks;
  1137. EventHook node = *pnode;
  1138. for (;;) {
  1139. if ( node == NULL || node->fh == fh )
  1140. break;
  1141. pnode = &node->next;
  1142. node = *pnode;
  1143. }
  1144. return pnode;
  1145. }
  1146. static void
  1147. event_looper_hook( EventLooper looper, int fd, int events )
  1148. {
  1149. FH f = _fh_from_int(fd);
  1150. EventHook *pnode;
  1151. EventHook node;
  1152. if (f == NULL) /* invalid arg */ {
  1153. D("event_looper_hook: invalid fd=%d\n", fd);
  1154. return;
  1155. }
  1156. pnode = event_looper_find_p( looper, f );
  1157. node = *pnode;
  1158. if ( node == NULL ) {
  1159. node = event_hook_alloc( f );
  1160. node->next = *pnode;
  1161. *pnode = node;
  1162. }
  1163. if ( (node->wanted & events) != events ) {
  1164. /* this should update start/stop/check/peek */
  1165. D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
  1166. fd, node->wanted, events);
  1167. f->clazz->_fh_hook( f, events & ~node->wanted, node );
  1168. node->wanted |= events;
  1169. } else {
  1170. D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
  1171. events, fd, node->wanted);
  1172. }
  1173. }
  1174. static void
  1175. event_looper_unhook( EventLooper looper, int fd, int events )
  1176. {
  1177. FH fh = _fh_from_int(fd);
  1178. EventHook *pnode = event_looper_find_p( looper, fh );
  1179. EventHook node = *pnode;
  1180. if (node != NULL) {
  1181. int events2 = events & node->wanted;
  1182. if ( events2 == 0 ) {
  1183. D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
  1184. return;
  1185. }
  1186. node->wanted &= ~events2;
  1187. if (!node->wanted) {
  1188. *pnode = node->next;
  1189. event_hook_free( node );
  1190. }
  1191. }
  1192. }
  1193. /*
  1194. * A fixer for WaitForMultipleObjects on condition that there are more than 64
  1195. * handles to wait on.
  1196. *
  1197. * In cetain cases DDMS may establish more than 64 connections with ADB. For
  1198. * instance, this may happen if there are more than 64 processes running on a
  1199. * device, or there are multiple devices connected (including the emulator) with
  1200. * the combined number of running processes greater than 64. In this case using
  1201. * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
  1202. * because of the API limitations (64 handles max). So, we need to provide a way
  1203. * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
  1204. * easiest (and "Microsoft recommended") way to do that would be dividing the
  1205. * handle array into chunks with the chunk size less than 64, and fire up as many
  1206. * waiting threads as there are chunks. Then each thread would wait on a chunk of
  1207. * handles, and will report back to the caller which handle has been set.
  1208. * Here is the implementation of that algorithm.
  1209. */
  1210. /* Number of handles to wait on in each wating thread. */
  1211. #define WAIT_ALL_CHUNK_SIZE 63
  1212. /* Descriptor for a wating thread */
  1213. typedef struct WaitForAllParam {
  1214. /* A handle to an event to signal when waiting is over. This handle is shared
  1215. * accross all the waiting threads, so each waiting thread knows when any
  1216. * other thread has exited, so it can exit too. */
  1217. HANDLE main_event;
  1218. /* Upon exit from a waiting thread contains the index of the handle that has
  1219. * been signaled. The index is an absolute index of the signaled handle in
  1220. * the original array. This pointer is shared accross all the waiting threads
  1221. * and it's not guaranteed (due to a race condition) that when all the
  1222. * waiting threads exit, the value contained here would indicate the first
  1223. * handle that was signaled. This is fine, because the caller cares only
  1224. * about any handle being signaled. It doesn't care about the order, nor
  1225. * about the whole list of handles that were signaled. */
  1226. LONG volatile *signaled_index;
  1227. /* Array of handles to wait on in a waiting thread. */
  1228. HANDLE* handles;
  1229. /* Number of handles in 'handles' array to wait on. */
  1230. int handles_count;
  1231. /* Index inside the main array of the first handle in the 'handles' array. */
  1232. int first_handle_index;
  1233. /* Waiting thread handle. */
  1234. HANDLE thread;
  1235. } WaitForAllParam;
  1236. /* Waiting thread routine. */
  1237. static unsigned __stdcall
  1238. _in_waiter_thread(void* arg)
  1239. {
  1240. HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
  1241. int res;
  1242. WaitForAllParam* const param = (WaitForAllParam*)arg;
  1243. /* We have to wait on the main_event in order to be notified when any of the
  1244. * sibling threads is exiting. */
  1245. wait_on[0] = param->main_event;
  1246. /* The rest of the handles go behind the main event handle. */
  1247. memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
  1248. res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
  1249. if (res > 0 && res < (param->handles_count + 1)) {
  1250. /* One of the original handles got signaled. Save its absolute index into
  1251. * the output variable. */
  1252. InterlockedCompareExchange(param->signaled_index,
  1253. res - 1L + param->first_handle_index, -1L);
  1254. }
  1255. /* Notify the caller (and the siblings) that the wait is over. */
  1256. SetEvent(param->main_event);
  1257. _endthreadex(0);
  1258. return 0;
  1259. }
  1260. /* WaitForMultipeObjects fixer routine.
  1261. * Param:
  1262. * handles Array of handles to wait on.
  1263. * handles_count Number of handles in the array.
  1264. * Return:
  1265. * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
  1266. * WAIT_FAILED on an error.
  1267. */
  1268. static int
  1269. _wait_for_all(HANDLE* handles, int handles_count)
  1270. {
  1271. WaitForAllParam* threads;
  1272. HANDLE main_event;
  1273. int chunks, chunk, remains;
  1274. /* This variable is going to be accessed by several threads at the same time,
  1275. * this is bound to fail randomly when the core is run on multi-core machines.
  1276. * To solve this, we need to do the following (1 _and_ 2):
  1277. * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
  1278. * out the reads/writes in this function unexpectedly.
  1279. * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
  1280. * all accesses inside a critical section. But we can also use
  1281. * InterlockedCompareExchange() which always provide a full memory barrier
  1282. * on Win32.
  1283. */
  1284. volatile LONG sig_index = -1;
  1285. /* Calculate number of chunks, and allocate thread param array. */
  1286. chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
  1287. remains = handles_count % WAIT_ALL_CHUNK_SIZE;
  1288. threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
  1289. sizeof(WaitForAllParam));
  1290. if (threads == NULL) {
  1291. D("Unable to allocate thread array for %d handles.", handles_count);
  1292. return (int)WAIT_FAILED;
  1293. }
  1294. /* Create main event to wait on for all waiting threads. This is a "manualy
  1295. * reset" event that will remain set once it was set. */
  1296. main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
  1297. if (main_event == NULL) {
  1298. D("Unable to create main event. Error: %d", (int)GetLastError());
  1299. free(threads);
  1300. return (int)WAIT_FAILED;
  1301. }
  1302. /*
  1303. * Initialize waiting thread parameters.
  1304. */
  1305. for (chunk = 0; chunk < chunks; chunk++) {
  1306. threads[chunk].main_event = main_event;
  1307. threads[chunk].signaled_index = &sig_index;
  1308. threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
  1309. threads[chunk].handles = handles + threads[chunk].first_handle_index;
  1310. threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
  1311. }
  1312. if (remains) {
  1313. threads[chunk].main_event = main_event;
  1314. threads[chunk].signaled_index = &sig_index;
  1315. threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
  1316. threads[chunk].handles = handles + threads[chunk].first_handle_index;
  1317. threads[chunk].handles_count = remains;
  1318. chunks++;
  1319. }
  1320. /* Start the waiting threads. */
  1321. for (chunk = 0; chunk < chunks; chunk++) {
  1322. /* Note that using adb_thread_create is not appropriate here, since we
  1323. * need a handle to wait on for thread termination. */
  1324. threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
  1325. &threads[chunk], 0, NULL);
  1326. if (threads[chunk].thread == NULL) {
  1327. /* Unable to create a waiter thread. Collapse. */
  1328. D("Unable to create a waiting thread %d of %d. errno=%d",
  1329. chunk, chunks, errno);
  1330. chunks = chunk;
  1331. SetEvent(main_event);
  1332. break;
  1333. }
  1334. }
  1335. /* Wait on any of the threads to get signaled. */
  1336. WaitForSingleObject(main_event, INFINITE);
  1337. /* Wait on all the waiting threads to exit. */
  1338. for (chunk = 0; chunk < chunks; chunk++) {
  1339. WaitForSingleObject(threads[chunk].thread, INFINITE);
  1340. CloseHandle(threads[chunk].thread);
  1341. }
  1342. CloseHandle(main_event);
  1343. free(threads);
  1344. const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
  1345. return (ret >= 0) ? ret : (int)WAIT_FAILED;
  1346. }
  1347. static EventLooperRec win32_looper;
  1348. static void fdevent_init(void)
  1349. {
  1350. win32_looper.htab_count = 0;
  1351. win32_looper.hooks = NULL;
  1352. }
  1353. static void fdevent_connect(fdevent *fde)
  1354. {
  1355. EventLooper looper = &win32_looper;
  1356. int events = fde->state & FDE_EVENTMASK;
  1357. if (events != 0)
  1358. event_looper_hook( looper, fde->fd, events );
  1359. }
  1360. static void fdevent_disconnect(fdevent *fde)
  1361. {
  1362. EventLooper looper = &win32_looper;
  1363. int events = fde->state & FDE_EVENTMASK;
  1364. if (events != 0)
  1365. event_looper_unhook( looper, fde->fd, events );
  1366. }
  1367. static void fdevent_update(fdevent *fde, unsigned events)
  1368. {
  1369. EventLooper looper = &win32_looper;
  1370. unsigned events0 = fde->state & FDE_EVENTMASK;
  1371. if (events != events0) {
  1372. int removes = events0 & ~events;
  1373. int adds = events & ~events0;
  1374. if (removes) {
  1375. D("fdevent_update: remove %x from %d\n", removes, fde->fd);
  1376. event_looper_unhook( looper, fde->fd, removes );
  1377. }
  1378. if (adds) {
  1379. D("fdevent_update: add %x to %d\n", adds, fde->fd);
  1380. event_looper_hook ( looper, fde->fd, adds );
  1381. }
  1382. }
  1383. }
  1384. static void fdevent_process()
  1385. {
  1386. EventLooper looper = &win32_looper;
  1387. EventHook hook;
  1388. int gotone = 0;
  1389. /* if we have at least one ready hook, execute it/them */
  1390. for (hook = looper->hooks; hook; hook = hook->next) {
  1391. hook->ready = 0;
  1392. if (hook->prepare) {
  1393. hook->prepare(hook);
  1394. if (hook->ready != 0) {
  1395. event_hook_signal( hook );
  1396. gotone = 1;
  1397. }
  1398. }
  1399. }
  1400. /* nothing's ready yet, so wait for something to happen */
  1401. if (!gotone)
  1402. {
  1403. looper->htab_count = 0;
  1404. for (hook = looper->hooks; hook; hook = hook->next)
  1405. {
  1406. if (hook->start && !hook->start(hook)) {
  1407. D( "fdevent_process: error when starting a hook\n" );
  1408. return;
  1409. }
  1410. if (hook->h != INVALID_HANDLE_VALUE) {
  1411. int nn;
  1412. for (nn = 0; nn < looper->htab_count; nn++)
  1413. {
  1414. if ( looper->htab[nn] == hook->h )
  1415. goto DontAdd;
  1416. }
  1417. looper->htab[ looper->htab_count++ ] = hook->h;
  1418. DontAdd:
  1419. ;
  1420. }
  1421. }
  1422. if (looper->htab_count == 0) {
  1423. D( "fdevent_process: nothing to wait for !!\n" );
  1424. return;
  1425. }
  1426. do
  1427. {
  1428. int wait_ret;
  1429. D( "adb_win32: waiting for %d events\n", looper->htab_count );
  1430. if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
  1431. D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
  1432. wait_ret = _wait_for_all(looper->htab, looper->htab_count);
  1433. } else {
  1434. wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
  1435. }
  1436. if (wait_ret == (int)WAIT_FAILED) {
  1437. D( "adb_win32: wait failed, error %ld\n", GetLastError() );
  1438. } else {
  1439. D( "adb_win32: got one (index %d)\n", wait_ret );
  1440. /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
  1441. * like mouse movements. we need to filter these with the "check" function
  1442. */
  1443. if ((unsigned)wait_ret < (unsigned)looper->htab_count)
  1444. {
  1445. for (hook = looper->hooks; hook; hook = hook->next)
  1446. {
  1447. if ( looper->htab[wait_ret] == hook->h &&
  1448. (!hook->check || hook->check(hook)) )
  1449. {
  1450. D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
  1451. event_hook_signal( hook );
  1452. gotone = 1;
  1453. break;
  1454. }
  1455. }
  1456. }
  1457. }
  1458. }
  1459. while (!gotone);
  1460. for (hook = looper->hooks; hook; hook = hook->next) {
  1461. if (hook->stop)
  1462. hook->stop( hook );
  1463. }
  1464. }
  1465. for (hook = looper->hooks; hook; hook = hook->next) {
  1466. if (hook->peek && hook->peek(hook))
  1467. event_hook_signal( hook );
  1468. }
  1469. }
  1470. static void fdevent_register(fdevent *fde)
  1471. {
  1472. int fd = fde->fd - WIN32_FH_BASE;
  1473. if(fd < 0) {
  1474. FATAL("bogus negative fd (%d)\n", fde->fd);
  1475. }
  1476. if(fd >= fd_table_max) {
  1477. int oldmax = fd_table_max;
  1478. if(fde->fd > 32000) {
  1479. FATAL("bogus huuuuge fd (%d)\n", fde->fd);
  1480. }
  1481. if(fd_table_max == 0) {
  1482. fdevent_init();
  1483. fd_table_max = 256;
  1484. }
  1485. while(fd_table_max <= fd) {
  1486. fd_table_max *= 2;
  1487. }
  1488. fd_table = realloc(fd_table, sizeof(fdevent*) * fd_table_max);
  1489. if(fd_table == 0) {
  1490. FATAL("could not expand fd_table to %d entries\n", fd_table_max);
  1491. }
  1492. memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
  1493. }
  1494. fd_table[fd] = fde;
  1495. }
  1496. static void fdevent_unregister(fdevent *fde)
  1497. {
  1498. int fd = fde->fd - WIN32_FH_BASE;
  1499. if((fd < 0) || (fd >= fd_table_max)) {
  1500. FATAL("fd out of range (%d)\n", fde->fd);
  1501. }
  1502. if(fd_table[fd] != fde) {
  1503. FATAL("fd_table out of sync");
  1504. }
  1505. fd_table[fd] = 0;
  1506. if(!(fde->state & FDE_DONT_CLOSE)) {
  1507. dump_fde(fde, "close");
  1508. adb_close(fde->fd);
  1509. }
  1510. }
  1511. static void fdevent_plist_enqueue(fdevent *node)
  1512. {
  1513. fdevent *list = &list_pending;
  1514. node->next = list;
  1515. node->prev = list->prev;
  1516. node->prev->next = node;
  1517. list->prev = node;
  1518. }
  1519. static void fdevent_plist_remove(fdevent *node)
  1520. {
  1521. node->prev->next = node->next;
  1522. node->next->prev = node->prev;
  1523. node->next = 0;
  1524. node->prev = 0;
  1525. }
  1526. static fdevent *fdevent_plist_dequeue(void)
  1527. {
  1528. fdevent *list = &list_pending;
  1529. fdevent *node = list->next;
  1530. if(node == list) return 0;
  1531. list->next = node->next;
  1532. list->next->prev = list;
  1533. node->next = 0;
  1534. node->prev = 0;
  1535. return node;
  1536. }
  1537. fdevent *fdevent_create(int fd, fd_func func, void *arg)
  1538. {
  1539. fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
  1540. if(fde == 0) return 0;
  1541. fdevent_install(fde, fd, func, arg);
  1542. fde->state |= FDE_CREATED;
  1543. return fde;
  1544. }
  1545. void fdevent_destroy(fdevent *fde)
  1546. {
  1547. if(fde == 0) return;
  1548. if(!(fde->state & FDE_CREATED)) {
  1549. FATAL("fde %p not created by fdevent_create()\n", fde);
  1550. }
  1551. fdevent_remove(fde);
  1552. }
  1553. void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
  1554. {
  1555. memset(fde, 0, sizeof(fdevent));
  1556. fde->state = FDE_ACTIVE;
  1557. fde->fd = fd;
  1558. fde->func = func;
  1559. fde->arg = arg;
  1560. fdevent_register(fde);
  1561. dump_fde(fde, "connect");
  1562. fdevent_connect(fde);
  1563. fde->state |= FDE_ACTIVE;
  1564. }
  1565. void fdevent_remove(fdevent *fde)
  1566. {
  1567. if(fde->state & FDE_PENDING) {
  1568. fdevent_plist_remove(fde);
  1569. }
  1570. if(fde->state & FDE_ACTIVE) {
  1571. fdevent_disconnect(fde);
  1572. dump_fde(fde, "disconnect");
  1573. fdevent_unregister(fde);
  1574. }
  1575. fde->state = 0;
  1576. fde->events = 0;
  1577. }
  1578. void fdevent_set(fdevent *fde, unsigned events)
  1579. {
  1580. events &= FDE_EVENTMASK;
  1581. if((fde->state & FDE_EVENTMASK) == (int)events) return;
  1582. if(fde->state & FDE_ACTIVE) {
  1583. fdevent_update(fde, events);
  1584. dump_fde(fde, "update");
  1585. }
  1586. fde->state = (fde->state & FDE_STATEMASK) | events;
  1587. if(fde->state & FDE_PENDING) {
  1588. /* if we're pending, make sure
  1589. ** we don't signal an event that
  1590. ** is no longer wanted.
  1591. */
  1592. fde->events &= (~events);
  1593. if(fde->events == 0) {
  1594. fdevent_plist_remove(fde);
  1595. fde->state &= (~FDE_PENDING);
  1596. }
  1597. }
  1598. }
  1599. void fdevent_add(fdevent *fde, unsigned events)
  1600. {
  1601. fdevent_set(
  1602. fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
  1603. }
  1604. void fdevent_del(fdevent *fde, unsigned events)
  1605. {
  1606. fdevent_set(
  1607. fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
  1608. }
  1609. void fdevent_loop()
  1610. {
  1611. fdevent *fde;
  1612. for(;;) {
  1613. #if DEBUG
  1614. fprintf(stderr,"--- ---- waiting for events\n");
  1615. #endif
  1616. fdevent_process();
  1617. while((fde = fdevent_plist_dequeue())) {
  1618. unsigned events = fde->events;
  1619. fde->events = 0;
  1620. fde->state &= (~FDE_PENDING);
  1621. dump_fde(fde, "callback");
  1622. fde->func(fde->fd, events, fde->arg);
  1623. }
  1624. }
  1625. }
  1626. /** FILE EVENT HOOKS
  1627. **/
  1628. static void _event_file_prepare( EventHook hook )
  1629. {
  1630. if (hook->wanted & (FDE_READ|FDE_WRITE)) {
  1631. /* we can always read/write */
  1632. hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
  1633. }
  1634. }
  1635. static int _event_file_peek( EventHook hook )
  1636. {
  1637. return (hook->wanted & (FDE_READ|FDE_WRITE));
  1638. }
  1639. static void _fh_file_hook( FH f, int events, EventHook hook )
  1640. {
  1641. hook->h = f->fh_handle;
  1642. hook->prepare = _event_file_prepare;
  1643. hook->peek = _event_file_peek;
  1644. }
  1645. /** SOCKET EVENT HOOKS
  1646. **/
  1647. static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
  1648. {
  1649. if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
  1650. if (hook->wanted & FDE_READ)
  1651. hook->ready |= FDE_READ;
  1652. if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
  1653. hook->ready |= FDE_ERROR;
  1654. }
  1655. if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
  1656. if (hook->wanted & FDE_WRITE)
  1657. hook->ready |= FDE_WRITE;
  1658. if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
  1659. hook->ready |= FDE_ERROR;
  1660. }
  1661. if ( evts->lNetworkEvents & FD_OOB ) {
  1662. if (hook->wanted & FDE_ERROR)
  1663. hook->ready |= FDE_ERROR;
  1664. }
  1665. }
  1666. static void _event_socket_prepare( EventHook hook )
  1667. {
  1668. WSANETWORKEVENTS evts;
  1669. /* look if some of the events we want already happened ? */
  1670. if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
  1671. _event_socket_verify( hook, &evts );
  1672. }
  1673. static int _socket_wanted_to_flags( int wanted )
  1674. {
  1675. int flags = 0;
  1676. if (wanted & FDE_READ)
  1677. flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
  1678. if (wanted & FDE_WRITE)
  1679. flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
  1680. if (wanted & FDE_ERROR)
  1681. flags |= FD_OOB;
  1682. return flags;
  1683. }
  1684. static int _event_socket_start( EventHook hook )
  1685. {
  1686. /* create an event which we're going to wait for */
  1687. FH fh = hook->fh;
  1688. long flags = _socket_wanted_to_flags( hook->wanted );
  1689. hook->h = fh->event;
  1690. if (hook->h == INVALID_HANDLE_VALUE) {
  1691. D( "_event_socket_start: no event for %s\n", fh->name );
  1692. return 0;
  1693. }
  1694. if ( flags != fh->mask ) {
  1695. D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
  1696. if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
  1697. D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
  1698. CloseHandle( hook->h );
  1699. hook->h = INVALID_HANDLE_VALUE;
  1700. exit(1);
  1701. return 0;
  1702. }
  1703. fh->mask = flags;
  1704. }
  1705. return 1;
  1706. }
  1707. static void _event_socket_stop( EventHook hook )
  1708. {
  1709. hook->h = INVALID_HANDLE_VALUE;
  1710. }
  1711. static int _event_socket_check( EventHook hook )
  1712. {
  1713. int result = 0;
  1714. FH fh = hook->fh;
  1715. WSANETWORKEVENTS evts;
  1716. if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
  1717. _event_socket_verify( hook, &evts );
  1718. result = (hook->ready != 0);
  1719. if (result) {
  1720. ResetEvent( hook->h );
  1721. }
  1722. }
  1723. D( "_event_socket_check %s returns %d\n", fh->name, result );
  1724. return result;
  1725. }
  1726. static int _event_socket_peek( EventHook hook )
  1727. {
  1728. WSANETWORKEVENTS evts;
  1729. FH fh = hook->fh;
  1730. /* look if some of the events we want already happened ? */
  1731. if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
  1732. _event_socket_verify( hook, &evts );
  1733. if (hook->ready)
  1734. ResetEvent( hook->h );
  1735. }
  1736. return hook->ready != 0;
  1737. }
  1738. static void _fh_socket_hook( FH f, int events, EventHook hook )
  1739. {
  1740. hook->prepare = _event_socket_prepare;
  1741. hook->start = _event_socket_start;
  1742. hook->stop = _event_socket_stop;
  1743. hook->check = _event_socket_check;
  1744. hook->peek = _event_socket_peek;
  1745. _event_socket_start( hook );
  1746. }
  1747. /** SOCKETPAIR EVENT HOOKS
  1748. **/
  1749. static void _event_socketpair_prepare( EventHook hook )
  1750. {
  1751. FH fh = hook->fh;
  1752. SocketPair pair = fh->fh_pair;
  1753. BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
  1754. BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
  1755. if (hook->wanted & FDE_READ && rbip->can_read)
  1756. hook->ready |= FDE_READ;
  1757. if (hook->wanted & FDE_WRITE && wbip->can_write)
  1758. hook->ready |= FDE_WRITE;
  1759. }
  1760. static int _event_socketpair_start( EventHook hook )
  1761. {
  1762. FH fh = hook->fh;
  1763. SocketPair pair = fh->fh_pair;
  1764. BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
  1765. BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
  1766. if (hook->wanted == FDE_READ)
  1767. hook->h = rbip->evt_read;
  1768. else if (hook->wanted == FDE_WRITE)
  1769. hook->h = wbip->evt_write;
  1770. else {
  1771. D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
  1772. return 0;
  1773. }
  1774. D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
  1775. hook->fh->name, _fh_to_int(fh), hook->wanted);
  1776. return 1;
  1777. }
  1778. static int _event_socketpair_peek( EventHook hook )
  1779. {
  1780. _event_socketpair_prepare( hook );
  1781. return hook->ready != 0;
  1782. }
  1783. static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
  1784. {
  1785. hook->prepare = _event_socketpair_prepare;
  1786. hook->start = _event_socketpair_start;
  1787. hook->peek = _event_socketpair_peek;
  1788. }
  1789. void
  1790. adb_sysdeps_init( void )
  1791. {
  1792. #define ADB_MUTEX(x) InitializeCriticalSection( & x );
  1793. #include "mutex_list.h"
  1794. InitializeCriticalSection( &_win32_lock );
  1795. }
  1796. /* Windows doesn't have strtok_r. Use the one from bionic. */
  1797. /*
  1798. * Copyright (c) 1988 Regents of the University of California.
  1799. * All rights reserved.
  1800. *
  1801. * Redistribution and use in source and binary forms, with or without
  1802. * modification, are permitted provided that the following conditions
  1803. * are met:
  1804. * 1. Redistributions of source code must retain the above copyright
  1805. * notice, this list of conditions and the following disclaimer.
  1806. * 2. Redistributions in binary form must reproduce the above copyright
  1807. * notice, this list of conditions and the following disclaimer in the
  1808. * documentation and/or other materials provided with the distribution.
  1809. * 3. Neither the name of the University nor the names of its contributors
  1810. * may be used to endorse or promote products derived from this software
  1811. * without specific prior written permission.
  1812. *
  1813. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  1814. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  1815. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  1816. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  1817. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  1818. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  1819. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  1820. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  1821. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  1822. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  1823. * SUCH DAMAGE.
  1824. */
  1825. char *
  1826. adb_strtok_r(char *s, const char *delim, char **last)
  1827. {
  1828. char *spanp;
  1829. int c, sc;
  1830. char *tok;
  1831. if (s == NULL && (s = *last) == NULL)
  1832. return (NULL);
  1833. /*
  1834. * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
  1835. */
  1836. cont:
  1837. c = *s++;
  1838. for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
  1839. if (c == sc)
  1840. goto cont;
  1841. }
  1842. if (c == 0) { /* no non-delimiter characters */
  1843. *last = NULL;
  1844. return (NULL);
  1845. }
  1846. tok = s - 1;
  1847. /*
  1848. * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
  1849. * Note that delim must have one NUL; we stop if we see that, too.
  1850. */
  1851. for (;;) {
  1852. c = *s++;
  1853. spanp = (char *)delim;
  1854. do {
  1855. if ((sc = *spanp++) == c) {
  1856. if (c == 0)
  1857. s = NULL;
  1858. else
  1859. s[-1] = 0;
  1860. *last = s;
  1861. return (tok);
  1862. }
  1863. } while (sc != 0);
  1864. }
  1865. /* NOTREACHED */
  1866. }
  1867. /**************************************************************************/
  1868. /**************************************************************************/
  1869. /***** *****/
  1870. /***** Console Window Terminal Emulation *****/
  1871. /***** *****/
  1872. /**************************************************************************/
  1873. /**************************************************************************/
  1874. // This reads input from a Win32 console window and translates it into Unix
  1875. // terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
  1876. // mode, not Application mode), which itself emulates xterm. Gnome Terminal
  1877. // is emulated instead of xterm because it is probably more popular than xterm:
  1878. // Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
  1879. // supports modern fonts, etc. It seems best to emulate the terminal that most
  1880. // Android developers use because they'll fix apps (the shell, etc.) to keep
  1881. // working with that terminal's emulation.
  1882. //
  1883. // The point of this emulation is not to be perfect or to solve all issues with
  1884. // console windows on Windows, but to be better than the original code which
  1885. // just called read() (which called ReadFile(), which called ReadConsoleA())
  1886. // which did not support Ctrl-C, tab completion, shell input line editing
  1887. // keys, server echo, and more.
  1888. //
  1889. // This implementation reconfigures the console with SetConsoleMode(), then
  1890. // calls ReadConsoleInput() to get raw input which it remaps to Unix
  1891. // terminal-style sequences which is returned via unix_read() which is used
  1892. // by the 'adb shell' command.
  1893. //
  1894. // Code organization:
  1895. //
  1896. // * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
  1897. // * unix_read() detects console windows (as opposed to pipes, files, etc.).
  1898. // * _console_read() is the main code of the emulation.
  1899. // Read an input record from the console; one that should be processed.
  1900. static bool _get_interesting_input_record_uncached(const HANDLE console,
  1901. INPUT_RECORD* const input_record) {
  1902. for (;;) {
  1903. DWORD read_count = 0;
  1904. memset(input_record, 0, sizeof(*input_record));
  1905. if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
  1906. D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
  1907. "failure, error %ld\n", GetLastError());
  1908. errno = EIO;
  1909. return false;
  1910. }
  1911. if (read_count == 0) { // should be impossible
  1912. fatal("ReadConsoleInputA returned 0");
  1913. }
  1914. if (read_count != 1) { // should be impossible
  1915. fatal("ReadConsoleInputA did not return one input record");
  1916. }
  1917. if ((input_record->EventType == KEY_EVENT) &&
  1918. (input_record->Event.KeyEvent.bKeyDown)) {
  1919. if (input_record->Event.KeyEvent.wRepeatCount == 0) {
  1920. fatal("ReadConsoleInputA returned a key event with zero repeat"
  1921. " count");
  1922. }
  1923. // Got an interesting INPUT_RECORD, so return
  1924. return true;
  1925. }
  1926. }
  1927. }
  1928. // Cached input record (in case _console_read() is passed a buffer that doesn't
  1929. // have enough space to fit wRepeatCount number of key sequences). A non-zero
  1930. // wRepeatCount indicates that a record is cached.
  1931. static INPUT_RECORD _win32_input_record;
  1932. // Get the next KEY_EVENT_RECORD that should be processed.
  1933. static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
  1934. // If nothing cached, read directly from the console until we get an
  1935. // interesting record.
  1936. if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
  1937. if (!_get_interesting_input_record_uncached(console,
  1938. &_win32_input_record)) {
  1939. // There was an error, so make sure wRepeatCount is zero because
  1940. // that signifies no cached input record.
  1941. _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
  1942. return NULL;
  1943. }
  1944. }
  1945. return &_win32_input_record.Event.KeyEvent;
  1946. }
  1947. static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
  1948. return (control_key_state & SHIFT_PRESSED) != 0;
  1949. }
  1950. static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
  1951. return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
  1952. }
  1953. static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
  1954. return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
  1955. }
  1956. static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
  1957. return (control_key_state & NUMLOCK_ON) != 0;
  1958. }
  1959. static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
  1960. return (control_key_state & CAPSLOCK_ON) != 0;
  1961. }
  1962. static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
  1963. return (control_key_state & ENHANCED_KEY) != 0;
  1964. }
  1965. // Constants from MSDN for ToAscii().
  1966. static const BYTE TOASCII_KEY_OFF = 0x00;
  1967. static const BYTE TOASCII_KEY_DOWN = 0x80;
  1968. static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
  1969. // Given a key event, ignore a modifier key and return the character that was
  1970. // entered without the modifier. Writes to *ch and returns the number of bytes
  1971. // written.
  1972. static size_t _get_char_ignoring_modifier(char* const ch,
  1973. const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
  1974. const WORD modifier) {
  1975. // If there is no character from Windows, try ignoring the specified
  1976. // modifier and look for a character. Note that if AltGr is being used,
  1977. // there will be a character from Windows.
  1978. if (key_event->uChar.AsciiChar == '\0') {
  1979. // Note that we read the control key state from the passed in argument
  1980. // instead of from key_event since the argument has been normalized.
  1981. if (((modifier == VK_SHIFT) &&
  1982. _is_shift_pressed(control_key_state)) ||
  1983. ((modifier == VK_CONTROL) &&
  1984. _is_ctrl_pressed(control_key_state)) ||
  1985. ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
  1986. BYTE key_state[256] = {0};
  1987. key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
  1988. TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
  1989. key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
  1990. TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
  1991. key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
  1992. TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
  1993. key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
  1994. TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
  1995. // cause this modifier to be ignored
  1996. key_state[modifier] = TOASCII_KEY_OFF;
  1997. WORD translated = 0;
  1998. if (ToAscii(key_event->wVirtualKeyCode,
  1999. key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
  2000. // Ignoring the modifier, we found a character.
  2001. *ch = (CHAR)translated;
  2002. return 1;
  2003. }
  2004. }
  2005. }
  2006. // Just use whatever Windows told us originally.
  2007. *ch = key_event->uChar.AsciiChar;
  2008. // If the character from Windows is NULL, return a size of zero.
  2009. return (*ch == '\0') ? 0 : 1;
  2010. }
  2011. // If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
  2012. // but taking into account the shift key. This is because for a sequence like
  2013. // Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
  2014. // we want to find the character ')'.
  2015. //
  2016. // Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
  2017. // because it is the default key-sequence to switch the input language.
  2018. // This is configurable in the Region and Language control panel.
  2019. static __inline__ size_t _get_non_control_char(char* const ch,
  2020. const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
  2021. return _get_char_ignoring_modifier(ch, key_event, control_key_state,
  2022. VK_CONTROL);
  2023. }
  2024. // Get without Alt.
  2025. static __inline__ size_t _get_non_alt_char(char* const ch,
  2026. const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
  2027. return _get_char_ignoring_modifier(ch, key_event, control_key_state,
  2028. VK_MENU);
  2029. }
  2030. // Ignore the control key, find the character from Windows, and apply any
  2031. // Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
  2032. // *pch and returns number of bytes written.
  2033. static size_t _get_control_character(char* const pch,
  2034. const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
  2035. const size_t len = _get_non_control_char(pch, key_event,
  2036. control_key_state);
  2037. if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
  2038. char ch = *pch;
  2039. switch (ch) {
  2040. case '2':
  2041. case '@':
  2042. case '`':
  2043. ch = '\0';
  2044. break;
  2045. case '3':
  2046. case '[':
  2047. case '{':
  2048. ch = '\x1b';
  2049. break;
  2050. case '4':
  2051. case '\\':
  2052. case '|':
  2053. ch = '\x1c';
  2054. break;
  2055. case '5':
  2056. case ']':
  2057. case '}':
  2058. ch = '\x1d';
  2059. break;
  2060. case '6':
  2061. case '^':
  2062. case '~':
  2063. ch = '\x1e';
  2064. break;
  2065. case '7':
  2066. case '-':
  2067. case '_':
  2068. ch = '\x1f';
  2069. break;
  2070. case '8':
  2071. ch = '\x7f';
  2072. break;
  2073. case '/':
  2074. if (!_is_alt_pressed(control_key_state)) {
  2075. ch = '\x1f';
  2076. }
  2077. break;
  2078. case '?':
  2079. if (!_is_alt_pressed(control_key_state)) {
  2080. ch = '\x7f';
  2081. }
  2082. break;
  2083. }
  2084. *pch = ch;
  2085. }
  2086. return len;
  2087. }
  2088. static DWORD _normalize_altgr_control_key_state(
  2089. const KEY_EVENT_RECORD* const key_event) {
  2090. DWORD control_key_state = key_event->dwControlKeyState;
  2091. // If we're in an AltGr situation where the AltGr key is down (depending on
  2092. // the keyboard layout, that might be the physical right alt key which
  2093. // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
  2094. // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
  2095. // a character (which indicates that there was an AltGr mapping), then act
  2096. // as if alt and control are not really down for the purposes of modifiers.
  2097. // This makes it so that if the user with, say, a German keyboard layout
  2098. // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
  2099. // output the key and we don't see the Alt and Ctrl keys.
  2100. if (_is_ctrl_pressed(control_key_state) &&
  2101. _is_alt_pressed(control_key_state)
  2102. && (key_event->uChar.AsciiChar != '\0')) {
  2103. // Try to remove as few bits as possible to improve our chances of
  2104. // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
  2105. // Left-Alt + Right-Ctrl + AltGr.
  2106. if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
  2107. // Remove Right-Alt.
  2108. control_key_state &= ~RIGHT_ALT_PRESSED;
  2109. // If uChar is set, a Ctrl key is pressed, and Right-Alt is
  2110. // pressed, Left-Ctrl is almost always set, except if the user
  2111. // presses Right-Ctrl, then AltGr (in that specific order) for
  2112. // whatever reason. At any rate, make sure the bit is not set.
  2113. control_key_state &= ~LEFT_CTRL_PRESSED;
  2114. } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
  2115. // Remove Left-Alt.
  2116. control_key_state &= ~LEFT_ALT_PRESSED;
  2117. // Whichever Ctrl key is down, remove it from the state. We only
  2118. // remove one key, to improve our chances of detecting the
  2119. // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
  2120. if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
  2121. // Remove Left-Ctrl.
  2122. control_key_state &= ~LEFT_CTRL_PRESSED;
  2123. } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
  2124. // Remove Right-Ctrl.
  2125. control_key_state &= ~RIGHT_CTRL_PRESSED;
  2126. }
  2127. }
  2128. // Note that this logic isn't 100% perfect because Windows doesn't
  2129. // allow us to detect all combinations because a physical AltGr key
  2130. // press shows up as two bits, plus some combinations are ambiguous
  2131. // about what is actually physically pressed.
  2132. }
  2133. return control_key_state;
  2134. }
  2135. // If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
  2136. // dwControlKeyState for the following keypad keys: period, 0-9. If we detect
  2137. // this scenario, set the SHIFT_PRESSED bit so we can add modifiers
  2138. // appropriately.
  2139. static DWORD _normalize_keypad_control_key_state(const WORD vk,
  2140. const DWORD control_key_state) {
  2141. if (!_is_numlock_on(control_key_state)) {
  2142. return control_key_state;
  2143. }
  2144. if (!_is_enhanced_key(control_key_state)) {
  2145. switch (vk) {
  2146. case VK_INSERT: // 0
  2147. case VK_DELETE: // .
  2148. case VK_END: // 1
  2149. case VK_DOWN: // 2
  2150. case VK_NEXT: // 3
  2151. case VK_LEFT: // 4
  2152. case VK_CLEAR: // 5
  2153. case VK_RIGHT: // 6
  2154. case VK_HOME: // 7
  2155. case VK_UP: // 8
  2156. case VK_PRIOR: // 9
  2157. return control_key_state | SHIFT_PRESSED;
  2158. }
  2159. }
  2160. return control_key_state;
  2161. }
  2162. static const char* _get_keypad_sequence(const DWORD control_key_state,
  2163. const char* const normal, const char* const shifted) {
  2164. if (_is_shift_pressed(control_key_state)) {
  2165. // Shift is pressed and NumLock is off
  2166. return shifted;
  2167. } else {
  2168. // Shift is not pressed and NumLock is off, or,
  2169. // Shift is pressed and NumLock is on, in which case we want the
  2170. // NumLock and Shift to neutralize each other, thus, we want the normal
  2171. // sequence.
  2172. return normal;
  2173. }
  2174. // If Shift is not pressed and NumLock is on, a different virtual key code
  2175. // is returned by Windows, which can be taken care of by a different case
  2176. // statement in _console_read().
  2177. }
  2178. // Write sequence to buf and return the number of bytes written.
  2179. static size_t _get_modifier_sequence(char* const buf, const WORD vk,
  2180. DWORD control_key_state, const char* const normal) {
  2181. // Copy the base sequence into buf.
  2182. const size_t len = strlen(normal);
  2183. memcpy(buf, normal, len);
  2184. int code = 0;
  2185. control_key_state = _normalize_keypad_control_key_state(vk,
  2186. control_key_state);
  2187. if (_is_shift_pressed(control_key_state)) {
  2188. code |= 0x1;
  2189. }
  2190. if (_is_alt_pressed(control_key_state)) { // any alt key pressed
  2191. code |= 0x2;
  2192. }
  2193. if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
  2194. code |= 0x4;
  2195. }
  2196. // If some modifier was held down, then we need to insert the modifier code
  2197. if (code != 0) {
  2198. if (len == 0) {
  2199. // Should be impossible because caller should pass a string of
  2200. // non-zero length.
  2201. return 0;
  2202. }
  2203. size_t index = len - 1;
  2204. const char lastChar = buf[index];
  2205. if (lastChar != '~') {
  2206. buf[index++] = '1';
  2207. }
  2208. buf[index++] = ';'; // modifier separator
  2209. // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
  2210. // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
  2211. buf[index++] = '1' + code;
  2212. buf[index++] = lastChar; // move ~ (or other last char) to the end
  2213. return index;
  2214. }
  2215. return len;
  2216. }
  2217. // Write sequence to buf and return the number of bytes written.
  2218. static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
  2219. const DWORD control_key_state, const char* const normal,
  2220. const char shifted) {
  2221. if (_is_shift_pressed(control_key_state)) {
  2222. // Shift is pressed and NumLock is off
  2223. if (shifted != '\0') {
  2224. buf[0] = shifted;
  2225. return sizeof(buf[0]);
  2226. } else {
  2227. return 0;
  2228. }
  2229. } else {
  2230. // Shift is not pressed and NumLock is off, or,
  2231. // Shift is pressed and NumLock is on, in which case we want the
  2232. // NumLock and Shift to neutralize each other, thus, we want the normal
  2233. // sequence.
  2234. return _get_modifier_sequence(buf, vk, control_key_state, normal);
  2235. }
  2236. // If Shift is not pressed and NumLock is on, a different virtual key code
  2237. // is returned by Windows, which can be taken care of by a different case
  2238. // statement in _console_read().
  2239. }
  2240. // The decimal key on the keypad produces a '.' for U.S. English and a ',' for
  2241. // Standard German. Figure this out at runtime so we know what to output for
  2242. // Shift-VK_DELETE.
  2243. static char _get_decimal_char() {
  2244. return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
  2245. }
  2246. // Prefix the len bytes in buf with the escape character, and then return the
  2247. // new buffer length.
  2248. size_t _escape_prefix(char* const buf, const size_t len) {
  2249. // If nothing to prefix, don't do anything. We might be called with
  2250. // len == 0, if alt was held down with a dead key which produced nothing.
  2251. if (len == 0) {
  2252. return 0;
  2253. }
  2254. memmove(&buf[1], buf, len);
  2255. buf[0] = '\x1b';
  2256. return len + 1;
  2257. }
  2258. // Writes to buffer buf (of length len), returning number of bytes written or
  2259. // -1 on error. Never returns zero because Win32 consoles are never 'closed'
  2260. // (as far as I can tell).
  2261. static int _console_read(const HANDLE console, void* buf, size_t len) {
  2262. for (;;) {
  2263. KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
  2264. if (key_event == NULL) {
  2265. return -1;
  2266. }
  2267. const WORD vk = key_event->wVirtualKeyCode;
  2268. const CHAR ch = key_event->uChar.AsciiChar;
  2269. const DWORD control_key_state = _normalize_altgr_control_key_state(
  2270. key_event);
  2271. // The following emulation code should write the output sequence to
  2272. // either seqstr or to seqbuf and seqbuflen.
  2273. const char* seqstr = NULL; // NULL terminated C-string
  2274. // Enough space for max sequence string below, plus modifiers and/or
  2275. // escape prefix.
  2276. char seqbuf[16];
  2277. size_t seqbuflen = 0; // Space used in seqbuf.
  2278. #define MATCH(vk, normal) \
  2279. case (vk): \
  2280. { \
  2281. seqstr = (normal); \
  2282. } \
  2283. break;
  2284. // Modifier keys should affect the output sequence.
  2285. #define MATCH_MODIFIER(vk, normal) \
  2286. case (vk): \
  2287. { \
  2288. seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
  2289. control_key_state, (normal)); \
  2290. } \
  2291. break;
  2292. // The shift key should affect the output sequence.
  2293. #define MATCH_KEYPAD(vk, normal, shifted) \
  2294. case (vk): \
  2295. { \
  2296. seqstr = _get_keypad_sequence(control_key_state, (normal), \
  2297. (shifted)); \
  2298. } \
  2299. break;
  2300. // The shift key and other modifier keys should affect the output
  2301. // sequence.
  2302. #define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
  2303. case (vk): \
  2304. { \
  2305. seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
  2306. control_key_state, (normal), (shifted)); \
  2307. } \
  2308. break;
  2309. #define ESC "\x1b"
  2310. #define CSI ESC "["
  2311. #define SS3 ESC "O"
  2312. // Only support normal mode, not application mode.
  2313. // Enhanced keys:
  2314. // * 6-pack: insert, delete, home, end, page up, page down
  2315. // * cursor keys: up, down, right, left
  2316. // * keypad: divide, enter
  2317. // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
  2318. // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
  2319. if (_is_enhanced_key(control_key_state)) {
  2320. switch (vk) {
  2321. case VK_RETURN: // Enter key on keypad
  2322. if (_is_ctrl_pressed(control_key_state)) {
  2323. seqstr = "\n";
  2324. } else {
  2325. seqstr = "\r";
  2326. }
  2327. break;
  2328. MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
  2329. MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
  2330. // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
  2331. // will be fixed soon to match xterm which sends CSI "F" and
  2332. // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
  2333. MATCH(VK_END, CSI "F");
  2334. MATCH(VK_HOME, CSI "H");
  2335. MATCH_MODIFIER(VK_LEFT, CSI "D");
  2336. MATCH_MODIFIER(VK_UP, CSI "A");
  2337. MATCH_MODIFIER(VK_RIGHT, CSI "C");
  2338. MATCH_MODIFIER(VK_DOWN, CSI "B");
  2339. MATCH_MODIFIER(VK_INSERT, CSI "2~");
  2340. MATCH_MODIFIER(VK_DELETE, CSI "3~");
  2341. MATCH(VK_DIVIDE, "/");
  2342. }
  2343. } else { // Non-enhanced keys:
  2344. switch (vk) {
  2345. case VK_BACK: // backspace
  2346. if (_is_alt_pressed(control_key_state)) {
  2347. seqstr = ESC "\x7f";
  2348. } else {
  2349. seqstr = "\x7f";
  2350. }
  2351. break;
  2352. case VK_TAB:
  2353. if (_is_shift_pressed(control_key_state)) {
  2354. seqstr = CSI "Z";
  2355. } else {
  2356. seqstr = "\t";
  2357. }
  2358. break;
  2359. // Number 5 key in keypad when NumLock is off, or if NumLock is
  2360. // on and Shift is down.
  2361. MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
  2362. case VK_RETURN: // Enter key on main keyboard
  2363. if (_is_alt_pressed(control_key_state)) {
  2364. seqstr = ESC "\n";
  2365. } else if (_is_ctrl_pressed(control_key_state)) {
  2366. seqstr = "\n";
  2367. } else {
  2368. seqstr = "\r";
  2369. }
  2370. break;
  2371. // VK_ESCAPE: Don't do any special handling. The OS uses many
  2372. // of the sequences with Escape and many of the remaining
  2373. // sequences don't produce bKeyDown messages, only !bKeyDown
  2374. // for whatever reason.
  2375. case VK_SPACE:
  2376. if (_is_alt_pressed(control_key_state)) {
  2377. seqstr = ESC " ";
  2378. } else if (_is_ctrl_pressed(control_key_state)) {
  2379. seqbuf[0] = '\0'; // NULL char
  2380. seqbuflen = 1;
  2381. } else {
  2382. seqstr = " ";
  2383. }
  2384. break;
  2385. MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
  2386. MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
  2387. MATCH_KEYPAD(VK_END, CSI "4~", "1");
  2388. MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
  2389. MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
  2390. MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
  2391. MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
  2392. MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
  2393. MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
  2394. MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
  2395. _get_decimal_char());
  2396. case 0x30: // 0
  2397. case 0x31: // 1
  2398. case 0x39: // 9
  2399. case VK_OEM_1: // ;:
  2400. case VK_OEM_PLUS: // =+
  2401. case VK_OEM_COMMA: // ,<
  2402. case VK_OEM_PERIOD: // .>
  2403. case VK_OEM_7: // '"
  2404. case VK_OEM_102: // depends on keyboard, could be <> or \|
  2405. case VK_OEM_2: // /?
  2406. case VK_OEM_3: // `~
  2407. case VK_OEM_4: // [{
  2408. case VK_OEM_5: // \|
  2409. case VK_OEM_6: // ]}
  2410. {
  2411. seqbuflen = _get_control_character(seqbuf, key_event,
  2412. control_key_state);
  2413. if (_is_alt_pressed(control_key_state)) {
  2414. seqbuflen = _escape_prefix(seqbuf, seqbuflen);
  2415. }
  2416. }
  2417. break;
  2418. case 0x32: // 2
  2419. case 0x36: // 6
  2420. case VK_OEM_MINUS: // -_
  2421. {
  2422. seqbuflen = _get_control_character(seqbuf, key_event,
  2423. control_key_state);
  2424. // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
  2425. // prefix with escape.
  2426. if (_is_alt_pressed(control_key_state) &&
  2427. !(_is_ctrl_pressed(control_key_state) &&
  2428. !_is_shift_pressed(control_key_state))) {
  2429. seqbuflen = _escape_prefix(seqbuf, seqbuflen);
  2430. }
  2431. }
  2432. break;
  2433. case 0x33: // 3
  2434. case 0x34: // 4
  2435. case 0x35: // 5
  2436. case 0x37: // 7
  2437. case 0x38: // 8
  2438. {
  2439. seqbuflen = _get_control_character(seqbuf, key_event,
  2440. control_key_state);
  2441. // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
  2442. // prefix with escape.
  2443. if (_is_alt_pressed(control_key_state) &&
  2444. !(_is_ctrl_pressed(control_key_state) &&
  2445. !_is_shift_pressed(control_key_state))) {
  2446. seqbuflen = _escape_prefix(seqbuf, seqbuflen);
  2447. }
  2448. }
  2449. break;
  2450. case 0x41: // a
  2451. case 0x42: // b
  2452. case 0x43: // c
  2453. case 0x44: // d
  2454. case 0x45: // e
  2455. case 0x46: // f
  2456. case 0x47: // g
  2457. case 0x48: // h
  2458. case 0x49: // i
  2459. case 0x4a: // j
  2460. case 0x4b: // k
  2461. case 0x4c: // l
  2462. case 0x4d: // m
  2463. case 0x4e: // n
  2464. case 0x4f: // o
  2465. case 0x50: // p
  2466. case 0x51: // q
  2467. case 0x52: // r
  2468. case 0x53: // s
  2469. case 0x54: // t
  2470. case 0x55: // u
  2471. case 0x56: // v
  2472. case 0x57: // w
  2473. case 0x58: // x
  2474. case 0x59: // y
  2475. case 0x5a: // z
  2476. {
  2477. seqbuflen = _get_non_alt_char(seqbuf, key_event,
  2478. control_key_state);
  2479. // If Alt is pressed, then prefix with escape.
  2480. if (_is_alt_pressed(control_key_state)) {
  2481. seqbuflen = _escape_prefix(seqbuf, seqbuflen);
  2482. }
  2483. }
  2484. break;
  2485. // These virtual key codes are generated by the keys on the
  2486. // keypad *when NumLock is on* and *Shift is up*.
  2487. MATCH(VK_NUMPAD0, "0");
  2488. MATCH(VK_NUMPAD1, "1");
  2489. MATCH(VK_NUMPAD2, "2");
  2490. MATCH(VK_NUMPAD3, "3");
  2491. MATCH(VK_NUMPAD4, "4");
  2492. MATCH(VK_NUMPAD5, "5");
  2493. MATCH(VK_NUMPAD6, "6");
  2494. MATCH(VK_NUMPAD7, "7");
  2495. MATCH(VK_NUMPAD8, "8");
  2496. MATCH(VK_NUMPAD9, "9");
  2497. MATCH(VK_MULTIPLY, "*");
  2498. MATCH(VK_ADD, "+");
  2499. MATCH(VK_SUBTRACT, "-");
  2500. // VK_DECIMAL is generated by the . key on the keypad *when
  2501. // NumLock is on* and *Shift is up* and the sequence is not
  2502. // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
  2503. // Windows Security screen to come up).
  2504. case VK_DECIMAL:
  2505. // U.S. English uses '.', Germany German uses ','.
  2506. seqbuflen = _get_non_control_char(seqbuf, key_event,
  2507. control_key_state);
  2508. break;
  2509. MATCH_MODIFIER(VK_F1, SS3 "P");
  2510. MATCH_MODIFIER(VK_F2, SS3 "Q");
  2511. MATCH_MODIFIER(VK_F3, SS3 "R");
  2512. MATCH_MODIFIER(VK_F4, SS3 "S");
  2513. MATCH_MODIFIER(VK_F5, CSI "15~");
  2514. MATCH_MODIFIER(VK_F6, CSI "17~");
  2515. MATCH_MODIFIER(VK_F7, CSI "18~");
  2516. MATCH_MODIFIER(VK_F8, CSI "19~");
  2517. MATCH_MODIFIER(VK_F9, CSI "20~");
  2518. MATCH_MODIFIER(VK_F10, CSI "21~");
  2519. MATCH_MODIFIER(VK_F11, CSI "23~");
  2520. MATCH_MODIFIER(VK_F12, CSI "24~");
  2521. MATCH_MODIFIER(VK_F13, CSI "25~");
  2522. MATCH_MODIFIER(VK_F14, CSI "26~");
  2523. MATCH_MODIFIER(VK_F15, CSI "28~");
  2524. MATCH_MODIFIER(VK_F16, CSI "29~");
  2525. MATCH_MODIFIER(VK_F17, CSI "31~");
  2526. MATCH_MODIFIER(VK_F18, CSI "32~");
  2527. MATCH_MODIFIER(VK_F19, CSI "33~");
  2528. MATCH_MODIFIER(VK_F20, CSI "34~");
  2529. // MATCH_MODIFIER(VK_F21, ???);
  2530. // MATCH_MODIFIER(VK_F22, ???);
  2531. // MATCH_MODIFIER(VK_F23, ???);
  2532. // MATCH_MODIFIER(VK_F24, ???);
  2533. }
  2534. }
  2535. #undef MATCH
  2536. #undef MATCH_MODIFIER
  2537. #undef MATCH_KEYPAD
  2538. #undef MATCH_MODIFIER_KEYPAD
  2539. #undef ESC
  2540. #undef CSI
  2541. #undef SS3
  2542. const char* out;
  2543. size_t outlen;
  2544. // Check for output in any of:
  2545. // * seqstr is set (and strlen can be used to determine the length).
  2546. // * seqbuf and seqbuflen are set
  2547. // Fallback to ch from Windows.
  2548. if (seqstr != NULL) {
  2549. out = seqstr;
  2550. outlen = strlen(seqstr);
  2551. } else if (seqbuflen > 0) {
  2552. out = seqbuf;
  2553. outlen = seqbuflen;
  2554. } else if (ch != '\0') {
  2555. // Use whatever Windows told us it is.
  2556. seqbuf[0] = ch;
  2557. seqbuflen = 1;
  2558. out = seqbuf;
  2559. outlen = seqbuflen;
  2560. } else {
  2561. // No special handling for the virtual key code and Windows isn't
  2562. // telling us a character code, then we don't know how to translate
  2563. // the key press.
  2564. //
  2565. // Consume the input and 'continue' to cause us to get a new key
  2566. // event.
  2567. D("_console_read: unknown virtual key code: %d, enhanced: %s\n",
  2568. vk, _is_enhanced_key(control_key_state) ? "true" : "false");
  2569. key_event->wRepeatCount = 0;
  2570. continue;
  2571. }
  2572. int bytesRead = 0;
  2573. // put output wRepeatCount times into buf/len
  2574. while (key_event->wRepeatCount > 0) {
  2575. if (len >= outlen) {
  2576. // Write to buf/len
  2577. memcpy(buf, out, outlen);
  2578. buf = (void*)((char*)buf + outlen);
  2579. len -= outlen;
  2580. bytesRead += outlen;
  2581. // consume the input
  2582. --key_event->wRepeatCount;
  2583. } else {
  2584. // Not enough space, so just leave it in _win32_input_record
  2585. // for a subsequent retrieval.
  2586. if (bytesRead == 0) {
  2587. // We didn't write anything because there wasn't enough
  2588. // space to even write one sequence. This should never
  2589. // happen if the caller uses sensible buffer sizes
  2590. // (i.e. >= maximum sequence length which is probably a
  2591. // few bytes long).
  2592. D("_console_read: no buffer space to write one sequence; "
  2593. "buffer: %ld, sequence: %ld\n", (long)len,
  2594. (long)outlen);
  2595. errno = ENOMEM;
  2596. return -1;
  2597. } else {
  2598. // Stop trying to write to buf/len, just return whatever
  2599. // we wrote so far.
  2600. break;
  2601. }
  2602. }
  2603. }
  2604. return bytesRead;
  2605. }
  2606. }
  2607. static DWORD _old_console_mode; // previous GetConsoleMode() result
  2608. static HANDLE _console_handle; // when set, console mode should be restored
  2609. void stdin_raw_init(const int fd) {
  2610. if (STDIN_FILENO == fd) {
  2611. const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
  2612. if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
  2613. return;
  2614. }
  2615. if (GetFileType(in) != FILE_TYPE_CHAR) {
  2616. // stdin might be a file or pipe.
  2617. return;
  2618. }
  2619. if (!GetConsoleMode(in, &_old_console_mode)) {
  2620. // If GetConsoleMode() fails, stdin is probably is not a console.
  2621. return;
  2622. }
  2623. // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
  2624. // calling the process Ctrl-C routine (configured by
  2625. // SetConsoleCtrlHandler()).
  2626. // Disable ENABLE_LINE_INPUT so that input is immediately sent.
  2627. // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
  2628. // flag also seems necessary to have proper line-ending processing.
  2629. if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
  2630. ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
  2631. // This really should not fail.
  2632. D("stdin_raw_init: SetConsoleMode() failure, error %ld\n",
  2633. GetLastError());
  2634. }
  2635. // Once this is set, it means that stdin has been configured for
  2636. // reading from and that the old console mode should be restored later.
  2637. _console_handle = in;
  2638. // Note that we don't need to configure C Runtime line-ending
  2639. // translation because _console_read() does not call the C Runtime to
  2640. // read from the console.
  2641. }
  2642. }
  2643. void stdin_raw_restore(const int fd) {
  2644. if (STDIN_FILENO == fd) {
  2645. if (_console_handle != NULL) {
  2646. const HANDLE in = _console_handle;
  2647. _console_handle = NULL; // clear state
  2648. if (!SetConsoleMode(in, _old_console_mode)) {
  2649. // This really should not fail.
  2650. D("stdin_raw_restore: SetConsoleMode() failure, error %ld\n",
  2651. GetLastError());
  2652. }
  2653. }
  2654. }
  2655. }
  2656. // Called by 'adb shell' command to read from stdin.
  2657. int unix_read(int fd, void* buf, size_t len) {
  2658. if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
  2659. // If it is a request to read from stdin, and stdin_raw_init() has been
  2660. // called, and it successfully configured the console, then read from
  2661. // the console using Win32 console APIs and partially emulate a unix
  2662. // terminal.
  2663. return _console_read(_console_handle, buf, len);
  2664. } else {
  2665. // Just call into C Runtime which can read from pipes/files and which
  2666. // can do LF/CR translation.
  2667. #undef read
  2668. return read(fd, buf, len);
  2669. }
  2670. }