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