blob: f534d61165562fffc1aaf660ee069ce1f4ead4bf [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
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
17#define TRACE_TAG TRACE_SYSDEPS
18
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
Spencer Low753d4852015-07-30 23:07:55 -070028#include <memory>
29#include <string>
Spencer Low6815c072015-05-11 01:08:48 -070030#include <unordered_map>
Spencer Low753d4852015-07-30 23:07:55 -070031
Elliott Hughesfe447512015-07-24 11:35:40 -070032#include <cutils/sockets.h>
33
Spencer Low753d4852015-07-30 23:07:55 -070034#include <base/logging.h>
35#include <base/stringprintf.h>
36#include <base/strings.h>
37
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080038#include "adb.h"
39
40extern void fatal(const char *fmt, ...);
41
Elliott Hughes6a096932015-04-16 16:47:02 -070042/* forward declarations */
43
44typedef const struct FHClassRec_* FHClass;
45typedef struct FHRec_* FH;
46typedef struct EventHookRec_* EventHook;
47
48typedef struct FHClassRec_ {
49 void (*_fh_init)(FH);
50 int (*_fh_close)(FH);
51 int (*_fh_lseek)(FH, int, int);
52 int (*_fh_read)(FH, void*, int);
53 int (*_fh_write)(FH, const void*, int);
54 void (*_fh_hook)(FH, int, EventHook);
55} FHClassRec;
56
57static void _fh_file_init(FH);
58static int _fh_file_close(FH);
59static int _fh_file_lseek(FH, int, int);
60static int _fh_file_read(FH, void*, int);
61static int _fh_file_write(FH, const void*, int);
62static void _fh_file_hook(FH, int, EventHook);
63
64static const FHClassRec _fh_file_class = {
65 _fh_file_init,
66 _fh_file_close,
67 _fh_file_lseek,
68 _fh_file_read,
69 _fh_file_write,
70 _fh_file_hook
71};
72
73static void _fh_socket_init(FH);
74static int _fh_socket_close(FH);
75static int _fh_socket_lseek(FH, int, int);
76static int _fh_socket_read(FH, void*, int);
77static int _fh_socket_write(FH, const void*, int);
78static void _fh_socket_hook(FH, int, EventHook);
79
80static const FHClassRec _fh_socket_class = {
81 _fh_socket_init,
82 _fh_socket_close,
83 _fh_socket_lseek,
84 _fh_socket_read,
85 _fh_socket_write,
86 _fh_socket_hook
87};
88
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080089#define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
90
Spencer Low753d4852015-07-30 23:07:55 -070091std::string SystemErrorCodeToString(const DWORD error_code) {
92 const int kErrorMessageBufferSize = 256;
Spencer Lowcc467f12015-08-02 18:13:54 -070093 WCHAR msgbuf[kErrorMessageBufferSize];
Spencer Low753d4852015-07-30 23:07:55 -070094 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
Spencer Lowcc467f12015-08-02 18:13:54 -070095 DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf,
Spencer Low753d4852015-07-30 23:07:55 -070096 arraysize(msgbuf), nullptr);
97 if (len == 0) {
98 return android::base::StringPrintf(
99 "Error (%lu) while retrieving error. (%lu)", GetLastError(),
100 error_code);
101 }
102
Spencer Lowcc467f12015-08-02 18:13:54 -0700103 // Convert UTF-16 to UTF-8.
104 std::string msg(narrow(msgbuf));
Spencer Low753d4852015-07-30 23:07:55 -0700105 // Messages returned by the system end with line breaks.
106 msg = android::base::Trim(msg);
107 // There are many Windows error messages compared to POSIX, so include the
108 // numeric error code for easier, quicker, accurate identification. Use
109 // decimal instead of hex because there are decimal ranges like 10000-11999
110 // for Winsock.
111 android::base::StringAppendF(&msg, " (%lu)", error_code);
112 return msg;
113}
114
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800115/**************************************************************************/
116/**************************************************************************/
117/***** *****/
118/***** replaces libs/cutils/load_file.c *****/
119/***** *****/
120/**************************************************************************/
121/**************************************************************************/
122
123void *load_file(const char *fn, unsigned *_sz)
124{
125 HANDLE file;
126 char *data;
127 DWORD file_size;
128
Spencer Low6815c072015-05-11 01:08:48 -0700129 file = CreateFileW( widen(fn).c_str(),
130 GENERIC_READ,
131 FILE_SHARE_READ,
132 NULL,
133 OPEN_EXISTING,
134 0,
135 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800136
137 if (file == INVALID_HANDLE_VALUE)
138 return NULL;
139
140 file_size = GetFileSize( file, NULL );
141 data = NULL;
142
143 if (file_size > 0) {
144 data = (char*) malloc( file_size + 1 );
145 if (data == NULL) {
146 D("load_file: could not allocate %ld bytes\n", file_size );
147 file_size = 0;
148 } else {
149 DWORD out_bytes;
150
151 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
152 out_bytes != file_size )
153 {
154 D("load_file: could not read %ld bytes from '%s'\n", file_size, fn);
155 free(data);
156 data = NULL;
157 file_size = 0;
158 }
159 }
160 }
161 CloseHandle( file );
162
163 *_sz = (unsigned) file_size;
164 return data;
165}
166
167/**************************************************************************/
168/**************************************************************************/
169/***** *****/
170/***** common file descriptor handling *****/
171/***** *****/
172/**************************************************************************/
173/**************************************************************************/
174
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800175/* used to emulate unix-domain socket pairs */
176typedef struct SocketPairRec_* SocketPair;
177
178typedef struct FHRec_
179{
180 FHClass clazz;
181 int used;
182 int eof;
183 union {
184 HANDLE handle;
185 SOCKET socket;
186 SocketPair pair;
187 } u;
188
189 HANDLE event;
190 int mask;
191
192 char name[32];
193
194} FHRec;
195
196#define fh_handle u.handle
197#define fh_socket u.socket
198#define fh_pair u.pair
199
200#define WIN32_FH_BASE 100
201
202#define WIN32_MAX_FHS 128
203
204static adb_mutex_t _win32_lock;
205static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700206static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800207
208static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700209_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800210{
211 FH f;
212
213 fd -= WIN32_FH_BASE;
214
Spencer Lowb732a372015-07-24 15:38:19 -0700215 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Spencer Low3a2421b2015-05-22 20:09:06 -0700216 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
217 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800218 errno = EBADF;
219 return NULL;
220 }
221
222 f = &_win32_fhs[fd];
223
224 if (f->used == 0) {
Spencer Low3a2421b2015-05-22 20:09:06 -0700225 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
226 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800227 errno = EBADF;
228 return NULL;
229 }
230
231 return f;
232}
233
234
235static int
236_fh_to_int( FH f )
237{
238 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
239 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
240
241 return -1;
242}
243
244static FH
245_fh_alloc( FHClass clazz )
246{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800247 FH f = NULL;
248
249 adb_mutex_lock( &_win32_lock );
250
Spencer Lowb732a372015-07-24 15:38:19 -0700251 // Search entire array, starting from _win32_fh_next.
252 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
253 // Keep incrementing _win32_fh_next to avoid giving out an index that
254 // was recently closed, to try to avoid use-after-free.
255 const int index = _win32_fh_next++;
256 // Handle wrap-around of _win32_fh_next.
257 if (_win32_fh_next == WIN32_MAX_FHS) {
258 _win32_fh_next = 0;
259 }
260 if (_win32_fhs[index].clazz == NULL) {
261 f = &_win32_fhs[index];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800262 goto Exit;
263 }
264 }
265 D( "_fh_alloc: no more free file descriptors\n" );
Spencer Lowb732a372015-07-24 15:38:19 -0700266 errno = EMFILE; // Too many open files
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800267Exit:
268 if (f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700269 f->clazz = clazz;
270 f->used = 1;
271 f->eof = 0;
272 f->name[0] = '\0';
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800273 clazz->_fh_init(f);
274 }
275 adb_mutex_unlock( &_win32_lock );
276 return f;
277}
278
279
280static int
281_fh_close( FH f )
282{
Spencer Lowb732a372015-07-24 15:38:19 -0700283 // Use lock so that closing only happens once and so that _fh_alloc can't
284 // allocate a FH that we're in the middle of closing.
285 adb_mutex_lock(&_win32_lock);
286 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800287 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700288 f->name[0] = '\0';
289 f->eof = 0;
290 f->used = 0;
291 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800292 }
Spencer Lowb732a372015-07-24 15:38:19 -0700293 adb_mutex_unlock(&_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800294 return 0;
295}
296
Spencer Low753d4852015-07-30 23:07:55 -0700297// Deleter for unique_fh.
298class fh_deleter {
299 public:
300 void operator()(struct FHRec_* fh) {
301 // We're called from a destructor and destructors should not overwrite
302 // errno because callers may do:
303 // errno = EBLAH;
304 // return -1; // calls destructor, which should not overwrite errno
305 const int saved_errno = errno;
306 _fh_close(fh);
307 errno = saved_errno;
308 }
309};
310
311// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
312typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
313
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800314/**************************************************************************/
315/**************************************************************************/
316/***** *****/
317/***** file-based descriptor handling *****/
318/***** *****/
319/**************************************************************************/
320/**************************************************************************/
321
Elliott Hughes6a096932015-04-16 16:47:02 -0700322static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800323 f->fh_handle = INVALID_HANDLE_VALUE;
324}
325
Elliott Hughes6a096932015-04-16 16:47:02 -0700326static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800327 CloseHandle( f->fh_handle );
328 f->fh_handle = INVALID_HANDLE_VALUE;
329 return 0;
330}
331
Elliott Hughes6a096932015-04-16 16:47:02 -0700332static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800333 DWORD read_bytes;
334
335 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
336 D( "adb_read: could not read %d bytes from %s\n", len, f->name );
337 errno = EIO;
338 return -1;
339 } else if (read_bytes < (DWORD)len) {
340 f->eof = 1;
341 }
342 return (int)read_bytes;
343}
344
Elliott Hughes6a096932015-04-16 16:47:02 -0700345static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800346 DWORD wrote_bytes;
347
348 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
349 D( "adb_file_write: could not write %d bytes from %s\n", len, f->name );
350 errno = EIO;
351 return -1;
352 } else if (wrote_bytes < (DWORD)len) {
353 f->eof = 1;
354 }
355 return (int)wrote_bytes;
356}
357
Elliott Hughes6a096932015-04-16 16:47:02 -0700358static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800359 DWORD method;
360 DWORD result;
361
362 switch (origin)
363 {
364 case SEEK_SET: method = FILE_BEGIN; break;
365 case SEEK_CUR: method = FILE_CURRENT; break;
366 case SEEK_END: method = FILE_END; break;
367 default:
368 errno = EINVAL;
369 return -1;
370 }
371
372 result = SetFilePointer( f->fh_handle, pos, NULL, method );
373 if (result == INVALID_SET_FILE_POINTER) {
374 errno = EIO;
375 return -1;
376 } else {
377 f->eof = 0;
378 }
379 return (int)result;
380}
381
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800382
383/**************************************************************************/
384/**************************************************************************/
385/***** *****/
386/***** file-based descriptor handling *****/
387/***** *****/
388/**************************************************************************/
389/**************************************************************************/
390
391int adb_open(const char* path, int options)
392{
393 FH f;
394
395 DWORD desiredAccess = 0;
396 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
397
398 switch (options) {
399 case O_RDONLY:
400 desiredAccess = GENERIC_READ;
401 break;
402 case O_WRONLY:
403 desiredAccess = GENERIC_WRITE;
404 break;
405 case O_RDWR:
406 desiredAccess = GENERIC_READ | GENERIC_WRITE;
407 break;
408 default:
409 D("adb_open: invalid options (0x%0x)\n", options);
410 errno = EINVAL;
411 return -1;
412 }
413
414 f = _fh_alloc( &_fh_file_class );
415 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800416 return -1;
417 }
418
Spencer Low6815c072015-05-11 01:08:48 -0700419 f->fh_handle = CreateFileW( widen(path).c_str(), desiredAccess, shareMode,
420 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800421
422 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700423 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800424 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700425 D( "adb_open: could not open '%s': ", path );
426 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800427 case ERROR_FILE_NOT_FOUND:
428 D( "file not found\n" );
429 errno = ENOENT;
430 return -1;
431
432 case ERROR_PATH_NOT_FOUND:
433 D( "path not found\n" );
434 errno = ENOTDIR;
435 return -1;
436
437 default:
Spencer Low1711e012015-08-02 18:50:17 -0700438 D( "unknown error: %s\n",
439 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800440 errno = ENOENT;
441 return -1;
442 }
443 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800444
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800445 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
446 D( "adb_open: '%s' => fd %d\n", path, _fh_to_int(f) );
447 return _fh_to_int(f);
448}
449
450/* ignore mode on Win32 */
451int adb_creat(const char* path, int mode)
452{
453 FH f;
454
455 f = _fh_alloc( &_fh_file_class );
456 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800457 return -1;
458 }
459
Spencer Low6815c072015-05-11 01:08:48 -0700460 f->fh_handle = CreateFileW( widen(path).c_str(), GENERIC_WRITE,
461 FILE_SHARE_READ | FILE_SHARE_WRITE,
462 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
463 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800464
465 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700466 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800467 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700468 D( "adb_creat: could not open '%s': ", path );
469 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800470 case ERROR_FILE_NOT_FOUND:
471 D( "file not found\n" );
472 errno = ENOENT;
473 return -1;
474
475 case ERROR_PATH_NOT_FOUND:
476 D( "path not found\n" );
477 errno = ENOTDIR;
478 return -1;
479
480 default:
Spencer Low1711e012015-08-02 18:50:17 -0700481 D( "unknown error: %s\n",
482 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483 errno = ENOENT;
484 return -1;
485 }
486 }
487 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
488 D( "adb_creat: '%s' => fd %d\n", path, _fh_to_int(f) );
489 return _fh_to_int(f);
490}
491
492
493int adb_read(int fd, void* buf, int len)
494{
Spencer Low3a2421b2015-05-22 20:09:06 -0700495 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800496
497 if (f == NULL) {
498 return -1;
499 }
500
501 return f->clazz->_fh_read( f, buf, len );
502}
503
504
505int adb_write(int fd, const void* buf, int len)
506{
Spencer Low3a2421b2015-05-22 20:09:06 -0700507 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800508
509 if (f == NULL) {
510 return -1;
511 }
512
513 return f->clazz->_fh_write(f, buf, len);
514}
515
516
517int adb_lseek(int fd, int pos, int where)
518{
Spencer Low3a2421b2015-05-22 20:09:06 -0700519 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800520
521 if (!f) {
522 return -1;
523 }
524
525 return f->clazz->_fh_lseek(f, pos, where);
526}
527
528
529int adb_close(int fd)
530{
Spencer Low3a2421b2015-05-22 20:09:06 -0700531 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800532
533 if (!f) {
534 return -1;
535 }
536
537 D( "adb_close: %s\n", f->name);
538 _fh_close(f);
539 return 0;
540}
541
542/**************************************************************************/
543/**************************************************************************/
544/***** *****/
545/***** socket-based file descriptors *****/
546/***** *****/
547/**************************************************************************/
548/**************************************************************************/
549
Spencer Low31aafa62015-01-25 14:40:16 -0800550#undef setsockopt
551
Spencer Low753d4852015-07-30 23:07:55 -0700552static void _socket_set_errno( const DWORD err ) {
553 // The Windows C Runtime (MSVCRT.DLL) strerror() does not support a lot of
554 // POSIX and socket error codes, so this can only meaningfully map so much.
555 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800556 case 0: errno = 0; break;
Spencer Low32625852015-08-11 16:45:32 -0700557 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
558 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
559 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800560 case WSAEWOULDBLOCK: errno = EAGAIN; break;
561 case WSAEINTR: errno = EINTR; break;
Spencer Low753d4852015-07-30 23:07:55 -0700562 case WSAEFAULT: errno = EFAULT; break;
563 case WSAEINVAL: errno = EINVAL; break;
564 case WSAEMFILE: errno = EMFILE; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800565 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800566 errno = EINVAL;
Spencer Low753d4852015-07-30 23:07:55 -0700567 D( "_socket_set_errno: mapping Windows error code %lu to errno %d\n",
568 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800569 }
570}
571
Elliott Hughes6a096932015-04-16 16:47:02 -0700572static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800573 f->fh_socket = INVALID_SOCKET;
574 f->event = WSACreateEvent();
Spencer Low753d4852015-07-30 23:07:55 -0700575 if (f->event == WSA_INVALID_EVENT) {
576 D("WSACreateEvent failed: %s\n",
577 SystemErrorCodeToString(WSAGetLastError()).c_str());
578
579 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
580 // on failure, instead of NULL which is what Windows really returns on
581 // error. It might be better to change all the other code to look for
582 // NULL, but that is a much riskier change.
583 f->event = INVALID_HANDLE_VALUE;
584 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800585 f->mask = 0;
586}
587
Elliott Hughes6a096932015-04-16 16:47:02 -0700588static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700589 if (f->fh_socket != INVALID_SOCKET) {
590 /* gently tell any peer that we're closing the socket */
591 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
592 // If the socket is not connected, this returns an error. We want to
593 // minimize logging spam, so don't log these errors for now.
594#if 0
595 D("socket shutdown failed: %s\n",
596 SystemErrorCodeToString(WSAGetLastError()).c_str());
597#endif
598 }
599 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
600 D("closesocket failed: %s\n",
601 SystemErrorCodeToString(WSAGetLastError()).c_str());
602 }
603 f->fh_socket = INVALID_SOCKET;
604 }
605 if (f->event != NULL) {
606 if (!CloseHandle(f->event)) {
607 D("CloseHandle failed: %s\n",
608 SystemErrorCodeToString(GetLastError()).c_str());
609 }
610 f->event = NULL;
611 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800612 f->mask = 0;
613 return 0;
614}
615
Elliott Hughes6a096932015-04-16 16:47:02 -0700616static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800617 errno = EPIPE;
618 return -1;
619}
620
Elliott Hughes6a096932015-04-16 16:47:02 -0700621static int _fh_socket_read(FH f, void* buf, int len) {
622 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800623 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700624 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700625 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
626 // that to reduce spam and confusion.
627 if (err != WSAEWOULDBLOCK) {
628 D("recv fd %d failed: %s\n", _fh_to_int(f),
629 SystemErrorCodeToString(err).c_str());
630 }
Spencer Low753d4852015-07-30 23:07:55 -0700631 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800632 result = -1;
633 }
634 return result;
635}
636
Elliott Hughes6a096932015-04-16 16:47:02 -0700637static int _fh_socket_write(FH f, const void* buf, int len) {
638 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700640 const DWORD err = WSAGetLastError();
641 D("send fd %d failed: %s\n", _fh_to_int(f),
642 SystemErrorCodeToString(err).c_str());
643 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800644 result = -1;
645 }
646 return result;
647}
648
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800649/**************************************************************************/
650/**************************************************************************/
651/***** *****/
652/***** replacement for libs/cutils/socket_xxxx.c *****/
653/***** *****/
654/**************************************************************************/
655/**************************************************************************/
656
657#include <winsock2.h>
658
659static int _winsock_init;
660
661static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800662_init_winsock( void )
663{
Spencer Low753d4852015-07-30 23:07:55 -0700664 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700665 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800666 if (!_winsock_init) {
667 WSADATA wsaData;
668 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
669 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700670 fatal( "adb: could not initialize Winsock: %s",
671 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800672 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800673 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700674
675 // Note that we do not call atexit() to register WSACleanup to be called
676 // at normal process termination because:
677 // 1) When exit() is called, there are still threads actively using
678 // Winsock because we don't cleanly shutdown all threads, so it
679 // doesn't make sense to call WSACleanup() and may cause problems
680 // with those threads.
681 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
682 // calls WSACleanup() which tries to unload a DLL, which tries to
683 // grab the LoaderLock. This conflicts with the device_poll_thread
684 // which holds the LoaderLock because AdbWinApi.dll calls
685 // setupapi.dll which tries to load wintrust.dll which tries to load
686 // crypt32.dll which calls atexit() which tries to acquire the C
687 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800688 }
689}
690
Spencer Low753d4852015-07-30 23:07:55 -0700691int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800692 struct sockaddr_in addr;
693 SOCKET s;
694
Spencer Low753d4852015-07-30 23:07:55 -0700695 unique_fh f(_fh_alloc(&_fh_socket_class));
696 if (!f) {
697 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800698 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700699 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800700
701 if (!_winsock_init)
702 _init_winsock();
703
704 memset(&addr, 0, sizeof(addr));
705 addr.sin_family = AF_INET;
706 addr.sin_port = htons(port);
707 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
708
709 s = socket(AF_INET, type, 0);
710 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700711 *error = android::base::StringPrintf("cannot create socket: %s",
712 SystemErrorCodeToString(WSAGetLastError()).c_str());
713 D("%s\n", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700714 return -1;
715 }
716 f->fh_socket = s;
717
718 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700719 // Save err just in case inet_ntoa() or ntohs() changes the last error.
720 const DWORD err = WSAGetLastError();
721 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
722 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
723 SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700724 D("could not connect to %s:%d: %s\n",
725 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800726 return -1;
727 }
728
Spencer Low753d4852015-07-30 23:07:55 -0700729 const int fd = _fh_to_int(f.get());
730 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
731 type != SOCK_STREAM ? "udp:" : "", port );
732 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
733 fd );
734 f.release();
735 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800736}
737
738#define LISTEN_BACKLOG 4
739
Spencer Low753d4852015-07-30 23:07:55 -0700740// interface_address is INADDR_LOOPBACK or INADDR_ANY.
741static int _network_server(int port, int type, u_long interface_address,
742 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800743 struct sockaddr_in addr;
744 SOCKET s;
745 int n;
746
Spencer Low753d4852015-07-30 23:07:55 -0700747 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800748 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700749 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800750 return -1;
751 }
752
753 if (!_winsock_init)
754 _init_winsock();
755
756 memset(&addr, 0, sizeof(addr));
757 addr.sin_family = AF_INET;
758 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700759 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800760
Spencer Low753d4852015-07-30 23:07:55 -0700761 // TODO: Consider using dual-stack socket that can simultaneously listen on
762 // IPv4 and IPv6.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800763 s = socket(AF_INET, type, 0);
Spencer Low753d4852015-07-30 23:07:55 -0700764 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700765 *error = android::base::StringPrintf("cannot create socket: %s",
766 SystemErrorCodeToString(WSAGetLastError()).c_str());
767 D("%s\n", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700768 return -1;
769 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800770
771 f->fh_socket = s;
772
Spencer Low32625852015-08-11 16:45:32 -0700773 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
774 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800775 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700776 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
777 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700778 *error = android::base::StringPrintf(
779 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
780 SystemErrorCodeToString(WSAGetLastError()).c_str());
781 D("%s\n", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700782 return -1;
783 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800784
Spencer Low32625852015-08-11 16:45:32 -0700785 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
786 // Save err just in case inet_ntoa() or ntohs() changes the last error.
787 const DWORD err = WSAGetLastError();
788 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
789 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
790 SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700791 D("could not bind to %s:%d: %s\n",
792 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800793 return -1;
794 }
795 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700796 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700797 *error = android::base::StringPrintf("cannot listen on socket: %s",
798 SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700799 D("could not listen on %s:%d: %s\n",
800 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800801 return -1;
802 }
803 }
Spencer Low753d4852015-07-30 23:07:55 -0700804 const int fd = _fh_to_int(f.get());
805 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
806 interface_address == INADDR_LOOPBACK ? "lo" : "any",
807 type != SOCK_STREAM ? "udp:" : "", port );
808 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
809 fd );
810 f.release();
811 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800812}
813
Spencer Low753d4852015-07-30 23:07:55 -0700814int network_loopback_server(int port, int type, std::string* error) {
815 return _network_server(port, type, INADDR_LOOPBACK, error);
816}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800817
Spencer Low753d4852015-07-30 23:07:55 -0700818int network_inaddr_any_server(int port, int type, std::string* error) {
819 return _network_server(port, type, INADDR_ANY, error);
820}
821
822int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
823 unique_fh f(_fh_alloc(&_fh_socket_class));
824 if (!f) {
825 *error = strerror(errno);
826 return -1;
827 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800828
Elliott Hughes43df1092015-07-23 17:12:58 -0700829 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800830
Spencer Low753d4852015-07-30 23:07:55 -0700831 struct addrinfo hints;
832 memset(&hints, 0, sizeof(hints));
833 hints.ai_family = AF_UNSPEC;
834 hints.ai_socktype = type;
835
836 char port_str[16];
837 snprintf(port_str, sizeof(port_str), "%d", port);
838
839 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700840
841#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
842 // TODO: When the Android SDK tools increases the Windows system
843 // requirements >= WinXP SP2, switch to GetAddrInfoW(widen(host).c_str()).
844#else
845 // Otherwise, keep using getaddrinfo(), or do runtime API detection
846 // with GetProcAddress("GetAddrInfoW").
847#endif
Spencer Low753d4852015-07-30 23:07:55 -0700848 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -0700849 *error = android::base::StringPrintf(
850 "cannot resolve host '%s' and port %s: %s", host.c_str(),
851 port_str, SystemErrorCodeToString(WSAGetLastError()).c_str());
852 D("%s\n", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800853 return -1;
854 }
Spencer Low753d4852015-07-30 23:07:55 -0700855 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
856 addrinfo(addrinfo_ptr, freeaddrinfo);
857 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800858
Spencer Low753d4852015-07-30 23:07:55 -0700859 // TODO: Try all the addresses if there's more than one? This just uses
860 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
861 // which tries all addresses, takes a timeout and more.
862 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
863 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800864 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700865 *error = android::base::StringPrintf("cannot create socket: %s",
866 SystemErrorCodeToString(WSAGetLastError()).c_str());
867 D("%s\n", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800868 return -1;
869 }
870 f->fh_socket = s;
871
Spencer Low753d4852015-07-30 23:07:55 -0700872 // TODO: Implement timeouts for Windows. Seems like the default in theory
873 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
874 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700875 // TODO: Use WSAAddressToString or inet_ntop on address.
876 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
877 host.c_str(), port_str,
878 SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700879 D("could not connect to %s:%s:%s: %s\n",
880 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
881 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800882 return -1;
883 }
884
Spencer Low753d4852015-07-30 23:07:55 -0700885 const int fd = _fh_to_int(f.get());
886 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
887 type != SOCK_STREAM ? "udp:" : "", port );
888 D( "host '%s' port %d type %s => fd %d\n", host.c_str(), port,
889 type != SOCK_STREAM ? "udp" : "tcp", fd );
890 f.release();
891 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800892}
893
894#undef accept
895int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
896{
Spencer Low3a2421b2015-05-22 20:09:06 -0700897 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200898
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800899 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Spencer Low753d4852015-07-30 23:07:55 -0700900 D("adb_socket_accept: invalid fd %d\n", serverfd);
901 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800902 return -1;
903 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200904
Spencer Low753d4852015-07-30 23:07:55 -0700905 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800906 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700907 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
908 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800909 return -1;
910 }
911
912 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
913 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700914 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700915 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
916 " failed: " + SystemErrorCodeToString(err);
917 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800918 return -1;
919 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200920
Spencer Low753d4852015-07-30 23:07:55 -0700921 const int fd = _fh_to_int(fh.get());
922 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
923 D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, fd );
924 fh.release();
925 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800926}
927
928
Spencer Low31aafa62015-01-25 14:40:16 -0800929int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800930{
Spencer Low3a2421b2015-05-22 20:09:06 -0700931 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200932
Spencer Low31aafa62015-01-25 14:40:16 -0800933 if ( !fh || fh->clazz != &_fh_socket_class ) {
934 D("adb_setsockopt: invalid fd %d\n", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700935 errno = EBADF;
936 return -1;
937 }
938 int result = setsockopt( fh->fh_socket, level, optname,
939 reinterpret_cast<const char*>(optval), optlen );
940 if ( result == SOCKET_ERROR ) {
941 const DWORD err = WSAGetLastError();
942 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
943 "failed: %s\n", fd, level, optname,
944 SystemErrorCodeToString(err).c_str() );
945 _socket_set_errno( err );
946 result = -1;
947 }
948 return result;
949}
950
951
952int adb_shutdown(int fd)
953{
954 FH f = _fh_from_int(fd, __func__);
955
956 if (!f || f->clazz != &_fh_socket_class) {
957 D("adb_shutdown: invalid fd %d\n", fd);
958 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -0800959 return -1;
960 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800961
Spencer Low753d4852015-07-30 23:07:55 -0700962 D( "adb_shutdown: %s\n", f->name);
963 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
964 const DWORD err = WSAGetLastError();
965 D("socket shutdown fd %d failed: %s\n", fd,
966 SystemErrorCodeToString(err).c_str());
967 _socket_set_errno(err);
968 return -1;
969 }
970 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800971}
972
973/**************************************************************************/
974/**************************************************************************/
975/***** *****/
976/***** emulated socketpairs *****/
977/***** *****/
978/**************************************************************************/
979/**************************************************************************/
980
981/* we implement socketpairs directly in use space for the following reasons:
982 * - it avoids copying data from/to the Nt kernel
983 * - it allows us to implement fdevent hooks easily and cheaply, something
984 * that is not possible with standard Win32 pipes !!
985 *
986 * basically, we use two circular buffers, each one corresponding to a given
987 * direction.
988 *
989 * each buffer is implemented as two regions:
990 *
991 * region A which is (a_start,a_end)
992 * region B which is (0, b_end) with b_end <= a_start
993 *
994 * an empty buffer has: a_start = a_end = b_end = 0
995 *
996 * a_start is the pointer where we start reading data
997 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
998 * then you start writing at b_end
999 *
1000 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
1001 *
1002 * there is room when b_end < a_start || a_end < BUFER_SIZE
1003 *
1004 * when reading, a_start is incremented, it a_start meets a_end, then
1005 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1006 */
1007
1008#define BIP_BUFFER_SIZE 4096
1009
1010#if 0
1011#include <stdio.h>
1012# define BIPD(x) D x
1013# define BIPDUMP bip_dump_hex
1014
1015static void bip_dump_hex( const unsigned char* ptr, size_t len )
1016{
1017 int nn, len2 = len;
1018
1019 if (len2 > 8) len2 = 8;
1020
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001021 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001022 printf("%02x", ptr[nn]);
1023 printf(" ");
1024
1025 for (nn = 0; nn < len2; nn++) {
1026 int c = ptr[nn];
1027 if (c < 32 || c > 127)
1028 c = '.';
1029 printf("%c", c);
1030 }
1031 printf("\n");
1032 fflush(stdout);
1033}
1034
1035#else
1036# define BIPD(x) do {} while (0)
1037# define BIPDUMP(p,l) BIPD(p)
1038#endif
1039
1040typedef struct BipBufferRec_
1041{
1042 int a_start;
1043 int a_end;
1044 int b_end;
1045 int fdin;
1046 int fdout;
1047 int closed;
1048 int can_write; /* boolean */
1049 HANDLE evt_write; /* event signaled when one can write to a buffer */
1050 int can_read; /* boolean */
1051 HANDLE evt_read; /* event signaled when one can read from a buffer */
1052 CRITICAL_SECTION lock;
1053 unsigned char buff[ BIP_BUFFER_SIZE ];
1054
1055} BipBufferRec, *BipBuffer;
1056
1057static void
1058bip_buffer_init( BipBuffer buffer )
1059{
1060 D( "bit_buffer_init %p\n", buffer );
1061 buffer->a_start = 0;
1062 buffer->a_end = 0;
1063 buffer->b_end = 0;
1064 buffer->can_write = 1;
1065 buffer->can_read = 0;
1066 buffer->fdin = 0;
1067 buffer->fdout = 0;
1068 buffer->closed = 0;
1069 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1070 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1071 InitializeCriticalSection( &buffer->lock );
1072}
1073
1074static void
1075bip_buffer_close( BipBuffer bip )
1076{
1077 bip->closed = 1;
1078
1079 if (!bip->can_read) {
1080 SetEvent( bip->evt_read );
1081 }
1082 if (!bip->can_write) {
1083 SetEvent( bip->evt_write );
1084 }
1085}
1086
1087static void
1088bip_buffer_done( BipBuffer bip )
1089{
1090 BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
1091 CloseHandle( bip->evt_read );
1092 CloseHandle( bip->evt_write );
1093 DeleteCriticalSection( &bip->lock );
1094}
1095
1096static int
1097bip_buffer_write( BipBuffer bip, const void* src, int len )
1098{
1099 int avail, count = 0;
1100
1101 if (len <= 0)
1102 return 0;
1103
1104 BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1105 BIPDUMP( src, len );
1106
1107 EnterCriticalSection( &bip->lock );
1108
1109 while (!bip->can_write) {
1110 int ret;
1111 LeaveCriticalSection( &bip->lock );
1112
1113 if (bip->closed) {
1114 errno = EPIPE;
1115 return -1;
1116 }
1117 /* spinlocking here is probably unfair, but let's live with it */
1118 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1119 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
1120 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
1121 return 0;
1122 }
1123 if (bip->closed) {
1124 errno = EPIPE;
1125 return -1;
1126 }
1127 EnterCriticalSection( &bip->lock );
1128 }
1129
1130 BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1131
1132 avail = BIP_BUFFER_SIZE - bip->a_end;
1133 if (avail > 0)
1134 {
1135 /* we can append to region A */
1136 if (avail > len)
1137 avail = len;
1138
1139 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001140 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001141 count += avail;
1142 len -= avail;
1143
1144 bip->a_end += avail;
1145 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1146 bip->can_write = 0;
1147 ResetEvent( bip->evt_write );
1148 goto Exit;
1149 }
1150 }
1151
1152 if (len == 0)
1153 goto Exit;
1154
1155 avail = bip->a_start - bip->b_end;
1156 assert( avail > 0 ); /* since can_write is TRUE */
1157
1158 if (avail > len)
1159 avail = len;
1160
1161 memcpy( bip->buff + bip->b_end, src, avail );
1162 count += avail;
1163 bip->b_end += avail;
1164
1165 if (bip->b_end == bip->a_start) {
1166 bip->can_write = 0;
1167 ResetEvent( bip->evt_write );
1168 }
1169
1170Exit:
1171 assert( count > 0 );
1172
1173 if ( !bip->can_read ) {
1174 bip->can_read = 1;
1175 SetEvent( bip->evt_read );
1176 }
1177
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001178 BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001179 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1180 LeaveCriticalSection( &bip->lock );
1181
1182 return count;
1183 }
1184
1185static int
1186bip_buffer_read( BipBuffer bip, void* dst, int len )
1187{
1188 int avail, count = 0;
1189
1190 if (len <= 0)
1191 return 0;
1192
1193 BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1194
1195 EnterCriticalSection( &bip->lock );
1196 while ( !bip->can_read )
1197 {
1198#if 0
1199 LeaveCriticalSection( &bip->lock );
1200 errno = EAGAIN;
1201 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001202#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001203 int ret;
1204 LeaveCriticalSection( &bip->lock );
1205
1206 if (bip->closed) {
1207 errno = EPIPE;
1208 return -1;
1209 }
1210
1211 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1212 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
1213 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
1214 return 0;
1215 }
1216 if (bip->closed) {
1217 errno = EPIPE;
1218 return -1;
1219 }
1220 EnterCriticalSection( &bip->lock );
1221#endif
1222 }
1223
1224 BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1225
1226 avail = bip->a_end - bip->a_start;
1227 assert( avail > 0 ); /* since can_read is TRUE */
1228
1229 if (avail > len)
1230 avail = len;
1231
1232 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001233 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001234 count += avail;
1235 len -= avail;
1236
1237 bip->a_start += avail;
1238 if (bip->a_start < bip->a_end)
1239 goto Exit;
1240
1241 bip->a_start = 0;
1242 bip->a_end = bip->b_end;
1243 bip->b_end = 0;
1244
1245 avail = bip->a_end;
1246 if (avail > 0) {
1247 if (avail > len)
1248 avail = len;
1249 memcpy( dst, bip->buff, avail );
1250 count += avail;
1251 bip->a_start += avail;
1252
1253 if ( bip->a_start < bip->a_end )
1254 goto Exit;
1255
1256 bip->a_start = bip->a_end = 0;
1257 }
1258
1259 bip->can_read = 0;
1260 ResetEvent( bip->evt_read );
1261
1262Exit:
1263 assert( count > 0 );
1264
1265 if (!bip->can_write ) {
1266 bip->can_write = 1;
1267 SetEvent( bip->evt_write );
1268 }
1269
1270 BIPDUMP( (const unsigned char*)dst - count, count );
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001271 BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001272 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1273 LeaveCriticalSection( &bip->lock );
1274
1275 return count;
1276}
1277
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001278typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001279{
1280 BipBufferRec a2b_bip;
1281 BipBufferRec b2a_bip;
1282 FH a_fd;
1283 int used;
1284
1285} SocketPairRec;
1286
1287void _fh_socketpair_init( FH f )
1288{
1289 f->fh_pair = NULL;
1290}
1291
1292static int
1293_fh_socketpair_close( FH f )
1294{
1295 if ( f->fh_pair ) {
1296 SocketPair pair = f->fh_pair;
1297
1298 if ( f == pair->a_fd ) {
1299 pair->a_fd = NULL;
1300 }
1301
1302 bip_buffer_close( &pair->b2a_bip );
1303 bip_buffer_close( &pair->a2b_bip );
1304
1305 if ( --pair->used == 0 ) {
1306 bip_buffer_done( &pair->b2a_bip );
1307 bip_buffer_done( &pair->a2b_bip );
1308 free( pair );
1309 }
1310 f->fh_pair = NULL;
1311 }
1312 return 0;
1313}
1314
1315static int
1316_fh_socketpair_lseek( FH f, int pos, int origin )
1317{
1318 errno = ESPIPE;
1319 return -1;
1320}
1321
1322static int
1323_fh_socketpair_read( FH f, void* buf, int len )
1324{
1325 SocketPair pair = f->fh_pair;
1326 BipBuffer bip;
1327
1328 if (!pair)
1329 return -1;
1330
1331 if ( f == pair->a_fd )
1332 bip = &pair->b2a_bip;
1333 else
1334 bip = &pair->a2b_bip;
1335
1336 return bip_buffer_read( bip, buf, len );
1337}
1338
1339static int
1340_fh_socketpair_write( FH f, const void* buf, int len )
1341{
1342 SocketPair pair = f->fh_pair;
1343 BipBuffer bip;
1344
1345 if (!pair)
1346 return -1;
1347
1348 if ( f == pair->a_fd )
1349 bip = &pair->a2b_bip;
1350 else
1351 bip = &pair->b2a_bip;
1352
1353 return bip_buffer_write( bip, buf, len );
1354}
1355
1356
1357static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1358
1359static const FHClassRec _fh_socketpair_class =
1360{
1361 _fh_socketpair_init,
1362 _fh_socketpair_close,
1363 _fh_socketpair_lseek,
1364 _fh_socketpair_read,
1365 _fh_socketpair_write,
1366 _fh_socketpair_hook
1367};
1368
1369
Elliott Hughes6a096932015-04-16 16:47:02 -07001370int adb_socketpair(int sv[2]) {
1371 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001372
Spencer Low753d4852015-07-30 23:07:55 -07001373 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1374 if (!fa) {
1375 return -1;
1376 }
1377 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1378 if (!fb) {
1379 return -1;
1380 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001381
Elliott Hughes6a096932015-04-16 16:47:02 -07001382 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001383 if (pair == NULL) {
1384 D("adb_socketpair: not enough memory to allocate pipes\n" );
Spencer Low753d4852015-07-30 23:07:55 -07001385 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001386 }
1387
1388 bip_buffer_init( &pair->a2b_bip );
1389 bip_buffer_init( &pair->b2a_bip );
1390
1391 fa->fh_pair = pair;
1392 fb->fh_pair = pair;
1393 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001394 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001395
Spencer Low753d4852015-07-30 23:07:55 -07001396 sv[0] = _fh_to_int(fa.get());
1397 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001398
1399 pair->a2b_bip.fdin = sv[0];
1400 pair->a2b_bip.fdout = sv[1];
1401 pair->b2a_bip.fdin = sv[1];
1402 pair->b2a_bip.fdout = sv[0];
1403
1404 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1405 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
1406 D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001407 fa.release();
1408 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001409 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001410}
1411
1412/**************************************************************************/
1413/**************************************************************************/
1414/***** *****/
1415/***** fdevents emulation *****/
1416/***** *****/
1417/***** this is a very simple implementation, we rely on the fact *****/
1418/***** that ADB doesn't use FDE_ERROR. *****/
1419/***** *****/
1420/**************************************************************************/
1421/**************************************************************************/
1422
1423#define FATAL(x...) fatal(__FUNCTION__, x)
1424
1425#if DEBUG
1426static void dump_fde(fdevent *fde, const char *info)
1427{
1428 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1429 fde->state & FDE_READ ? 'R' : ' ',
1430 fde->state & FDE_WRITE ? 'W' : ' ',
1431 fde->state & FDE_ERROR ? 'E' : ' ',
1432 info);
1433}
1434#else
1435#define dump_fde(fde, info) do { } while(0)
1436#endif
1437
1438#define FDE_EVENTMASK 0x00ff
1439#define FDE_STATEMASK 0xff00
1440
1441#define FDE_ACTIVE 0x0100
1442#define FDE_PENDING 0x0200
1443#define FDE_CREATED 0x0400
1444
1445static void fdevent_plist_enqueue(fdevent *node);
1446static void fdevent_plist_remove(fdevent *node);
1447static fdevent *fdevent_plist_dequeue(void);
1448
1449static fdevent list_pending = {
1450 .next = &list_pending,
1451 .prev = &list_pending,
1452};
1453
1454static fdevent **fd_table = 0;
1455static int fd_table_max = 0;
1456
1457typedef struct EventLooperRec_* EventLooper;
1458
1459typedef struct EventHookRec_
1460{
1461 EventHook next;
1462 FH fh;
1463 HANDLE h;
1464 int wanted; /* wanted event flags */
1465 int ready; /* ready event flags */
1466 void* aux;
1467 void (*prepare)( EventHook hook );
1468 int (*start) ( EventHook hook );
1469 void (*stop) ( EventHook hook );
1470 int (*check) ( EventHook hook );
1471 int (*peek) ( EventHook hook );
1472} EventHookRec;
1473
1474static EventHook _free_hooks;
1475
1476static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001477event_hook_alloc(FH fh) {
1478 EventHook hook = _free_hooks;
1479 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001480 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001481 } else {
1482 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001483 if (hook == NULL)
1484 fatal( "could not allocate event hook\n" );
1485 }
1486 hook->next = NULL;
1487 hook->fh = fh;
1488 hook->wanted = 0;
1489 hook->ready = 0;
1490 hook->h = INVALID_HANDLE_VALUE;
1491 hook->aux = NULL;
1492
1493 hook->prepare = NULL;
1494 hook->start = NULL;
1495 hook->stop = NULL;
1496 hook->check = NULL;
1497 hook->peek = NULL;
1498
1499 return hook;
1500}
1501
1502static void
1503event_hook_free( EventHook hook )
1504{
1505 hook->fh = NULL;
1506 hook->wanted = 0;
1507 hook->ready = 0;
1508 hook->next = _free_hooks;
1509 _free_hooks = hook;
1510}
1511
1512
1513static void
1514event_hook_signal( EventHook hook )
1515{
1516 FH f = hook->fh;
1517 int fd = _fh_to_int(f);
1518 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1519
1520 if (fde != NULL && fde->fd == fd) {
1521 if ((fde->state & FDE_PENDING) == 0) {
1522 fde->state |= FDE_PENDING;
1523 fdevent_plist_enqueue( fde );
1524 }
1525 fde->events |= hook->wanted;
1526 }
1527}
1528
1529
1530#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1531
1532typedef struct EventLooperRec_
1533{
1534 EventHook hooks;
1535 HANDLE htab[ MAX_LOOPER_HANDLES ];
1536 int htab_count;
1537
1538} EventLooperRec;
1539
1540static EventHook*
1541event_looper_find_p( EventLooper looper, FH fh )
1542{
1543 EventHook *pnode = &looper->hooks;
1544 EventHook node = *pnode;
1545 for (;;) {
1546 if ( node == NULL || node->fh == fh )
1547 break;
1548 pnode = &node->next;
1549 node = *pnode;
1550 }
1551 return pnode;
1552}
1553
1554static void
1555event_looper_hook( EventLooper looper, int fd, int events )
1556{
Spencer Low3a2421b2015-05-22 20:09:06 -07001557 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001558 EventHook *pnode;
1559 EventHook node;
1560
1561 if (f == NULL) /* invalid arg */ {
1562 D("event_looper_hook: invalid fd=%d\n", fd);
1563 return;
1564 }
1565
1566 pnode = event_looper_find_p( looper, f );
1567 node = *pnode;
1568 if ( node == NULL ) {
1569 node = event_hook_alloc( f );
1570 node->next = *pnode;
1571 *pnode = node;
1572 }
1573
1574 if ( (node->wanted & events) != events ) {
1575 /* this should update start/stop/check/peek */
1576 D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
1577 fd, node->wanted, events);
1578 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1579 node->wanted |= events;
1580 } else {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001581 D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001582 events, fd, node->wanted);
1583 }
1584}
1585
1586static void
1587event_looper_unhook( EventLooper looper, int fd, int events )
1588{
Spencer Low3a2421b2015-05-22 20:09:06 -07001589 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001590 EventHook *pnode = event_looper_find_p( looper, fh );
1591 EventHook node = *pnode;
1592
1593 if (node != NULL) {
1594 int events2 = events & node->wanted;
1595 if ( events2 == 0 ) {
1596 D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
1597 return;
1598 }
1599 node->wanted &= ~events2;
1600 if (!node->wanted) {
1601 *pnode = node->next;
1602 event_hook_free( node );
1603 }
1604 }
1605}
1606
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001607/*
1608 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1609 * handles to wait on.
1610 *
1611 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1612 * instance, this may happen if there are more than 64 processes running on a
1613 * device, or there are multiple devices connected (including the emulator) with
1614 * the combined number of running processes greater than 64. In this case using
1615 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1616 * because of the API limitations (64 handles max). So, we need to provide a way
1617 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1618 * easiest (and "Microsoft recommended") way to do that would be dividing the
1619 * handle array into chunks with the chunk size less than 64, and fire up as many
1620 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1621 * handles, and will report back to the caller which handle has been set.
1622 * Here is the implementation of that algorithm.
1623 */
1624
1625/* Number of handles to wait on in each wating thread. */
1626#define WAIT_ALL_CHUNK_SIZE 63
1627
1628/* Descriptor for a wating thread */
1629typedef struct WaitForAllParam {
1630 /* A handle to an event to signal when waiting is over. This handle is shared
1631 * accross all the waiting threads, so each waiting thread knows when any
1632 * other thread has exited, so it can exit too. */
1633 HANDLE main_event;
1634 /* Upon exit from a waiting thread contains the index of the handle that has
1635 * been signaled. The index is an absolute index of the signaled handle in
1636 * the original array. This pointer is shared accross all the waiting threads
1637 * and it's not guaranteed (due to a race condition) that when all the
1638 * waiting threads exit, the value contained here would indicate the first
1639 * handle that was signaled. This is fine, because the caller cares only
1640 * about any handle being signaled. It doesn't care about the order, nor
1641 * about the whole list of handles that were signaled. */
1642 LONG volatile *signaled_index;
1643 /* Array of handles to wait on in a waiting thread. */
1644 HANDLE* handles;
1645 /* Number of handles in 'handles' array to wait on. */
1646 int handles_count;
1647 /* Index inside the main array of the first handle in the 'handles' array. */
1648 int first_handle_index;
1649 /* Waiting thread handle. */
1650 HANDLE thread;
1651} WaitForAllParam;
1652
1653/* Waiting thread routine. */
1654static unsigned __stdcall
1655_in_waiter_thread(void* arg)
1656{
1657 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1658 int res;
1659 WaitForAllParam* const param = (WaitForAllParam*)arg;
1660
1661 /* We have to wait on the main_event in order to be notified when any of the
1662 * sibling threads is exiting. */
1663 wait_on[0] = param->main_event;
1664 /* The rest of the handles go behind the main event handle. */
1665 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1666
1667 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1668 if (res > 0 && res < (param->handles_count + 1)) {
1669 /* One of the original handles got signaled. Save its absolute index into
1670 * the output variable. */
1671 InterlockedCompareExchange(param->signaled_index,
1672 res - 1L + param->first_handle_index, -1L);
1673 }
1674
1675 /* Notify the caller (and the siblings) that the wait is over. */
1676 SetEvent(param->main_event);
1677
1678 _endthreadex(0);
1679 return 0;
1680}
1681
1682/* WaitForMultipeObjects fixer routine.
1683 * Param:
1684 * handles Array of handles to wait on.
1685 * handles_count Number of handles in the array.
1686 * Return:
1687 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1688 * WAIT_FAILED on an error.
1689 */
1690static int
1691_wait_for_all(HANDLE* handles, int handles_count)
1692{
1693 WaitForAllParam* threads;
1694 HANDLE main_event;
1695 int chunks, chunk, remains;
1696
1697 /* This variable is going to be accessed by several threads at the same time,
1698 * this is bound to fail randomly when the core is run on multi-core machines.
1699 * To solve this, we need to do the following (1 _and_ 2):
1700 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1701 * out the reads/writes in this function unexpectedly.
1702 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1703 * all accesses inside a critical section. But we can also use
1704 * InterlockedCompareExchange() which always provide a full memory barrier
1705 * on Win32.
1706 */
1707 volatile LONG sig_index = -1;
1708
1709 /* Calculate number of chunks, and allocate thread param array. */
1710 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1711 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1712 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1713 sizeof(WaitForAllParam));
1714 if (threads == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001715 D("Unable to allocate thread array for %d handles.\n", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001716 return (int)WAIT_FAILED;
1717 }
1718
1719 /* Create main event to wait on for all waiting threads. This is a "manualy
1720 * reset" event that will remain set once it was set. */
1721 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1722 if (main_event == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001723 D("Unable to create main event. Error: %ld\n", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001724 free(threads);
1725 return (int)WAIT_FAILED;
1726 }
1727
1728 /*
1729 * Initialize waiting thread parameters.
1730 */
1731
1732 for (chunk = 0; chunk < chunks; chunk++) {
1733 threads[chunk].main_event = main_event;
1734 threads[chunk].signaled_index = &sig_index;
1735 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1736 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1737 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1738 }
1739 if (remains) {
1740 threads[chunk].main_event = main_event;
1741 threads[chunk].signaled_index = &sig_index;
1742 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1743 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1744 threads[chunk].handles_count = remains;
1745 chunks++;
1746 }
1747
1748 /* Start the waiting threads. */
1749 for (chunk = 0; chunk < chunks; chunk++) {
1750 /* Note that using adb_thread_create is not appropriate here, since we
1751 * need a handle to wait on for thread termination. */
1752 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1753 &threads[chunk], 0, NULL);
1754 if (threads[chunk].thread == NULL) {
1755 /* Unable to create a waiter thread. Collapse. */
Spencer Low5c761bd2015-07-21 02:06:26 -07001756 D("Unable to create a waiting thread %d of %d. errno=%d\n",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001757 chunk, chunks, errno);
1758 chunks = chunk;
1759 SetEvent(main_event);
1760 break;
1761 }
1762 }
1763
1764 /* Wait on any of the threads to get signaled. */
1765 WaitForSingleObject(main_event, INFINITE);
1766
1767 /* Wait on all the waiting threads to exit. */
1768 for (chunk = 0; chunk < chunks; chunk++) {
1769 WaitForSingleObject(threads[chunk].thread, INFINITE);
1770 CloseHandle(threads[chunk].thread);
1771 }
1772
1773 CloseHandle(main_event);
1774 free(threads);
1775
1776
1777 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1778 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1779}
1780
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001781static EventLooperRec win32_looper;
1782
1783static void fdevent_init(void)
1784{
1785 win32_looper.htab_count = 0;
1786 win32_looper.hooks = NULL;
1787}
1788
1789static void fdevent_connect(fdevent *fde)
1790{
1791 EventLooper looper = &win32_looper;
1792 int events = fde->state & FDE_EVENTMASK;
1793
1794 if (events != 0)
1795 event_looper_hook( looper, fde->fd, events );
1796}
1797
1798static void fdevent_disconnect(fdevent *fde)
1799{
1800 EventLooper looper = &win32_looper;
1801 int events = fde->state & FDE_EVENTMASK;
1802
1803 if (events != 0)
1804 event_looper_unhook( looper, fde->fd, events );
1805}
1806
1807static void fdevent_update(fdevent *fde, unsigned events)
1808{
1809 EventLooper looper = &win32_looper;
1810 unsigned events0 = fde->state & FDE_EVENTMASK;
1811
1812 if (events != events0) {
1813 int removes = events0 & ~events;
1814 int adds = events & ~events0;
1815 if (removes) {
1816 D("fdevent_update: remove %x from %d\n", removes, fde->fd);
1817 event_looper_unhook( looper, fde->fd, removes );
1818 }
1819 if (adds) {
1820 D("fdevent_update: add %x to %d\n", adds, fde->fd);
1821 event_looper_hook ( looper, fde->fd, adds );
1822 }
1823 }
1824}
1825
1826static void fdevent_process()
1827{
1828 EventLooper looper = &win32_looper;
1829 EventHook hook;
1830 int gotone = 0;
1831
1832 /* if we have at least one ready hook, execute it/them */
1833 for (hook = looper->hooks; hook; hook = hook->next) {
1834 hook->ready = 0;
1835 if (hook->prepare) {
1836 hook->prepare(hook);
1837 if (hook->ready != 0) {
1838 event_hook_signal( hook );
1839 gotone = 1;
1840 }
1841 }
1842 }
1843
1844 /* nothing's ready yet, so wait for something to happen */
1845 if (!gotone)
1846 {
1847 looper->htab_count = 0;
1848
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001849 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001850 {
1851 if (hook->start && !hook->start(hook)) {
1852 D( "fdevent_process: error when starting a hook\n" );
1853 return;
1854 }
1855 if (hook->h != INVALID_HANDLE_VALUE) {
1856 int nn;
1857
1858 for (nn = 0; nn < looper->htab_count; nn++)
1859 {
1860 if ( looper->htab[nn] == hook->h )
1861 goto DontAdd;
1862 }
1863 looper->htab[ looper->htab_count++ ] = hook->h;
1864 DontAdd:
1865 ;
1866 }
1867 }
1868
1869 if (looper->htab_count == 0) {
1870 D( "fdevent_process: nothing to wait for !!\n" );
1871 return;
1872 }
1873
1874 do
1875 {
1876 int wait_ret;
1877
1878 D( "adb_win32: waiting for %d events\n", looper->htab_count );
1879 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001880 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
1881 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1882 } else {
1883 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001884 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001885 if (wait_ret == (int)WAIT_FAILED) {
1886 D( "adb_win32: wait failed, error %ld\n", GetLastError() );
1887 } else {
1888 D( "adb_win32: got one (index %d)\n", wait_ret );
1889
1890 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1891 * like mouse movements. we need to filter these with the "check" function
1892 */
1893 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1894 {
1895 for (hook = looper->hooks; hook; hook = hook->next)
1896 {
1897 if ( looper->htab[wait_ret] == hook->h &&
1898 (!hook->check || hook->check(hook)) )
1899 {
1900 D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
1901 event_hook_signal( hook );
1902 gotone = 1;
1903 break;
1904 }
1905 }
1906 }
1907 }
1908 }
1909 while (!gotone);
1910
1911 for (hook = looper->hooks; hook; hook = hook->next) {
1912 if (hook->stop)
1913 hook->stop( hook );
1914 }
1915 }
1916
1917 for (hook = looper->hooks; hook; hook = hook->next) {
1918 if (hook->peek && hook->peek(hook))
1919 event_hook_signal( hook );
1920 }
1921}
1922
1923
1924static void fdevent_register(fdevent *fde)
1925{
1926 int fd = fde->fd - WIN32_FH_BASE;
1927
1928 if(fd < 0) {
1929 FATAL("bogus negative fd (%d)\n", fde->fd);
1930 }
1931
1932 if(fd >= fd_table_max) {
1933 int oldmax = fd_table_max;
1934 if(fde->fd > 32000) {
1935 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1936 }
1937 if(fd_table_max == 0) {
1938 fdevent_init();
1939 fd_table_max = 256;
1940 }
1941 while(fd_table_max <= fd) {
1942 fd_table_max *= 2;
1943 }
Elliott Hughes6a096932015-04-16 16:47:02 -07001944 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001945 if(fd_table == 0) {
1946 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1947 }
1948 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
1949 }
1950
1951 fd_table[fd] = fde;
1952}
1953
1954static void fdevent_unregister(fdevent *fde)
1955{
1956 int fd = fde->fd - WIN32_FH_BASE;
1957
1958 if((fd < 0) || (fd >= fd_table_max)) {
1959 FATAL("fd out of range (%d)\n", fde->fd);
1960 }
1961
1962 if(fd_table[fd] != fde) {
1963 FATAL("fd_table out of sync");
1964 }
1965
1966 fd_table[fd] = 0;
1967
1968 if(!(fde->state & FDE_DONT_CLOSE)) {
1969 dump_fde(fde, "close");
1970 adb_close(fde->fd);
1971 }
1972}
1973
1974static void fdevent_plist_enqueue(fdevent *node)
1975{
1976 fdevent *list = &list_pending;
1977
1978 node->next = list;
1979 node->prev = list->prev;
1980 node->prev->next = node;
1981 list->prev = node;
1982}
1983
1984static void fdevent_plist_remove(fdevent *node)
1985{
1986 node->prev->next = node->next;
1987 node->next->prev = node->prev;
1988 node->next = 0;
1989 node->prev = 0;
1990}
1991
1992static fdevent *fdevent_plist_dequeue(void)
1993{
1994 fdevent *list = &list_pending;
1995 fdevent *node = list->next;
1996
1997 if(node == list) return 0;
1998
1999 list->next = node->next;
2000 list->next->prev = list;
2001 node->next = 0;
2002 node->prev = 0;
2003
2004 return node;
2005}
2006
2007fdevent *fdevent_create(int fd, fd_func func, void *arg)
2008{
2009 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2010 if(fde == 0) return 0;
2011 fdevent_install(fde, fd, func, arg);
2012 fde->state |= FDE_CREATED;
2013 return fde;
2014}
2015
2016void fdevent_destroy(fdevent *fde)
2017{
2018 if(fde == 0) return;
2019 if(!(fde->state & FDE_CREATED)) {
2020 FATAL("fde %p not created by fdevent_create()\n", fde);
2021 }
2022 fdevent_remove(fde);
2023}
2024
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002025void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002026{
2027 memset(fde, 0, sizeof(fdevent));
2028 fde->state = FDE_ACTIVE;
2029 fde->fd = fd;
2030 fde->func = func;
2031 fde->arg = arg;
2032
2033 fdevent_register(fde);
2034 dump_fde(fde, "connect");
2035 fdevent_connect(fde);
2036 fde->state |= FDE_ACTIVE;
2037}
2038
2039void fdevent_remove(fdevent *fde)
2040{
2041 if(fde->state & FDE_PENDING) {
2042 fdevent_plist_remove(fde);
2043 }
2044
2045 if(fde->state & FDE_ACTIVE) {
2046 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002047 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002048 fdevent_unregister(fde);
2049 }
2050
2051 fde->state = 0;
2052 fde->events = 0;
2053}
2054
2055
2056void fdevent_set(fdevent *fde, unsigned events)
2057{
2058 events &= FDE_EVENTMASK;
2059
2060 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2061
2062 if(fde->state & FDE_ACTIVE) {
2063 fdevent_update(fde, events);
2064 dump_fde(fde, "update");
2065 }
2066
2067 fde->state = (fde->state & FDE_STATEMASK) | events;
2068
2069 if(fde->state & FDE_PENDING) {
2070 /* if we're pending, make sure
2071 ** we don't signal an event that
2072 ** is no longer wanted.
2073 */
2074 fde->events &= (~events);
2075 if(fde->events == 0) {
2076 fdevent_plist_remove(fde);
2077 fde->state &= (~FDE_PENDING);
2078 }
2079 }
2080}
2081
2082void fdevent_add(fdevent *fde, unsigned events)
2083{
2084 fdevent_set(
2085 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2086}
2087
2088void fdevent_del(fdevent *fde, unsigned events)
2089{
2090 fdevent_set(
2091 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2092}
2093
2094void fdevent_loop()
2095{
2096 fdevent *fde;
2097
2098 for(;;) {
2099#if DEBUG
2100 fprintf(stderr,"--- ---- waiting for events\n");
2101#endif
2102 fdevent_process();
2103
2104 while((fde = fdevent_plist_dequeue())) {
2105 unsigned events = fde->events;
2106 fde->events = 0;
2107 fde->state &= (~FDE_PENDING);
2108 dump_fde(fde, "callback");
2109 fde->func(fde->fd, events, fde->arg);
2110 }
2111 }
2112}
2113
2114/** FILE EVENT HOOKS
2115 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002116
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002117static void _event_file_prepare( EventHook hook )
2118{
2119 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2120 /* we can always read/write */
2121 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2122 }
2123}
2124
2125static int _event_file_peek( EventHook hook )
2126{
2127 return (hook->wanted & (FDE_READ|FDE_WRITE));
2128}
2129
2130static void _fh_file_hook( FH f, int events, EventHook hook )
2131{
2132 hook->h = f->fh_handle;
2133 hook->prepare = _event_file_prepare;
2134 hook->peek = _event_file_peek;
2135}
2136
2137/** SOCKET EVENT HOOKS
2138 **/
2139
2140static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2141{
2142 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2143 if (hook->wanted & FDE_READ)
2144 hook->ready |= FDE_READ;
2145 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2146 hook->ready |= FDE_ERROR;
2147 }
2148 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2149 if (hook->wanted & FDE_WRITE)
2150 hook->ready |= FDE_WRITE;
2151 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2152 hook->ready |= FDE_ERROR;
2153 }
2154 if ( evts->lNetworkEvents & FD_OOB ) {
2155 if (hook->wanted & FDE_ERROR)
2156 hook->ready |= FDE_ERROR;
2157 }
2158}
2159
2160static void _event_socket_prepare( EventHook hook )
2161{
2162 WSANETWORKEVENTS evts;
2163
2164 /* look if some of the events we want already happened ? */
2165 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2166 _event_socket_verify( hook, &evts );
2167}
2168
2169static int _socket_wanted_to_flags( int wanted )
2170{
2171 int flags = 0;
2172 if (wanted & FDE_READ)
2173 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2174
2175 if (wanted & FDE_WRITE)
2176 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2177
2178 if (wanted & FDE_ERROR)
2179 flags |= FD_OOB;
2180
2181 return flags;
2182}
2183
2184static int _event_socket_start( EventHook hook )
2185{
2186 /* create an event which we're going to wait for */
2187 FH fh = hook->fh;
2188 long flags = _socket_wanted_to_flags( hook->wanted );
2189
2190 hook->h = fh->event;
2191 if (hook->h == INVALID_HANDLE_VALUE) {
2192 D( "_event_socket_start: no event for %s\n", fh->name );
2193 return 0;
2194 }
2195
2196 if ( flags != fh->mask ) {
2197 D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
2198 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
2199 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
2200 CloseHandle( hook->h );
2201 hook->h = INVALID_HANDLE_VALUE;
2202 exit(1);
2203 return 0;
2204 }
2205 fh->mask = flags;
2206 }
2207 return 1;
2208}
2209
2210static void _event_socket_stop( EventHook hook )
2211{
2212 hook->h = INVALID_HANDLE_VALUE;
2213}
2214
2215static int _event_socket_check( EventHook hook )
2216{
2217 int result = 0;
2218 FH fh = hook->fh;
2219 WSANETWORKEVENTS evts;
2220
2221 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2222 _event_socket_verify( hook, &evts );
2223 result = (hook->ready != 0);
2224 if (result) {
2225 ResetEvent( hook->h );
2226 }
2227 }
2228 D( "_event_socket_check %s returns %d\n", fh->name, result );
2229 return result;
2230}
2231
2232static int _event_socket_peek( EventHook hook )
2233{
2234 WSANETWORKEVENTS evts;
2235 FH fh = hook->fh;
2236
2237 /* look if some of the events we want already happened ? */
2238 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2239 _event_socket_verify( hook, &evts );
2240 if (hook->ready)
2241 ResetEvent( hook->h );
2242 }
2243
2244 return hook->ready != 0;
2245}
2246
2247
2248
2249static void _fh_socket_hook( FH f, int events, EventHook hook )
2250{
2251 hook->prepare = _event_socket_prepare;
2252 hook->start = _event_socket_start;
2253 hook->stop = _event_socket_stop;
2254 hook->check = _event_socket_check;
2255 hook->peek = _event_socket_peek;
2256
Spencer Low753d4852015-07-30 23:07:55 -07002257 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002258 _event_socket_start( hook );
2259}
2260
2261/** SOCKETPAIR EVENT HOOKS
2262 **/
2263
2264static void _event_socketpair_prepare( EventHook hook )
2265{
2266 FH fh = hook->fh;
2267 SocketPair pair = fh->fh_pair;
2268 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2269 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2270
2271 if (hook->wanted & FDE_READ && rbip->can_read)
2272 hook->ready |= FDE_READ;
2273
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002274 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002275 hook->ready |= FDE_WRITE;
2276 }
2277
2278 static int _event_socketpair_start( EventHook hook )
2279 {
2280 FH fh = hook->fh;
2281 SocketPair pair = fh->fh_pair;
2282 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2283 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2284
2285 if (hook->wanted == FDE_READ)
2286 hook->h = rbip->evt_read;
2287
2288 else if (hook->wanted == FDE_WRITE)
2289 hook->h = wbip->evt_write;
2290
2291 else {
2292 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
2293 return 0;
2294 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002295 D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002296 hook->fh->name, _fh_to_int(fh), hook->wanted);
2297 return 1;
2298}
2299
2300static int _event_socketpair_peek( EventHook hook )
2301{
2302 _event_socketpair_prepare( hook );
2303 return hook->ready != 0;
2304}
2305
2306static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2307{
2308 hook->prepare = _event_socketpair_prepare;
2309 hook->start = _event_socketpair_start;
2310 hook->peek = _event_socketpair_peek;
2311}
2312
2313
2314void
2315adb_sysdeps_init( void )
2316{
2317#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2318#include "mutex_list.h"
2319 InitializeCriticalSection( &_win32_lock );
2320}
2321
Spencer Lowbeb61982015-03-01 15:06:21 -08002322/**************************************************************************/
2323/**************************************************************************/
2324/***** *****/
2325/***** Console Window Terminal Emulation *****/
2326/***** *****/
2327/**************************************************************************/
2328/**************************************************************************/
2329
2330// This reads input from a Win32 console window and translates it into Unix
2331// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2332// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2333// is emulated instead of xterm because it is probably more popular than xterm:
2334// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2335// supports modern fonts, etc. It seems best to emulate the terminal that most
2336// Android developers use because they'll fix apps (the shell, etc.) to keep
2337// working with that terminal's emulation.
2338//
2339// The point of this emulation is not to be perfect or to solve all issues with
2340// console windows on Windows, but to be better than the original code which
2341// just called read() (which called ReadFile(), which called ReadConsoleA())
2342// which did not support Ctrl-C, tab completion, shell input line editing
2343// keys, server echo, and more.
2344//
2345// This implementation reconfigures the console with SetConsoleMode(), then
2346// calls ReadConsoleInput() to get raw input which it remaps to Unix
2347// terminal-style sequences which is returned via unix_read() which is used
2348// by the 'adb shell' command.
2349//
2350// Code organization:
2351//
2352// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2353// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2354// * _console_read() is the main code of the emulation.
2355
2356
2357// Read an input record from the console; one that should be processed.
2358static bool _get_interesting_input_record_uncached(const HANDLE console,
2359 INPUT_RECORD* const input_record) {
2360 for (;;) {
2361 DWORD read_count = 0;
2362 memset(input_record, 0, sizeof(*input_record));
2363 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2364 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
Spencer Low1711e012015-08-02 18:50:17 -07002365 "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002366 errno = EIO;
2367 return false;
2368 }
2369
2370 if (read_count == 0) { // should be impossible
2371 fatal("ReadConsoleInputA returned 0");
2372 }
2373
2374 if (read_count != 1) { // should be impossible
2375 fatal("ReadConsoleInputA did not return one input record");
2376 }
2377
2378 if ((input_record->EventType == KEY_EVENT) &&
2379 (input_record->Event.KeyEvent.bKeyDown)) {
2380 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2381 fatal("ReadConsoleInputA returned a key event with zero repeat"
2382 " count");
2383 }
2384
2385 // Got an interesting INPUT_RECORD, so return
2386 return true;
2387 }
2388 }
2389}
2390
2391// Cached input record (in case _console_read() is passed a buffer that doesn't
2392// have enough space to fit wRepeatCount number of key sequences). A non-zero
2393// wRepeatCount indicates that a record is cached.
2394static INPUT_RECORD _win32_input_record;
2395
2396// Get the next KEY_EVENT_RECORD that should be processed.
2397static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2398 // If nothing cached, read directly from the console until we get an
2399 // interesting record.
2400 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2401 if (!_get_interesting_input_record_uncached(console,
2402 &_win32_input_record)) {
2403 // There was an error, so make sure wRepeatCount is zero because
2404 // that signifies no cached input record.
2405 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2406 return NULL;
2407 }
2408 }
2409
2410 return &_win32_input_record.Event.KeyEvent;
2411}
2412
2413static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2414 return (control_key_state & SHIFT_PRESSED) != 0;
2415}
2416
2417static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2418 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2419}
2420
2421static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2422 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2423}
2424
2425static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2426 return (control_key_state & NUMLOCK_ON) != 0;
2427}
2428
2429static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2430 return (control_key_state & CAPSLOCK_ON) != 0;
2431}
2432
2433static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2434 return (control_key_state & ENHANCED_KEY) != 0;
2435}
2436
2437// Constants from MSDN for ToAscii().
2438static const BYTE TOASCII_KEY_OFF = 0x00;
2439static const BYTE TOASCII_KEY_DOWN = 0x80;
2440static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2441
2442// Given a key event, ignore a modifier key and return the character that was
2443// entered without the modifier. Writes to *ch and returns the number of bytes
2444// written.
2445static size_t _get_char_ignoring_modifier(char* const ch,
2446 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2447 const WORD modifier) {
2448 // If there is no character from Windows, try ignoring the specified
2449 // modifier and look for a character. Note that if AltGr is being used,
2450 // there will be a character from Windows.
2451 if (key_event->uChar.AsciiChar == '\0') {
2452 // Note that we read the control key state from the passed in argument
2453 // instead of from key_event since the argument has been normalized.
2454 if (((modifier == VK_SHIFT) &&
2455 _is_shift_pressed(control_key_state)) ||
2456 ((modifier == VK_CONTROL) &&
2457 _is_ctrl_pressed(control_key_state)) ||
2458 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2459
2460 BYTE key_state[256] = {0};
2461 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2462 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2463 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2464 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2465 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2466 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2467 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2468 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2469
2470 // cause this modifier to be ignored
2471 key_state[modifier] = TOASCII_KEY_OFF;
2472
2473 WORD translated = 0;
2474 if (ToAscii(key_event->wVirtualKeyCode,
2475 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2476 // Ignoring the modifier, we found a character.
2477 *ch = (CHAR)translated;
2478 return 1;
2479 }
2480 }
2481 }
2482
2483 // Just use whatever Windows told us originally.
2484 *ch = key_event->uChar.AsciiChar;
2485
2486 // If the character from Windows is NULL, return a size of zero.
2487 return (*ch == '\0') ? 0 : 1;
2488}
2489
2490// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2491// but taking into account the shift key. This is because for a sequence like
2492// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2493// we want to find the character ')'.
2494//
2495// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2496// because it is the default key-sequence to switch the input language.
2497// This is configurable in the Region and Language control panel.
2498static __inline__ size_t _get_non_control_char(char* const ch,
2499 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2500 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2501 VK_CONTROL);
2502}
2503
2504// Get without Alt.
2505static __inline__ size_t _get_non_alt_char(char* const ch,
2506 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2507 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2508 VK_MENU);
2509}
2510
2511// Ignore the control key, find the character from Windows, and apply any
2512// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2513// *pch and returns number of bytes written.
2514static size_t _get_control_character(char* const pch,
2515 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2516 const size_t len = _get_non_control_char(pch, key_event,
2517 control_key_state);
2518
2519 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2520 char ch = *pch;
2521 switch (ch) {
2522 case '2':
2523 case '@':
2524 case '`':
2525 ch = '\0';
2526 break;
2527 case '3':
2528 case '[':
2529 case '{':
2530 ch = '\x1b';
2531 break;
2532 case '4':
2533 case '\\':
2534 case '|':
2535 ch = '\x1c';
2536 break;
2537 case '5':
2538 case ']':
2539 case '}':
2540 ch = '\x1d';
2541 break;
2542 case '6':
2543 case '^':
2544 case '~':
2545 ch = '\x1e';
2546 break;
2547 case '7':
2548 case '-':
2549 case '_':
2550 ch = '\x1f';
2551 break;
2552 case '8':
2553 ch = '\x7f';
2554 break;
2555 case '/':
2556 if (!_is_alt_pressed(control_key_state)) {
2557 ch = '\x1f';
2558 }
2559 break;
2560 case '?':
2561 if (!_is_alt_pressed(control_key_state)) {
2562 ch = '\x7f';
2563 }
2564 break;
2565 }
2566 *pch = ch;
2567 }
2568
2569 return len;
2570}
2571
2572static DWORD _normalize_altgr_control_key_state(
2573 const KEY_EVENT_RECORD* const key_event) {
2574 DWORD control_key_state = key_event->dwControlKeyState;
2575
2576 // If we're in an AltGr situation where the AltGr key is down (depending on
2577 // the keyboard layout, that might be the physical right alt key which
2578 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2579 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2580 // a character (which indicates that there was an AltGr mapping), then act
2581 // as if alt and control are not really down for the purposes of modifiers.
2582 // This makes it so that if the user with, say, a German keyboard layout
2583 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2584 // output the key and we don't see the Alt and Ctrl keys.
2585 if (_is_ctrl_pressed(control_key_state) &&
2586 _is_alt_pressed(control_key_state)
2587 && (key_event->uChar.AsciiChar != '\0')) {
2588 // Try to remove as few bits as possible to improve our chances of
2589 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2590 // Left-Alt + Right-Ctrl + AltGr.
2591 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2592 // Remove Right-Alt.
2593 control_key_state &= ~RIGHT_ALT_PRESSED;
2594 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2595 // pressed, Left-Ctrl is almost always set, except if the user
2596 // presses Right-Ctrl, then AltGr (in that specific order) for
2597 // whatever reason. At any rate, make sure the bit is not set.
2598 control_key_state &= ~LEFT_CTRL_PRESSED;
2599 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2600 // Remove Left-Alt.
2601 control_key_state &= ~LEFT_ALT_PRESSED;
2602 // Whichever Ctrl key is down, remove it from the state. We only
2603 // remove one key, to improve our chances of detecting the
2604 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2605 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2606 // Remove Left-Ctrl.
2607 control_key_state &= ~LEFT_CTRL_PRESSED;
2608 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2609 // Remove Right-Ctrl.
2610 control_key_state &= ~RIGHT_CTRL_PRESSED;
2611 }
2612 }
2613
2614 // Note that this logic isn't 100% perfect because Windows doesn't
2615 // allow us to detect all combinations because a physical AltGr key
2616 // press shows up as two bits, plus some combinations are ambiguous
2617 // about what is actually physically pressed.
2618 }
2619
2620 return control_key_state;
2621}
2622
2623// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2624// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2625// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2626// appropriately.
2627static DWORD _normalize_keypad_control_key_state(const WORD vk,
2628 const DWORD control_key_state) {
2629 if (!_is_numlock_on(control_key_state)) {
2630 return control_key_state;
2631 }
2632 if (!_is_enhanced_key(control_key_state)) {
2633 switch (vk) {
2634 case VK_INSERT: // 0
2635 case VK_DELETE: // .
2636 case VK_END: // 1
2637 case VK_DOWN: // 2
2638 case VK_NEXT: // 3
2639 case VK_LEFT: // 4
2640 case VK_CLEAR: // 5
2641 case VK_RIGHT: // 6
2642 case VK_HOME: // 7
2643 case VK_UP: // 8
2644 case VK_PRIOR: // 9
2645 return control_key_state | SHIFT_PRESSED;
2646 }
2647 }
2648
2649 return control_key_state;
2650}
2651
2652static const char* _get_keypad_sequence(const DWORD control_key_state,
2653 const char* const normal, const char* const shifted) {
2654 if (_is_shift_pressed(control_key_state)) {
2655 // Shift is pressed and NumLock is off
2656 return shifted;
2657 } else {
2658 // Shift is not pressed and NumLock is off, or,
2659 // Shift is pressed and NumLock is on, in which case we want the
2660 // NumLock and Shift to neutralize each other, thus, we want the normal
2661 // sequence.
2662 return normal;
2663 }
2664 // If Shift is not pressed and NumLock is on, a different virtual key code
2665 // is returned by Windows, which can be taken care of by a different case
2666 // statement in _console_read().
2667}
2668
2669// Write sequence to buf and return the number of bytes written.
2670static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2671 DWORD control_key_state, const char* const normal) {
2672 // Copy the base sequence into buf.
2673 const size_t len = strlen(normal);
2674 memcpy(buf, normal, len);
2675
2676 int code = 0;
2677
2678 control_key_state = _normalize_keypad_control_key_state(vk,
2679 control_key_state);
2680
2681 if (_is_shift_pressed(control_key_state)) {
2682 code |= 0x1;
2683 }
2684 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2685 code |= 0x2;
2686 }
2687 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2688 code |= 0x4;
2689 }
2690 // If some modifier was held down, then we need to insert the modifier code
2691 if (code != 0) {
2692 if (len == 0) {
2693 // Should be impossible because caller should pass a string of
2694 // non-zero length.
2695 return 0;
2696 }
2697 size_t index = len - 1;
2698 const char lastChar = buf[index];
2699 if (lastChar != '~') {
2700 buf[index++] = '1';
2701 }
2702 buf[index++] = ';'; // modifier separator
2703 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2704 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2705 buf[index++] = '1' + code;
2706 buf[index++] = lastChar; // move ~ (or other last char) to the end
2707 return index;
2708 }
2709 return len;
2710}
2711
2712// Write sequence to buf and return the number of bytes written.
2713static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2714 const DWORD control_key_state, const char* const normal,
2715 const char shifted) {
2716 if (_is_shift_pressed(control_key_state)) {
2717 // Shift is pressed and NumLock is off
2718 if (shifted != '\0') {
2719 buf[0] = shifted;
2720 return sizeof(buf[0]);
2721 } else {
2722 return 0;
2723 }
2724 } else {
2725 // Shift is not pressed and NumLock is off, or,
2726 // Shift is pressed and NumLock is on, in which case we want the
2727 // NumLock and Shift to neutralize each other, thus, we want the normal
2728 // sequence.
2729 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2730 }
2731 // If Shift is not pressed and NumLock is on, a different virtual key code
2732 // is returned by Windows, which can be taken care of by a different case
2733 // statement in _console_read().
2734}
2735
2736// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2737// Standard German. Figure this out at runtime so we know what to output for
2738// Shift-VK_DELETE.
2739static char _get_decimal_char() {
2740 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2741}
2742
2743// Prefix the len bytes in buf with the escape character, and then return the
2744// new buffer length.
2745size_t _escape_prefix(char* const buf, const size_t len) {
2746 // If nothing to prefix, don't do anything. We might be called with
2747 // len == 0, if alt was held down with a dead key which produced nothing.
2748 if (len == 0) {
2749 return 0;
2750 }
2751
2752 memmove(&buf[1], buf, len);
2753 buf[0] = '\x1b';
2754 return len + 1;
2755}
2756
2757// Writes to buffer buf (of length len), returning number of bytes written or
2758// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2759// (as far as I can tell).
2760static int _console_read(const HANDLE console, void* buf, size_t len) {
2761 for (;;) {
2762 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2763 if (key_event == NULL) {
2764 return -1;
2765 }
2766
2767 const WORD vk = key_event->wVirtualKeyCode;
2768 const CHAR ch = key_event->uChar.AsciiChar;
2769 const DWORD control_key_state = _normalize_altgr_control_key_state(
2770 key_event);
2771
2772 // The following emulation code should write the output sequence to
2773 // either seqstr or to seqbuf and seqbuflen.
2774 const char* seqstr = NULL; // NULL terminated C-string
2775 // Enough space for max sequence string below, plus modifiers and/or
2776 // escape prefix.
2777 char seqbuf[16];
2778 size_t seqbuflen = 0; // Space used in seqbuf.
2779
2780#define MATCH(vk, normal) \
2781 case (vk): \
2782 { \
2783 seqstr = (normal); \
2784 } \
2785 break;
2786
2787 // Modifier keys should affect the output sequence.
2788#define MATCH_MODIFIER(vk, normal) \
2789 case (vk): \
2790 { \
2791 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2792 control_key_state, (normal)); \
2793 } \
2794 break;
2795
2796 // The shift key should affect the output sequence.
2797#define MATCH_KEYPAD(vk, normal, shifted) \
2798 case (vk): \
2799 { \
2800 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2801 (shifted)); \
2802 } \
2803 break;
2804
2805 // The shift key and other modifier keys should affect the output
2806 // sequence.
2807#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2808 case (vk): \
2809 { \
2810 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2811 control_key_state, (normal), (shifted)); \
2812 } \
2813 break;
2814
2815#define ESC "\x1b"
2816#define CSI ESC "["
2817#define SS3 ESC "O"
2818
2819 // Only support normal mode, not application mode.
2820
2821 // Enhanced keys:
2822 // * 6-pack: insert, delete, home, end, page up, page down
2823 // * cursor keys: up, down, right, left
2824 // * keypad: divide, enter
2825 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2826 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2827 if (_is_enhanced_key(control_key_state)) {
2828 switch (vk) {
2829 case VK_RETURN: // Enter key on keypad
2830 if (_is_ctrl_pressed(control_key_state)) {
2831 seqstr = "\n";
2832 } else {
2833 seqstr = "\r";
2834 }
2835 break;
2836
2837 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2838 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2839
2840 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2841 // will be fixed soon to match xterm which sends CSI "F" and
2842 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2843 MATCH(VK_END, CSI "F");
2844 MATCH(VK_HOME, CSI "H");
2845
2846 MATCH_MODIFIER(VK_LEFT, CSI "D");
2847 MATCH_MODIFIER(VK_UP, CSI "A");
2848 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2849 MATCH_MODIFIER(VK_DOWN, CSI "B");
2850
2851 MATCH_MODIFIER(VK_INSERT, CSI "2~");
2852 MATCH_MODIFIER(VK_DELETE, CSI "3~");
2853
2854 MATCH(VK_DIVIDE, "/");
2855 }
2856 } else { // Non-enhanced keys:
2857 switch (vk) {
2858 case VK_BACK: // backspace
2859 if (_is_alt_pressed(control_key_state)) {
2860 seqstr = ESC "\x7f";
2861 } else {
2862 seqstr = "\x7f";
2863 }
2864 break;
2865
2866 case VK_TAB:
2867 if (_is_shift_pressed(control_key_state)) {
2868 seqstr = CSI "Z";
2869 } else {
2870 seqstr = "\t";
2871 }
2872 break;
2873
2874 // Number 5 key in keypad when NumLock is off, or if NumLock is
2875 // on and Shift is down.
2876 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2877
2878 case VK_RETURN: // Enter key on main keyboard
2879 if (_is_alt_pressed(control_key_state)) {
2880 seqstr = ESC "\n";
2881 } else if (_is_ctrl_pressed(control_key_state)) {
2882 seqstr = "\n";
2883 } else {
2884 seqstr = "\r";
2885 }
2886 break;
2887
2888 // VK_ESCAPE: Don't do any special handling. The OS uses many
2889 // of the sequences with Escape and many of the remaining
2890 // sequences don't produce bKeyDown messages, only !bKeyDown
2891 // for whatever reason.
2892
2893 case VK_SPACE:
2894 if (_is_alt_pressed(control_key_state)) {
2895 seqstr = ESC " ";
2896 } else if (_is_ctrl_pressed(control_key_state)) {
2897 seqbuf[0] = '\0'; // NULL char
2898 seqbuflen = 1;
2899 } else {
2900 seqstr = " ";
2901 }
2902 break;
2903
2904 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2905 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
2906
2907 MATCH_KEYPAD(VK_END, CSI "4~", "1");
2908 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2909
2910 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
2911 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
2912 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2913 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
2914
2915 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2916 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2917 _get_decimal_char());
2918
2919 case 0x30: // 0
2920 case 0x31: // 1
2921 case 0x39: // 9
2922 case VK_OEM_1: // ;:
2923 case VK_OEM_PLUS: // =+
2924 case VK_OEM_COMMA: // ,<
2925 case VK_OEM_PERIOD: // .>
2926 case VK_OEM_7: // '"
2927 case VK_OEM_102: // depends on keyboard, could be <> or \|
2928 case VK_OEM_2: // /?
2929 case VK_OEM_3: // `~
2930 case VK_OEM_4: // [{
2931 case VK_OEM_5: // \|
2932 case VK_OEM_6: // ]}
2933 {
2934 seqbuflen = _get_control_character(seqbuf, key_event,
2935 control_key_state);
2936
2937 if (_is_alt_pressed(control_key_state)) {
2938 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2939 }
2940 }
2941 break;
2942
2943 case 0x32: // 2
2944 case 0x36: // 6
2945 case VK_OEM_MINUS: // -_
2946 {
2947 seqbuflen = _get_control_character(seqbuf, key_event,
2948 control_key_state);
2949
2950 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2951 // prefix with escape.
2952 if (_is_alt_pressed(control_key_state) &&
2953 !(_is_ctrl_pressed(control_key_state) &&
2954 !_is_shift_pressed(control_key_state))) {
2955 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2956 }
2957 }
2958 break;
2959
2960 case 0x33: // 3
2961 case 0x34: // 4
2962 case 0x35: // 5
2963 case 0x37: // 7
2964 case 0x38: // 8
2965 {
2966 seqbuflen = _get_control_character(seqbuf, key_event,
2967 control_key_state);
2968
2969 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2970 // prefix with escape.
2971 if (_is_alt_pressed(control_key_state) &&
2972 !(_is_ctrl_pressed(control_key_state) &&
2973 !_is_shift_pressed(control_key_state))) {
2974 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2975 }
2976 }
2977 break;
2978
2979 case 0x41: // a
2980 case 0x42: // b
2981 case 0x43: // c
2982 case 0x44: // d
2983 case 0x45: // e
2984 case 0x46: // f
2985 case 0x47: // g
2986 case 0x48: // h
2987 case 0x49: // i
2988 case 0x4a: // j
2989 case 0x4b: // k
2990 case 0x4c: // l
2991 case 0x4d: // m
2992 case 0x4e: // n
2993 case 0x4f: // o
2994 case 0x50: // p
2995 case 0x51: // q
2996 case 0x52: // r
2997 case 0x53: // s
2998 case 0x54: // t
2999 case 0x55: // u
3000 case 0x56: // v
3001 case 0x57: // w
3002 case 0x58: // x
3003 case 0x59: // y
3004 case 0x5a: // z
3005 {
3006 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3007 control_key_state);
3008
3009 // If Alt is pressed, then prefix with escape.
3010 if (_is_alt_pressed(control_key_state)) {
3011 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3012 }
3013 }
3014 break;
3015
3016 // These virtual key codes are generated by the keys on the
3017 // keypad *when NumLock is on* and *Shift is up*.
3018 MATCH(VK_NUMPAD0, "0");
3019 MATCH(VK_NUMPAD1, "1");
3020 MATCH(VK_NUMPAD2, "2");
3021 MATCH(VK_NUMPAD3, "3");
3022 MATCH(VK_NUMPAD4, "4");
3023 MATCH(VK_NUMPAD5, "5");
3024 MATCH(VK_NUMPAD6, "6");
3025 MATCH(VK_NUMPAD7, "7");
3026 MATCH(VK_NUMPAD8, "8");
3027 MATCH(VK_NUMPAD9, "9");
3028
3029 MATCH(VK_MULTIPLY, "*");
3030 MATCH(VK_ADD, "+");
3031 MATCH(VK_SUBTRACT, "-");
3032 // VK_DECIMAL is generated by the . key on the keypad *when
3033 // NumLock is on* and *Shift is up* and the sequence is not
3034 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3035 // Windows Security screen to come up).
3036 case VK_DECIMAL:
3037 // U.S. English uses '.', Germany German uses ','.
3038 seqbuflen = _get_non_control_char(seqbuf, key_event,
3039 control_key_state);
3040 break;
3041
3042 MATCH_MODIFIER(VK_F1, SS3 "P");
3043 MATCH_MODIFIER(VK_F2, SS3 "Q");
3044 MATCH_MODIFIER(VK_F3, SS3 "R");
3045 MATCH_MODIFIER(VK_F4, SS3 "S");
3046 MATCH_MODIFIER(VK_F5, CSI "15~");
3047 MATCH_MODIFIER(VK_F6, CSI "17~");
3048 MATCH_MODIFIER(VK_F7, CSI "18~");
3049 MATCH_MODIFIER(VK_F8, CSI "19~");
3050 MATCH_MODIFIER(VK_F9, CSI "20~");
3051 MATCH_MODIFIER(VK_F10, CSI "21~");
3052 MATCH_MODIFIER(VK_F11, CSI "23~");
3053 MATCH_MODIFIER(VK_F12, CSI "24~");
3054
3055 MATCH_MODIFIER(VK_F13, CSI "25~");
3056 MATCH_MODIFIER(VK_F14, CSI "26~");
3057 MATCH_MODIFIER(VK_F15, CSI "28~");
3058 MATCH_MODIFIER(VK_F16, CSI "29~");
3059 MATCH_MODIFIER(VK_F17, CSI "31~");
3060 MATCH_MODIFIER(VK_F18, CSI "32~");
3061 MATCH_MODIFIER(VK_F19, CSI "33~");
3062 MATCH_MODIFIER(VK_F20, CSI "34~");
3063
3064 // MATCH_MODIFIER(VK_F21, ???);
3065 // MATCH_MODIFIER(VK_F22, ???);
3066 // MATCH_MODIFIER(VK_F23, ???);
3067 // MATCH_MODIFIER(VK_F24, ???);
3068 }
3069 }
3070
3071#undef MATCH
3072#undef MATCH_MODIFIER
3073#undef MATCH_KEYPAD
3074#undef MATCH_MODIFIER_KEYPAD
3075#undef ESC
3076#undef CSI
3077#undef SS3
3078
3079 const char* out;
3080 size_t outlen;
3081
3082 // Check for output in any of:
3083 // * seqstr is set (and strlen can be used to determine the length).
3084 // * seqbuf and seqbuflen are set
3085 // Fallback to ch from Windows.
3086 if (seqstr != NULL) {
3087 out = seqstr;
3088 outlen = strlen(seqstr);
3089 } else if (seqbuflen > 0) {
3090 out = seqbuf;
3091 outlen = seqbuflen;
3092 } else if (ch != '\0') {
3093 // Use whatever Windows told us it is.
3094 seqbuf[0] = ch;
3095 seqbuflen = 1;
3096 out = seqbuf;
3097 outlen = seqbuflen;
3098 } else {
3099 // No special handling for the virtual key code and Windows isn't
3100 // telling us a character code, then we don't know how to translate
3101 // the key press.
3102 //
3103 // Consume the input and 'continue' to cause us to get a new key
3104 // event.
3105 D("_console_read: unknown virtual key code: %d, enhanced: %s\n",
3106 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3107 key_event->wRepeatCount = 0;
3108 continue;
3109 }
3110
3111 int bytesRead = 0;
3112
3113 // put output wRepeatCount times into buf/len
3114 while (key_event->wRepeatCount > 0) {
3115 if (len >= outlen) {
3116 // Write to buf/len
3117 memcpy(buf, out, outlen);
3118 buf = (void*)((char*)buf + outlen);
3119 len -= outlen;
3120 bytesRead += outlen;
3121
3122 // consume the input
3123 --key_event->wRepeatCount;
3124 } else {
3125 // Not enough space, so just leave it in _win32_input_record
3126 // for a subsequent retrieval.
3127 if (bytesRead == 0) {
3128 // We didn't write anything because there wasn't enough
3129 // space to even write one sequence. This should never
3130 // happen if the caller uses sensible buffer sizes
3131 // (i.e. >= maximum sequence length which is probably a
3132 // few bytes long).
3133 D("_console_read: no buffer space to write one sequence; "
3134 "buffer: %ld, sequence: %ld\n", (long)len,
3135 (long)outlen);
3136 errno = ENOMEM;
3137 return -1;
3138 } else {
3139 // Stop trying to write to buf/len, just return whatever
3140 // we wrote so far.
3141 break;
3142 }
3143 }
3144 }
3145
3146 return bytesRead;
3147 }
3148}
3149
3150static DWORD _old_console_mode; // previous GetConsoleMode() result
3151static HANDLE _console_handle; // when set, console mode should be restored
3152
3153void stdin_raw_init(const int fd) {
3154 if (STDIN_FILENO == fd) {
3155 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3156 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3157 return;
3158 }
3159
3160 if (GetFileType(in) != FILE_TYPE_CHAR) {
3161 // stdin might be a file or pipe.
3162 return;
3163 }
3164
3165 if (!GetConsoleMode(in, &_old_console_mode)) {
3166 // If GetConsoleMode() fails, stdin is probably is not a console.
3167 return;
3168 }
3169
3170 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3171 // calling the process Ctrl-C routine (configured by
3172 // SetConsoleCtrlHandler()).
3173 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3174 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3175 // flag also seems necessary to have proper line-ending processing.
3176 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3177 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3178 // This really should not fail.
Spencer Low1711e012015-08-02 18:50:17 -07003179 D("stdin_raw_init: SetConsoleMode() failed: %s\n",
3180 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003181 }
3182
3183 // Once this is set, it means that stdin has been configured for
3184 // reading from and that the old console mode should be restored later.
3185 _console_handle = in;
3186
3187 // Note that we don't need to configure C Runtime line-ending
3188 // translation because _console_read() does not call the C Runtime to
3189 // read from the console.
3190 }
3191}
3192
3193void stdin_raw_restore(const int fd) {
3194 if (STDIN_FILENO == fd) {
3195 if (_console_handle != NULL) {
3196 const HANDLE in = _console_handle;
3197 _console_handle = NULL; // clear state
3198
3199 if (!SetConsoleMode(in, _old_console_mode)) {
3200 // This really should not fail.
Spencer Low1711e012015-08-02 18:50:17 -07003201 D("stdin_raw_restore: SetConsoleMode() failed: %s\n",
3202 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003203 }
3204 }
3205 }
3206}
3207
Spencer Low3a2421b2015-05-22 20:09:06 -07003208// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003209int unix_read(int fd, void* buf, size_t len) {
3210 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3211 // If it is a request to read from stdin, and stdin_raw_init() has been
3212 // called, and it successfully configured the console, then read from
3213 // the console using Win32 console APIs and partially emulate a unix
3214 // terminal.
3215 return _console_read(_console_handle, buf, len);
3216 } else {
3217 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003218 // can do LF/CR translation (which is overridable with _setmode()).
3219 // Undefine the macro that is set in sysdeps.h which bans calls to
3220 // plain read() in favor of unix_read() or adb_read().
3221#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003222#undef read
3223 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003224#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003225 }
3226}
Spencer Low6815c072015-05-11 01:08:48 -07003227
3228/**************************************************************************/
3229/**************************************************************************/
3230/***** *****/
3231/***** Unicode support *****/
3232/***** *****/
3233/**************************************************************************/
3234/**************************************************************************/
3235
3236// This implements support for using files with Unicode filenames and for
3237// outputting Unicode text to a Win32 console window. This is inspired from
3238// http://utf8everywhere.org/.
3239//
3240// Background
3241// ----------
3242//
3243// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3244// filenames to APIs such as open(). This works because filenames are largely
3245// opaque 'cookies' (perhaps excluding path separators).
3246//
3247// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3248// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3249// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3250// CreateFile() API is really just a macro that adds the W/A based on whether
3251// the UNICODE preprocessor symbol is defined).
3252//
3253// Options
3254// -------
3255//
3256// Thus, to write a portable program, there are a few options:
3257//
3258// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3259// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3260// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3261// open() API.
3262//
3263// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3264// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3265// potentially touching a lot of code.
3266//
3267// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3268// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3269// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3270// or C Runtime API.
3271//
3272// The Choice
3273// ----------
3274//
3275// The code below chooses option 3, the UTF-8 everywhere strategy. It
3276// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3277// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3278// args that are passed to main() at the beginning of program startup. We also
3279// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3280// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3281//
3282// Unicode console output
3283// ----------------------
3284//
3285// The way to output Unicode to a Win32 console window is to call
3286// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003287// such as Lucida Console or Consolas, and in the case of East Asian languages
3288// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3289// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3290// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003291//
3292// The problem is getting the C Runtime to make fprintf and related APIs call
3293// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3294// promising, but the various modes have issues:
3295//
3296// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3297// UTF-16 do not display properly.
3298// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3299// totally wrong.
3300// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3301// handler to be called (upon a later I/O call), aborting the process.
3302// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3303// to output nothing.
3304//
3305// So the only solution is to write our own adb_fprintf() that converts UTF-8
3306// to UTF-16 and then calls WriteConsoleW().
3307
3308
3309// Function prototype because attributes cannot be placed on func definitions.
3310static void _widen_fatal(const char *fmt, ...)
3311 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3312
3313// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3314// called from those functions.
3315static void _widen_fatal(const char *fmt, ...) {
3316 va_list ap;
3317 va_start(ap, fmt);
3318 // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3319 // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3320 // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3321 // By directly calling real C Runtime APIs that don't properly output
3322 // Unicode, but will be able to get a comprehendible message out. To do
3323 // this, make sure we don't call (v)fprintf macros by undefining them.
3324#pragma push_macro("fprintf")
3325#pragma push_macro("vfprintf")
3326#undef fprintf
3327#undef vfprintf
3328 fprintf(stderr, "error: ");
3329 vfprintf(stderr, fmt, ap);
3330 fprintf(stderr, "\n");
3331#pragma pop_macro("vfprintf")
3332#pragma pop_macro("fprintf")
3333 va_end(ap);
3334 exit(-1);
3335}
3336
3337// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3338// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3339
3340// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3341// string. Any other size specifies the number of chars to convert, excluding
3342// any NULL terminator (if you're passing an explicit size, you probably don't
3343// have a NULL terminated string in the first place).
3344std::wstring widen(const char* utf8, const int size) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003345 // Note: Do not call SystemErrorCodeToString() from widen() because
3346 // SystemErrorCodeToString() calls narrow() which may call fatal() which
3347 // calls adb_vfprintf() which calls widen(), potentially causing infinite
3348 // recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003349 const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3350 NULL, 0);
3351 if (chars_to_convert <= 0) {
3352 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3353 _widen_fatal("MultiByteToWideChar failed counting: %d, "
3354 "GetLastError: %lu", chars_to_convert, GetLastError());
3355 }
3356
3357 std::wstring utf16;
3358 size_t chars_to_allocate = chars_to_convert;
3359 if (size == -1) {
3360 // chars_to_convert includes a NULL terminator, so subtract space
3361 // for that because resize() includes that itself.
3362 --chars_to_allocate;
3363 }
3364 utf16.resize(chars_to_allocate);
3365
3366 // This uses &string[0] to get write-access to the entire string buffer
3367 // which may be assuming that the chars are all contiguous, but it seems
3368 // to work and saves us the hassle of using a temporary
3369 // std::vector<wchar_t>.
3370 const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3371 chars_to_convert);
3372 if (result != chars_to_convert) {
3373 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3374 _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3375 "GetLastError: %lu", result, GetLastError());
3376 }
3377
3378 // If a size was passed in (size != -1), then the string is NULL terminated
3379 // by a NULL char that was written by std::string::resize(). If size == -1,
3380 // then MultiByteToWideChar() read a NULL terminator from the original
3381 // string and converted it to a NULL UTF-16 char in the output.
3382
3383 return utf16;
3384}
3385
3386// Convert a NULL terminated string from UTF-8 to UTF-16.
3387std::wstring widen(const char* utf8) {
3388 // Pass -1 to let widen() determine the string length.
3389 return widen(utf8, -1);
3390}
3391
3392// Convert from UTF-8 to UTF-16.
3393std::wstring widen(const std::string& utf8) {
3394 return widen(utf8.c_str(), utf8.length());
3395}
3396
3397// Convert from UTF-16 to UTF-8.
3398std::string narrow(const std::wstring& utf16) {
3399 return narrow(utf16.c_str());
3400}
3401
3402// Convert from UTF-16 to UTF-8.
3403std::string narrow(const wchar_t* utf16) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003404 // Note: Do not call SystemErrorCodeToString() from narrow() because
Elliott Hughes1ba53092015-08-03 16:26:13 -07003405 // SystemErrorCodeToString() calls narrow() and we don't want potential
Spencer Lowcc467f12015-08-02 18:13:54 -07003406 // infinite recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003407 const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3408 0, NULL, NULL);
3409 if (chars_required <= 0) {
3410 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003411 fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003412 chars_required, GetLastError());
3413 }
3414
3415 std::string utf8;
3416 // Subtract space for the NULL terminator because resize() includes
3417 // that itself. Note that this could potentially throw a std::bad_alloc
3418 // exception.
3419 utf8.resize(chars_required - 1);
3420
3421 // This uses &string[0] to get write-access to the entire string buffer
3422 // which may be assuming that the chars are all contiguous, but it seems
3423 // to work and saves us the hassle of using a temporary
3424 // std::vector<char>.
3425 const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3426 chars_required, NULL, NULL);
3427 if (result != chars_required) {
3428 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003429 fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003430 result, GetLastError());
3431 }
3432
3433 return utf8;
3434}
3435
3436// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3437// be passed to main().
3438NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3439 narrow_args = new char*[argc + 1];
3440
3441 for (int i = 0; i < argc; ++i) {
3442 narrow_args[i] = strdup(narrow(argv[i]).c_str());
3443 }
3444 narrow_args[argc] = nullptr; // terminate
3445}
3446
3447NarrowArgs::~NarrowArgs() {
3448 if (narrow_args != nullptr) {
3449 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3450 free(*argp);
3451 }
3452 delete[] narrow_args;
3453 narrow_args = nullptr;
3454 }
3455}
3456
3457int unix_open(const char* path, int options, ...) {
3458 if ((options & O_CREAT) == 0) {
3459 return _wopen(widen(path).c_str(), options);
3460 } else {
3461 int mode;
3462 va_list args;
3463 va_start(args, options);
3464 mode = va_arg(args, int);
3465 va_end(args);
3466 return _wopen(widen(path).c_str(), options, mode);
3467 }
3468}
3469
3470// Version of stat() that takes a UTF-8 path.
3471int adb_stat(const char* f, struct adb_stat* s) {
3472#pragma push_macro("wstat")
3473// This definition of wstat seems to be missing from <sys/stat.h>.
3474#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3475#ifdef _USE_32BIT_TIME_T
3476#define wstat _wstat32i64
3477#else
3478#define wstat _wstat64
3479#endif
3480#else
3481// <sys/stat.h> has a function prototype for wstat() that should be available.
3482#endif
3483
3484 return wstat(widen(f).c_str(), s);
3485
3486#pragma pop_macro("wstat")
3487}
3488
3489// Version of opendir() that takes a UTF-8 path.
3490DIR* adb_opendir(const char* name) {
3491 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3492 // the fields, but right now all the callers treat the structure as
3493 // opaque.
3494 return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3495}
3496
3497// Version of readdir() that returns UTF-8 paths.
3498struct dirent* adb_readdir(DIR* dir) {
3499 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3500 struct _wdirent* const went = _wreaddir(wdir);
3501 if (went == nullptr) {
3502 return nullptr;
3503 }
3504 // Convert from UTF-16 to UTF-8.
3505 const std::string name_utf8(narrow(went->d_name));
3506
3507 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3508 // space for UTF-16 wchar_t's) with UTF-8 char's.
3509 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3510
3511 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3512 // Name too big to fit in existing buffer.
3513 errno = ENOMEM;
3514 return nullptr;
3515 }
3516
3517 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3518 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3519 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3520 // bigger than the caller expects because they expect a dirent structure
3521 // which has a smaller d_name field. Ignore this since the caller should be
3522 // resilient.
3523
3524 // Rewrite the UTF-16 d_name field to UTF-8.
3525 strcpy(ent->d_name, name_utf8.c_str());
3526
3527 return ent;
3528}
3529
3530// Version of closedir() to go with our version of adb_opendir().
3531int adb_closedir(DIR* dir) {
3532 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3533}
3534
3535// Version of unlink() that takes a UTF-8 path.
3536int adb_unlink(const char* path) {
3537 const std::wstring wpath(widen(path));
3538
3539 int rc = _wunlink(wpath.c_str());
3540
3541 if (rc == -1 && errno == EACCES) {
3542 /* unlink returns EACCES when the file is read-only, so we first */
3543 /* try to make it writable, then unlink again... */
3544 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3545 if (rc == 0)
3546 rc = _wunlink(wpath.c_str());
3547 }
3548 return rc;
3549}
3550
3551// Version of mkdir() that takes a UTF-8 path.
3552int adb_mkdir(const std::string& path, int mode) {
3553 return _wmkdir(widen(path.c_str()).c_str());
3554}
3555
3556// Version of utime() that takes a UTF-8 path.
3557int adb_utime(const char* path, struct utimbuf* u) {
3558 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3559 "utimbuf and _utimbuf should be the same size because they both "
3560 "contain the same types, namely time_t");
3561 return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3562}
3563
3564// Version of chmod() that takes a UTF-8 path.
3565int adb_chmod(const char* path, int mode) {
3566 return _wchmod(widen(path).c_str(), mode);
3567}
3568
3569// Internal function to get a Win32 console HANDLE from a C Runtime FILE*.
3570static HANDLE _get_console_handle(FILE* const stream) {
3571 // Get a C Runtime file descriptor number from the FILE* structure.
3572 const int fd = fileno(stream);
3573 if (fd < 0) {
3574 return NULL;
3575 }
3576
3577 // If it is not a "character device", it is probably a file and not a
3578 // console. Do this check early because it is probably cheap. Still do more
3579 // checks after this since there are devices that pass this test, but are
3580 // not a console, such as NUL, the Windows /dev/null equivalent (I think).
3581 if (!isatty(fd)) {
3582 return NULL;
3583 }
3584
3585 // Given a C Runtime file descriptor number, get the underlying OS
3586 // file handle.
3587 const intptr_t osfh = _get_osfhandle(fd);
3588 if (osfh == -1) {
3589 return NULL;
3590 }
3591
3592 const HANDLE h = reinterpret_cast<const HANDLE>(osfh);
3593
3594 DWORD old_mode = 0;
3595 if (!GetConsoleMode(h, &old_mode)) {
3596 return NULL;
3597 }
3598
3599 // If GetConsoleMode() was successful, assume this is a console.
3600 return h;
3601}
3602
3603// Internal helper function to write UTF-8 bytes to a console. Returns -1
3604// on error.
3605static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3606 HANDLE console) {
3607 // Convert from UTF-8 to UTF-16.
3608 // This could throw std::bad_alloc.
3609 const std::wstring output(widen(buf, size));
3610
3611 // Note that this does not do \n => \r\n translation because that
3612 // doesn't seem necessary for the Windows console. For the Windows
3613 // console \r moves to the beginning of the line and \n moves to a new
3614 // line.
3615
3616 // Flush any stream buffering so that our output is afterwards which
3617 // makes sense because our call is afterwards.
3618 (void)fflush(stream);
3619
3620 // Write UTF-16 to the console.
3621 DWORD written = 0;
3622 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3623 NULL)) {
3624 errno = EIO;
3625 return -1;
3626 }
3627
3628 // This is the number of UTF-16 chars written, which might be different
3629 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3630 // get this count correct.
3631 return written;
3632}
3633
3634// Function prototype because attributes cannot be placed on func definitions.
3635static int _console_vfprintf(const HANDLE console, FILE* stream,
3636 const char *format, va_list ap)
3637 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3638
3639// Internal function to format a UTF-8 string and write it to a Win32 console.
3640// Returns -1 on error.
3641static int _console_vfprintf(const HANDLE console, FILE* stream,
3642 const char *format, va_list ap) {
3643 std::string output_utf8;
3644
3645 // Format the string.
3646 // This could throw std::bad_alloc.
3647 android::base::StringAppendV(&output_utf8, format, ap);
3648
3649 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3650 stream, console);
3651}
3652
3653// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3654// Windows console.
3655int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3656 const HANDLE console = _get_console_handle(stream);
3657
3658 // If there is an associated Win32 console, write to it specially,
3659 // otherwise defer to the regular C Runtime, passing it UTF-8.
3660 if (console != NULL) {
3661 return _console_vfprintf(console, stream, format, ap);
3662 } else {
3663 // If vfprintf is a macro, undefine it, so we can call the real
3664 // C Runtime API.
3665#pragma push_macro("vfprintf")
3666#undef vfprintf
3667 return vfprintf(stream, format, ap);
3668#pragma pop_macro("vfprintf")
3669 }
3670}
3671
3672// Version of fprintf() that takes UTF-8 and can write Unicode to a
3673// Windows console.
3674int adb_fprintf(FILE *stream, const char *format, ...) {
3675 va_list ap;
3676 va_start(ap, format);
3677 const int result = adb_vfprintf(stream, format, ap);
3678 va_end(ap);
3679
3680 return result;
3681}
3682
3683// Version of printf() that takes UTF-8 and can write Unicode to a
3684// Windows console.
3685int adb_printf(const char *format, ...) {
3686 va_list ap;
3687 va_start(ap, format);
3688 const int result = adb_vfprintf(stdout, format, ap);
3689 va_end(ap);
3690
3691 return result;
3692}
3693
3694// Version of fputs() that takes UTF-8 and can write Unicode to a
3695// Windows console.
3696int adb_fputs(const char* buf, FILE* stream) {
3697 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3698 // which fputs (and hence adb_fputs) should return on error.
3699 return adb_fprintf(stream, "%s", buf);
3700}
3701
3702// Version of fputc() that takes UTF-8 and can write Unicode to a
3703// Windows console.
3704int adb_fputc(int ch, FILE* stream) {
3705 const int result = adb_fprintf(stream, "%c", ch);
3706 if (result <= 0) {
3707 // If there was an error, or if nothing was printed (which should be an
3708 // error), return an error, which fprintf signifies with EOF.
3709 return EOF;
3710 }
3711 // For success, fputc returns the char, cast to unsigned char, then to int.
3712 return static_cast<unsigned char>(ch);
3713}
3714
3715// Internal function to write UTF-8 to a Win32 console. Returns the number of
3716// items (of length size) written. On error, returns a short item count or 0.
3717static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3718 FILE* stream, HANDLE console) {
3719 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3720 // if we're passed only some of the bytes of a character (for example, from
3721 // the network socket for adb shell), we won't be able to convert the char
3722 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3723 // right.
3724 //
3725 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3726 //
3727 // For now we ignore this problem because the alternative is that we'd have
3728 // to parse UTF-8 and buffer things up (doable). At least this is better
3729 // than what we had before -- always incorrect multi-byte UTF-8 output.
3730 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3731 size * nmemb, stream, console);
3732 if (result == -1) {
3733 return 0;
3734 }
3735 return result / size;
3736}
3737
3738// Version of fwrite() that takes UTF-8 and can write Unicode to a
3739// Windows console.
3740size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3741 const HANDLE console = _get_console_handle(stream);
3742
3743 // If there is an associated Win32 console, write to it specially,
3744 // otherwise defer to the regular C Runtime, passing it UTF-8.
3745 if (console != NULL) {
3746 return _console_fwrite(ptr, size, nmemb, stream, console);
3747 } else {
3748 // If fwrite is a macro, undefine it, so we can call the real
3749 // C Runtime API.
3750#pragma push_macro("fwrite")
3751#undef fwrite
3752 return fwrite(ptr, size, nmemb, stream);
3753#pragma pop_macro("fwrite")
3754 }
3755}
3756
3757// Version of fopen() that takes a UTF-8 filename and can access a file with
3758// a Unicode filename.
3759FILE* adb_fopen(const char* f, const char* m) {
3760 return _wfopen(widen(f).c_str(), widen(m).c_str());
3761}
3762
3763// Shadow UTF-8 environment variable name/value pairs that are created from
3764// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003765// currently updated if putenv, setenv, unsetenv are called. Note that no
3766// thread synchronization is done, but we're called early enough in
3767// single-threaded startup that things work ok.
Spencer Low6815c072015-05-11 01:08:48 -07003768static std::unordered_map<std::string, char*> g_environ_utf8;
3769
3770// Make sure that shadow UTF-8 environment variables are setup.
3771static void _ensure_env_setup() {
3772 // If some name/value pairs exist, then we've already done the setup below.
3773 if (g_environ_utf8.size() != 0) {
3774 return;
3775 }
3776
3777 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3778 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3779 // to use the D() macro here because that tracing only works if the
3780 // ADB_TRACE environment variable is setup, but that env var can't be read
3781 // until this code completes.
3782 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3783 wchar_t* const equal = wcschr(*env, L'=');
3784 if (equal == nullptr) {
3785 // Malformed environment variable with no equal sign. Shouldn't
3786 // really happen, but we should be resilient to this.
3787 continue;
3788 }
3789
3790 const std::string name_utf8(narrow(std::wstring(*env, equal - *env)));
3791 char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3792
3793 // Overwrite any duplicate name, but there shouldn't be a dup in the
3794 // first place.
3795 g_environ_utf8[name_utf8] = value_utf8;
3796 }
3797}
3798
3799// Version of getenv() that takes a UTF-8 environment variable name and
3800// retrieves a UTF-8 value.
3801char* adb_getenv(const char* name) {
3802 _ensure_env_setup();
3803
Spencer Lowcc467f12015-08-02 18:13:54 -07003804 const auto it = g_environ_utf8.find(std::string(name));
Spencer Low6815c072015-05-11 01:08:48 -07003805 if (it == g_environ_utf8.end()) {
3806 return nullptr;
3807 }
3808
3809 return it->second;
3810}
3811
3812// Version of getcwd() that returns the current working directory in UTF-8.
3813char* adb_getcwd(char* buf, int size) {
3814 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3815 if (wbuf == nullptr) {
3816 return nullptr;
3817 }
3818
3819 const std::string buf_utf8(narrow(wbuf));
3820 free(wbuf);
3821 wbuf = nullptr;
3822
3823 // If size was specified, make sure all the chars will fit.
3824 if (size != 0) {
3825 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3826 errno = ERANGE;
3827 return nullptr;
3828 }
3829 }
3830
3831 // If buf was not specified, allocate storage.
3832 if (buf == nullptr) {
3833 if (size == 0) {
3834 size = buf_utf8.length() + 1;
3835 }
3836 buf = reinterpret_cast<char*>(malloc(size));
3837 if (buf == nullptr) {
3838 return nullptr;
3839 }
3840 }
3841
3842 // Destination buffer was allocated with enough space, or we've already
3843 // checked an existing buffer size for enough space.
3844 strcpy(buf, buf_utf8.c_str());
3845
3846 return buf;
3847}