blob: 80d41a4cc75ed0e0b5d2d9046dd7d25fea5a32b6 [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
662_cleanup_winsock( void )
663{
Spencer Low753d4852015-07-30 23:07:55 -0700664 // TODO: WSAStartup() might be called multiple times and this won't properly
665 // cleanup the right number of times. Plus, WSACleanup() probably doesn't
666 // make sense since it might interrupt other threads using Winsock (since
667 // our various threads are not explicitly cleanly shutdown at process exit).
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800668 WSACleanup();
669}
670
671static void
672_init_winsock( void )
673{
Spencer Low753d4852015-07-30 23:07:55 -0700674 // TODO: Multiple threads calling this may potentially cause multiple calls
675 // to WSAStartup() and multiple atexit() calls.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800676 if (!_winsock_init) {
677 WSADATA wsaData;
678 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
679 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700680 fatal( "adb: could not initialize Winsock: %s",
681 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800682 }
683 atexit( _cleanup_winsock );
684 _winsock_init = 1;
685 }
686}
687
Spencer Low753d4852015-07-30 23:07:55 -0700688int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800689 struct sockaddr_in addr;
690 SOCKET s;
691
Spencer Low753d4852015-07-30 23:07:55 -0700692 unique_fh f(_fh_alloc(&_fh_socket_class));
693 if (!f) {
694 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800695 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700696 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800697
698 if (!_winsock_init)
699 _init_winsock();
700
701 memset(&addr, 0, sizeof(addr));
702 addr.sin_family = AF_INET;
703 addr.sin_port = htons(port);
704 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
705
706 s = socket(AF_INET, type, 0);
707 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700708 *error = android::base::StringPrintf("cannot create socket: %s",
709 SystemErrorCodeToString(WSAGetLastError()).c_str());
710 D("%s\n", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700711 return -1;
712 }
713 f->fh_socket = s;
714
715 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700716 // Save err just in case inet_ntoa() or ntohs() changes the last error.
717 const DWORD err = WSAGetLastError();
718 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
719 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
720 SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700721 D("could not connect to %s:%d: %s\n",
722 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800723 return -1;
724 }
725
Spencer Low753d4852015-07-30 23:07:55 -0700726 const int fd = _fh_to_int(f.get());
727 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
728 type != SOCK_STREAM ? "udp:" : "", port );
729 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
730 fd );
731 f.release();
732 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800733}
734
735#define LISTEN_BACKLOG 4
736
Spencer Low753d4852015-07-30 23:07:55 -0700737// interface_address is INADDR_LOOPBACK or INADDR_ANY.
738static int _network_server(int port, int type, u_long interface_address,
739 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800740 struct sockaddr_in addr;
741 SOCKET s;
742 int n;
743
Spencer Low753d4852015-07-30 23:07:55 -0700744 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800745 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700746 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800747 return -1;
748 }
749
750 if (!_winsock_init)
751 _init_winsock();
752
753 memset(&addr, 0, sizeof(addr));
754 addr.sin_family = AF_INET;
755 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700756 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800757
Spencer Low753d4852015-07-30 23:07:55 -0700758 // TODO: Consider using dual-stack socket that can simultaneously listen on
759 // IPv4 and IPv6.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800760 s = socket(AF_INET, type, 0);
Spencer Low753d4852015-07-30 23:07:55 -0700761 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700762 *error = android::base::StringPrintf("cannot create socket: %s",
763 SystemErrorCodeToString(WSAGetLastError()).c_str());
764 D("%s\n", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700765 return -1;
766 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800767
768 f->fh_socket = s;
769
Spencer Low32625852015-08-11 16:45:32 -0700770 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
771 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800772 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700773 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
774 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700775 *error = android::base::StringPrintf(
776 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
777 SystemErrorCodeToString(WSAGetLastError()).c_str());
778 D("%s\n", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700779 return -1;
780 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800781
Spencer Low32625852015-08-11 16:45:32 -0700782 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
783 // Save err just in case inet_ntoa() or ntohs() changes the last error.
784 const DWORD err = WSAGetLastError();
785 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
786 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
787 SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700788 D("could not bind to %s:%d: %s\n",
789 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800790 return -1;
791 }
792 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700793 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700794 *error = android::base::StringPrintf("cannot listen on socket: %s",
795 SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700796 D("could not listen on %s:%d: %s\n",
797 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800798 return -1;
799 }
800 }
Spencer Low753d4852015-07-30 23:07:55 -0700801 const int fd = _fh_to_int(f.get());
802 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
803 interface_address == INADDR_LOOPBACK ? "lo" : "any",
804 type != SOCK_STREAM ? "udp:" : "", port );
805 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
806 fd );
807 f.release();
808 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800809}
810
Spencer Low753d4852015-07-30 23:07:55 -0700811int network_loopback_server(int port, int type, std::string* error) {
812 return _network_server(port, type, INADDR_LOOPBACK, error);
813}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800814
Spencer Low753d4852015-07-30 23:07:55 -0700815int network_inaddr_any_server(int port, int type, std::string* error) {
816 return _network_server(port, type, INADDR_ANY, error);
817}
818
819int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
820 unique_fh f(_fh_alloc(&_fh_socket_class));
821 if (!f) {
822 *error = strerror(errno);
823 return -1;
824 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800825
Elliott Hughes43df1092015-07-23 17:12:58 -0700826 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800827
Spencer Low753d4852015-07-30 23:07:55 -0700828 struct addrinfo hints;
829 memset(&hints, 0, sizeof(hints));
830 hints.ai_family = AF_UNSPEC;
831 hints.ai_socktype = type;
832
833 char port_str[16];
834 snprintf(port_str, sizeof(port_str), "%d", port);
835
836 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700837
838#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
839 // TODO: When the Android SDK tools increases the Windows system
840 // requirements >= WinXP SP2, switch to GetAddrInfoW(widen(host).c_str()).
841#else
842 // Otherwise, keep using getaddrinfo(), or do runtime API detection
843 // with GetProcAddress("GetAddrInfoW").
844#endif
Spencer Low753d4852015-07-30 23:07:55 -0700845 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -0700846 *error = android::base::StringPrintf(
847 "cannot resolve host '%s' and port %s: %s", host.c_str(),
848 port_str, SystemErrorCodeToString(WSAGetLastError()).c_str());
849 D("%s\n", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800850 return -1;
851 }
Spencer Low753d4852015-07-30 23:07:55 -0700852 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
853 addrinfo(addrinfo_ptr, freeaddrinfo);
854 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800855
Spencer Low753d4852015-07-30 23:07:55 -0700856 // TODO: Try all the addresses if there's more than one? This just uses
857 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
858 // which tries all addresses, takes a timeout and more.
859 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
860 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800861 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700862 *error = android::base::StringPrintf("cannot create socket: %s",
863 SystemErrorCodeToString(WSAGetLastError()).c_str());
864 D("%s\n", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800865 return -1;
866 }
867 f->fh_socket = s;
868
Spencer Low753d4852015-07-30 23:07:55 -0700869 // TODO: Implement timeouts for Windows. Seems like the default in theory
870 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
871 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700872 // TODO: Use WSAAddressToString or inet_ntop on address.
873 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
874 host.c_str(), port_str,
875 SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700876 D("could not connect to %s:%s:%s: %s\n",
877 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
878 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800879 return -1;
880 }
881
Spencer Low753d4852015-07-30 23:07:55 -0700882 const int fd = _fh_to_int(f.get());
883 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
884 type != SOCK_STREAM ? "udp:" : "", port );
885 D( "host '%s' port %d type %s => fd %d\n", host.c_str(), port,
886 type != SOCK_STREAM ? "udp" : "tcp", fd );
887 f.release();
888 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800889}
890
891#undef accept
892int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
893{
Spencer Low3a2421b2015-05-22 20:09:06 -0700894 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200895
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800896 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Spencer Low753d4852015-07-30 23:07:55 -0700897 D("adb_socket_accept: invalid fd %d\n", serverfd);
898 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800899 return -1;
900 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200901
Spencer Low753d4852015-07-30 23:07:55 -0700902 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800903 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700904 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
905 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800906 return -1;
907 }
908
909 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
910 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700911 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700912 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
913 " failed: " + SystemErrorCodeToString(err);
914 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800915 return -1;
916 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200917
Spencer Low753d4852015-07-30 23:07:55 -0700918 const int fd = _fh_to_int(fh.get());
919 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
920 D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, fd );
921 fh.release();
922 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800923}
924
925
Spencer Low31aafa62015-01-25 14:40:16 -0800926int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800927{
Spencer Low3a2421b2015-05-22 20:09:06 -0700928 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200929
Spencer Low31aafa62015-01-25 14:40:16 -0800930 if ( !fh || fh->clazz != &_fh_socket_class ) {
931 D("adb_setsockopt: invalid fd %d\n", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700932 errno = EBADF;
933 return -1;
934 }
935 int result = setsockopt( fh->fh_socket, level, optname,
936 reinterpret_cast<const char*>(optval), optlen );
937 if ( result == SOCKET_ERROR ) {
938 const DWORD err = WSAGetLastError();
939 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
940 "failed: %s\n", fd, level, optname,
941 SystemErrorCodeToString(err).c_str() );
942 _socket_set_errno( err );
943 result = -1;
944 }
945 return result;
946}
947
948
949int adb_shutdown(int fd)
950{
951 FH f = _fh_from_int(fd, __func__);
952
953 if (!f || f->clazz != &_fh_socket_class) {
954 D("adb_shutdown: invalid fd %d\n", fd);
955 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -0800956 return -1;
957 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800958
Spencer Low753d4852015-07-30 23:07:55 -0700959 D( "adb_shutdown: %s\n", f->name);
960 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
961 const DWORD err = WSAGetLastError();
962 D("socket shutdown fd %d failed: %s\n", fd,
963 SystemErrorCodeToString(err).c_str());
964 _socket_set_errno(err);
965 return -1;
966 }
967 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800968}
969
970/**************************************************************************/
971/**************************************************************************/
972/***** *****/
973/***** emulated socketpairs *****/
974/***** *****/
975/**************************************************************************/
976/**************************************************************************/
977
978/* we implement socketpairs directly in use space for the following reasons:
979 * - it avoids copying data from/to the Nt kernel
980 * - it allows us to implement fdevent hooks easily and cheaply, something
981 * that is not possible with standard Win32 pipes !!
982 *
983 * basically, we use two circular buffers, each one corresponding to a given
984 * direction.
985 *
986 * each buffer is implemented as two regions:
987 *
988 * region A which is (a_start,a_end)
989 * region B which is (0, b_end) with b_end <= a_start
990 *
991 * an empty buffer has: a_start = a_end = b_end = 0
992 *
993 * a_start is the pointer where we start reading data
994 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
995 * then you start writing at b_end
996 *
997 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
998 *
999 * there is room when b_end < a_start || a_end < BUFER_SIZE
1000 *
1001 * when reading, a_start is incremented, it a_start meets a_end, then
1002 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1003 */
1004
1005#define BIP_BUFFER_SIZE 4096
1006
1007#if 0
1008#include <stdio.h>
1009# define BIPD(x) D x
1010# define BIPDUMP bip_dump_hex
1011
1012static void bip_dump_hex( const unsigned char* ptr, size_t len )
1013{
1014 int nn, len2 = len;
1015
1016 if (len2 > 8) len2 = 8;
1017
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001018 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001019 printf("%02x", ptr[nn]);
1020 printf(" ");
1021
1022 for (nn = 0; nn < len2; nn++) {
1023 int c = ptr[nn];
1024 if (c < 32 || c > 127)
1025 c = '.';
1026 printf("%c", c);
1027 }
1028 printf("\n");
1029 fflush(stdout);
1030}
1031
1032#else
1033# define BIPD(x) do {} while (0)
1034# define BIPDUMP(p,l) BIPD(p)
1035#endif
1036
1037typedef struct BipBufferRec_
1038{
1039 int a_start;
1040 int a_end;
1041 int b_end;
1042 int fdin;
1043 int fdout;
1044 int closed;
1045 int can_write; /* boolean */
1046 HANDLE evt_write; /* event signaled when one can write to a buffer */
1047 int can_read; /* boolean */
1048 HANDLE evt_read; /* event signaled when one can read from a buffer */
1049 CRITICAL_SECTION lock;
1050 unsigned char buff[ BIP_BUFFER_SIZE ];
1051
1052} BipBufferRec, *BipBuffer;
1053
1054static void
1055bip_buffer_init( BipBuffer buffer )
1056{
1057 D( "bit_buffer_init %p\n", buffer );
1058 buffer->a_start = 0;
1059 buffer->a_end = 0;
1060 buffer->b_end = 0;
1061 buffer->can_write = 1;
1062 buffer->can_read = 0;
1063 buffer->fdin = 0;
1064 buffer->fdout = 0;
1065 buffer->closed = 0;
1066 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1067 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1068 InitializeCriticalSection( &buffer->lock );
1069}
1070
1071static void
1072bip_buffer_close( BipBuffer bip )
1073{
1074 bip->closed = 1;
1075
1076 if (!bip->can_read) {
1077 SetEvent( bip->evt_read );
1078 }
1079 if (!bip->can_write) {
1080 SetEvent( bip->evt_write );
1081 }
1082}
1083
1084static void
1085bip_buffer_done( BipBuffer bip )
1086{
1087 BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
1088 CloseHandle( bip->evt_read );
1089 CloseHandle( bip->evt_write );
1090 DeleteCriticalSection( &bip->lock );
1091}
1092
1093static int
1094bip_buffer_write( BipBuffer bip, const void* src, int len )
1095{
1096 int avail, count = 0;
1097
1098 if (len <= 0)
1099 return 0;
1100
1101 BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1102 BIPDUMP( src, len );
1103
1104 EnterCriticalSection( &bip->lock );
1105
1106 while (!bip->can_write) {
1107 int ret;
1108 LeaveCriticalSection( &bip->lock );
1109
1110 if (bip->closed) {
1111 errno = EPIPE;
1112 return -1;
1113 }
1114 /* spinlocking here is probably unfair, but let's live with it */
1115 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1116 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
1117 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
1118 return 0;
1119 }
1120 if (bip->closed) {
1121 errno = EPIPE;
1122 return -1;
1123 }
1124 EnterCriticalSection( &bip->lock );
1125 }
1126
1127 BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1128
1129 avail = BIP_BUFFER_SIZE - bip->a_end;
1130 if (avail > 0)
1131 {
1132 /* we can append to region A */
1133 if (avail > len)
1134 avail = len;
1135
1136 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001137 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001138 count += avail;
1139 len -= avail;
1140
1141 bip->a_end += avail;
1142 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1143 bip->can_write = 0;
1144 ResetEvent( bip->evt_write );
1145 goto Exit;
1146 }
1147 }
1148
1149 if (len == 0)
1150 goto Exit;
1151
1152 avail = bip->a_start - bip->b_end;
1153 assert( avail > 0 ); /* since can_write is TRUE */
1154
1155 if (avail > len)
1156 avail = len;
1157
1158 memcpy( bip->buff + bip->b_end, src, avail );
1159 count += avail;
1160 bip->b_end += avail;
1161
1162 if (bip->b_end == bip->a_start) {
1163 bip->can_write = 0;
1164 ResetEvent( bip->evt_write );
1165 }
1166
1167Exit:
1168 assert( count > 0 );
1169
1170 if ( !bip->can_read ) {
1171 bip->can_read = 1;
1172 SetEvent( bip->evt_read );
1173 }
1174
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001175 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 -08001176 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1177 LeaveCriticalSection( &bip->lock );
1178
1179 return count;
1180 }
1181
1182static int
1183bip_buffer_read( BipBuffer bip, void* dst, int len )
1184{
1185 int avail, count = 0;
1186
1187 if (len <= 0)
1188 return 0;
1189
1190 BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1191
1192 EnterCriticalSection( &bip->lock );
1193 while ( !bip->can_read )
1194 {
1195#if 0
1196 LeaveCriticalSection( &bip->lock );
1197 errno = EAGAIN;
1198 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001199#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001200 int ret;
1201 LeaveCriticalSection( &bip->lock );
1202
1203 if (bip->closed) {
1204 errno = EPIPE;
1205 return -1;
1206 }
1207
1208 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1209 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
1210 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
1211 return 0;
1212 }
1213 if (bip->closed) {
1214 errno = EPIPE;
1215 return -1;
1216 }
1217 EnterCriticalSection( &bip->lock );
1218#endif
1219 }
1220
1221 BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1222
1223 avail = bip->a_end - bip->a_start;
1224 assert( avail > 0 ); /* since can_read is TRUE */
1225
1226 if (avail > len)
1227 avail = len;
1228
1229 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001230 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001231 count += avail;
1232 len -= avail;
1233
1234 bip->a_start += avail;
1235 if (bip->a_start < bip->a_end)
1236 goto Exit;
1237
1238 bip->a_start = 0;
1239 bip->a_end = bip->b_end;
1240 bip->b_end = 0;
1241
1242 avail = bip->a_end;
1243 if (avail > 0) {
1244 if (avail > len)
1245 avail = len;
1246 memcpy( dst, bip->buff, avail );
1247 count += avail;
1248 bip->a_start += avail;
1249
1250 if ( bip->a_start < bip->a_end )
1251 goto Exit;
1252
1253 bip->a_start = bip->a_end = 0;
1254 }
1255
1256 bip->can_read = 0;
1257 ResetEvent( bip->evt_read );
1258
1259Exit:
1260 assert( count > 0 );
1261
1262 if (!bip->can_write ) {
1263 bip->can_write = 1;
1264 SetEvent( bip->evt_write );
1265 }
1266
1267 BIPDUMP( (const unsigned char*)dst - count, count );
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001268 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 -08001269 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1270 LeaveCriticalSection( &bip->lock );
1271
1272 return count;
1273}
1274
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001275typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001276{
1277 BipBufferRec a2b_bip;
1278 BipBufferRec b2a_bip;
1279 FH a_fd;
1280 int used;
1281
1282} SocketPairRec;
1283
1284void _fh_socketpair_init( FH f )
1285{
1286 f->fh_pair = NULL;
1287}
1288
1289static int
1290_fh_socketpair_close( FH f )
1291{
1292 if ( f->fh_pair ) {
1293 SocketPair pair = f->fh_pair;
1294
1295 if ( f == pair->a_fd ) {
1296 pair->a_fd = NULL;
1297 }
1298
1299 bip_buffer_close( &pair->b2a_bip );
1300 bip_buffer_close( &pair->a2b_bip );
1301
1302 if ( --pair->used == 0 ) {
1303 bip_buffer_done( &pair->b2a_bip );
1304 bip_buffer_done( &pair->a2b_bip );
1305 free( pair );
1306 }
1307 f->fh_pair = NULL;
1308 }
1309 return 0;
1310}
1311
1312static int
1313_fh_socketpair_lseek( FH f, int pos, int origin )
1314{
1315 errno = ESPIPE;
1316 return -1;
1317}
1318
1319static int
1320_fh_socketpair_read( FH f, void* buf, int len )
1321{
1322 SocketPair pair = f->fh_pair;
1323 BipBuffer bip;
1324
1325 if (!pair)
1326 return -1;
1327
1328 if ( f == pair->a_fd )
1329 bip = &pair->b2a_bip;
1330 else
1331 bip = &pair->a2b_bip;
1332
1333 return bip_buffer_read( bip, buf, len );
1334}
1335
1336static int
1337_fh_socketpair_write( FH f, const void* buf, int len )
1338{
1339 SocketPair pair = f->fh_pair;
1340 BipBuffer bip;
1341
1342 if (!pair)
1343 return -1;
1344
1345 if ( f == pair->a_fd )
1346 bip = &pair->a2b_bip;
1347 else
1348 bip = &pair->b2a_bip;
1349
1350 return bip_buffer_write( bip, buf, len );
1351}
1352
1353
1354static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1355
1356static const FHClassRec _fh_socketpair_class =
1357{
1358 _fh_socketpair_init,
1359 _fh_socketpair_close,
1360 _fh_socketpair_lseek,
1361 _fh_socketpair_read,
1362 _fh_socketpair_write,
1363 _fh_socketpair_hook
1364};
1365
1366
Elliott Hughes6a096932015-04-16 16:47:02 -07001367int adb_socketpair(int sv[2]) {
1368 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001369
Spencer Low753d4852015-07-30 23:07:55 -07001370 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1371 if (!fa) {
1372 return -1;
1373 }
1374 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1375 if (!fb) {
1376 return -1;
1377 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001378
Elliott Hughes6a096932015-04-16 16:47:02 -07001379 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001380 if (pair == NULL) {
1381 D("adb_socketpair: not enough memory to allocate pipes\n" );
Spencer Low753d4852015-07-30 23:07:55 -07001382 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001383 }
1384
1385 bip_buffer_init( &pair->a2b_bip );
1386 bip_buffer_init( &pair->b2a_bip );
1387
1388 fa->fh_pair = pair;
1389 fb->fh_pair = pair;
1390 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001391 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001392
Spencer Low753d4852015-07-30 23:07:55 -07001393 sv[0] = _fh_to_int(fa.get());
1394 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001395
1396 pair->a2b_bip.fdin = sv[0];
1397 pair->a2b_bip.fdout = sv[1];
1398 pair->b2a_bip.fdin = sv[1];
1399 pair->b2a_bip.fdout = sv[0];
1400
1401 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1402 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
1403 D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001404 fa.release();
1405 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001406 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001407}
1408
1409/**************************************************************************/
1410/**************************************************************************/
1411/***** *****/
1412/***** fdevents emulation *****/
1413/***** *****/
1414/***** this is a very simple implementation, we rely on the fact *****/
1415/***** that ADB doesn't use FDE_ERROR. *****/
1416/***** *****/
1417/**************************************************************************/
1418/**************************************************************************/
1419
1420#define FATAL(x...) fatal(__FUNCTION__, x)
1421
1422#if DEBUG
1423static void dump_fde(fdevent *fde, const char *info)
1424{
1425 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1426 fde->state & FDE_READ ? 'R' : ' ',
1427 fde->state & FDE_WRITE ? 'W' : ' ',
1428 fde->state & FDE_ERROR ? 'E' : ' ',
1429 info);
1430}
1431#else
1432#define dump_fde(fde, info) do { } while(0)
1433#endif
1434
1435#define FDE_EVENTMASK 0x00ff
1436#define FDE_STATEMASK 0xff00
1437
1438#define FDE_ACTIVE 0x0100
1439#define FDE_PENDING 0x0200
1440#define FDE_CREATED 0x0400
1441
1442static void fdevent_plist_enqueue(fdevent *node);
1443static void fdevent_plist_remove(fdevent *node);
1444static fdevent *fdevent_plist_dequeue(void);
1445
1446static fdevent list_pending = {
1447 .next = &list_pending,
1448 .prev = &list_pending,
1449};
1450
1451static fdevent **fd_table = 0;
1452static int fd_table_max = 0;
1453
1454typedef struct EventLooperRec_* EventLooper;
1455
1456typedef struct EventHookRec_
1457{
1458 EventHook next;
1459 FH fh;
1460 HANDLE h;
1461 int wanted; /* wanted event flags */
1462 int ready; /* ready event flags */
1463 void* aux;
1464 void (*prepare)( EventHook hook );
1465 int (*start) ( EventHook hook );
1466 void (*stop) ( EventHook hook );
1467 int (*check) ( EventHook hook );
1468 int (*peek) ( EventHook hook );
1469} EventHookRec;
1470
1471static EventHook _free_hooks;
1472
1473static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001474event_hook_alloc(FH fh) {
1475 EventHook hook = _free_hooks;
1476 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001477 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001478 } else {
1479 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001480 if (hook == NULL)
1481 fatal( "could not allocate event hook\n" );
1482 }
1483 hook->next = NULL;
1484 hook->fh = fh;
1485 hook->wanted = 0;
1486 hook->ready = 0;
1487 hook->h = INVALID_HANDLE_VALUE;
1488 hook->aux = NULL;
1489
1490 hook->prepare = NULL;
1491 hook->start = NULL;
1492 hook->stop = NULL;
1493 hook->check = NULL;
1494 hook->peek = NULL;
1495
1496 return hook;
1497}
1498
1499static void
1500event_hook_free( EventHook hook )
1501{
1502 hook->fh = NULL;
1503 hook->wanted = 0;
1504 hook->ready = 0;
1505 hook->next = _free_hooks;
1506 _free_hooks = hook;
1507}
1508
1509
1510static void
1511event_hook_signal( EventHook hook )
1512{
1513 FH f = hook->fh;
1514 int fd = _fh_to_int(f);
1515 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1516
1517 if (fde != NULL && fde->fd == fd) {
1518 if ((fde->state & FDE_PENDING) == 0) {
1519 fde->state |= FDE_PENDING;
1520 fdevent_plist_enqueue( fde );
1521 }
1522 fde->events |= hook->wanted;
1523 }
1524}
1525
1526
1527#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1528
1529typedef struct EventLooperRec_
1530{
1531 EventHook hooks;
1532 HANDLE htab[ MAX_LOOPER_HANDLES ];
1533 int htab_count;
1534
1535} EventLooperRec;
1536
1537static EventHook*
1538event_looper_find_p( EventLooper looper, FH fh )
1539{
1540 EventHook *pnode = &looper->hooks;
1541 EventHook node = *pnode;
1542 for (;;) {
1543 if ( node == NULL || node->fh == fh )
1544 break;
1545 pnode = &node->next;
1546 node = *pnode;
1547 }
1548 return pnode;
1549}
1550
1551static void
1552event_looper_hook( EventLooper looper, int fd, int events )
1553{
Spencer Low3a2421b2015-05-22 20:09:06 -07001554 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001555 EventHook *pnode;
1556 EventHook node;
1557
1558 if (f == NULL) /* invalid arg */ {
1559 D("event_looper_hook: invalid fd=%d\n", fd);
1560 return;
1561 }
1562
1563 pnode = event_looper_find_p( looper, f );
1564 node = *pnode;
1565 if ( node == NULL ) {
1566 node = event_hook_alloc( f );
1567 node->next = *pnode;
1568 *pnode = node;
1569 }
1570
1571 if ( (node->wanted & events) != events ) {
1572 /* this should update start/stop/check/peek */
1573 D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
1574 fd, node->wanted, events);
1575 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1576 node->wanted |= events;
1577 } else {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001578 D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001579 events, fd, node->wanted);
1580 }
1581}
1582
1583static void
1584event_looper_unhook( EventLooper looper, int fd, int events )
1585{
Spencer Low3a2421b2015-05-22 20:09:06 -07001586 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001587 EventHook *pnode = event_looper_find_p( looper, fh );
1588 EventHook node = *pnode;
1589
1590 if (node != NULL) {
1591 int events2 = events & node->wanted;
1592 if ( events2 == 0 ) {
1593 D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
1594 return;
1595 }
1596 node->wanted &= ~events2;
1597 if (!node->wanted) {
1598 *pnode = node->next;
1599 event_hook_free( node );
1600 }
1601 }
1602}
1603
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001604/*
1605 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1606 * handles to wait on.
1607 *
1608 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1609 * instance, this may happen if there are more than 64 processes running on a
1610 * device, or there are multiple devices connected (including the emulator) with
1611 * the combined number of running processes greater than 64. In this case using
1612 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1613 * because of the API limitations (64 handles max). So, we need to provide a way
1614 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1615 * easiest (and "Microsoft recommended") way to do that would be dividing the
1616 * handle array into chunks with the chunk size less than 64, and fire up as many
1617 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1618 * handles, and will report back to the caller which handle has been set.
1619 * Here is the implementation of that algorithm.
1620 */
1621
1622/* Number of handles to wait on in each wating thread. */
1623#define WAIT_ALL_CHUNK_SIZE 63
1624
1625/* Descriptor for a wating thread */
1626typedef struct WaitForAllParam {
1627 /* A handle to an event to signal when waiting is over. This handle is shared
1628 * accross all the waiting threads, so each waiting thread knows when any
1629 * other thread has exited, so it can exit too. */
1630 HANDLE main_event;
1631 /* Upon exit from a waiting thread contains the index of the handle that has
1632 * been signaled. The index is an absolute index of the signaled handle in
1633 * the original array. This pointer is shared accross all the waiting threads
1634 * and it's not guaranteed (due to a race condition) that when all the
1635 * waiting threads exit, the value contained here would indicate the first
1636 * handle that was signaled. This is fine, because the caller cares only
1637 * about any handle being signaled. It doesn't care about the order, nor
1638 * about the whole list of handles that were signaled. */
1639 LONG volatile *signaled_index;
1640 /* Array of handles to wait on in a waiting thread. */
1641 HANDLE* handles;
1642 /* Number of handles in 'handles' array to wait on. */
1643 int handles_count;
1644 /* Index inside the main array of the first handle in the 'handles' array. */
1645 int first_handle_index;
1646 /* Waiting thread handle. */
1647 HANDLE thread;
1648} WaitForAllParam;
1649
1650/* Waiting thread routine. */
1651static unsigned __stdcall
1652_in_waiter_thread(void* arg)
1653{
1654 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1655 int res;
1656 WaitForAllParam* const param = (WaitForAllParam*)arg;
1657
1658 /* We have to wait on the main_event in order to be notified when any of the
1659 * sibling threads is exiting. */
1660 wait_on[0] = param->main_event;
1661 /* The rest of the handles go behind the main event handle. */
1662 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1663
1664 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1665 if (res > 0 && res < (param->handles_count + 1)) {
1666 /* One of the original handles got signaled. Save its absolute index into
1667 * the output variable. */
1668 InterlockedCompareExchange(param->signaled_index,
1669 res - 1L + param->first_handle_index, -1L);
1670 }
1671
1672 /* Notify the caller (and the siblings) that the wait is over. */
1673 SetEvent(param->main_event);
1674
1675 _endthreadex(0);
1676 return 0;
1677}
1678
1679/* WaitForMultipeObjects fixer routine.
1680 * Param:
1681 * handles Array of handles to wait on.
1682 * handles_count Number of handles in the array.
1683 * Return:
1684 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1685 * WAIT_FAILED on an error.
1686 */
1687static int
1688_wait_for_all(HANDLE* handles, int handles_count)
1689{
1690 WaitForAllParam* threads;
1691 HANDLE main_event;
1692 int chunks, chunk, remains;
1693
1694 /* This variable is going to be accessed by several threads at the same time,
1695 * this is bound to fail randomly when the core is run on multi-core machines.
1696 * To solve this, we need to do the following (1 _and_ 2):
1697 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1698 * out the reads/writes in this function unexpectedly.
1699 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1700 * all accesses inside a critical section. But we can also use
1701 * InterlockedCompareExchange() which always provide a full memory barrier
1702 * on Win32.
1703 */
1704 volatile LONG sig_index = -1;
1705
1706 /* Calculate number of chunks, and allocate thread param array. */
1707 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1708 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1709 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1710 sizeof(WaitForAllParam));
1711 if (threads == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001712 D("Unable to allocate thread array for %d handles.\n", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001713 return (int)WAIT_FAILED;
1714 }
1715
1716 /* Create main event to wait on for all waiting threads. This is a "manualy
1717 * reset" event that will remain set once it was set. */
1718 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1719 if (main_event == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001720 D("Unable to create main event. Error: %ld\n", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001721 free(threads);
1722 return (int)WAIT_FAILED;
1723 }
1724
1725 /*
1726 * Initialize waiting thread parameters.
1727 */
1728
1729 for (chunk = 0; chunk < chunks; chunk++) {
1730 threads[chunk].main_event = main_event;
1731 threads[chunk].signaled_index = &sig_index;
1732 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1733 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1734 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1735 }
1736 if (remains) {
1737 threads[chunk].main_event = main_event;
1738 threads[chunk].signaled_index = &sig_index;
1739 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1740 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1741 threads[chunk].handles_count = remains;
1742 chunks++;
1743 }
1744
1745 /* Start the waiting threads. */
1746 for (chunk = 0; chunk < chunks; chunk++) {
1747 /* Note that using adb_thread_create is not appropriate here, since we
1748 * need a handle to wait on for thread termination. */
1749 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1750 &threads[chunk], 0, NULL);
1751 if (threads[chunk].thread == NULL) {
1752 /* Unable to create a waiter thread. Collapse. */
Spencer Low5c761bd2015-07-21 02:06:26 -07001753 D("Unable to create a waiting thread %d of %d. errno=%d\n",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001754 chunk, chunks, errno);
1755 chunks = chunk;
1756 SetEvent(main_event);
1757 break;
1758 }
1759 }
1760
1761 /* Wait on any of the threads to get signaled. */
1762 WaitForSingleObject(main_event, INFINITE);
1763
1764 /* Wait on all the waiting threads to exit. */
1765 for (chunk = 0; chunk < chunks; chunk++) {
1766 WaitForSingleObject(threads[chunk].thread, INFINITE);
1767 CloseHandle(threads[chunk].thread);
1768 }
1769
1770 CloseHandle(main_event);
1771 free(threads);
1772
1773
1774 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1775 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1776}
1777
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001778static EventLooperRec win32_looper;
1779
1780static void fdevent_init(void)
1781{
1782 win32_looper.htab_count = 0;
1783 win32_looper.hooks = NULL;
1784}
1785
1786static void fdevent_connect(fdevent *fde)
1787{
1788 EventLooper looper = &win32_looper;
1789 int events = fde->state & FDE_EVENTMASK;
1790
1791 if (events != 0)
1792 event_looper_hook( looper, fde->fd, events );
1793}
1794
1795static void fdevent_disconnect(fdevent *fde)
1796{
1797 EventLooper looper = &win32_looper;
1798 int events = fde->state & FDE_EVENTMASK;
1799
1800 if (events != 0)
1801 event_looper_unhook( looper, fde->fd, events );
1802}
1803
1804static void fdevent_update(fdevent *fde, unsigned events)
1805{
1806 EventLooper looper = &win32_looper;
1807 unsigned events0 = fde->state & FDE_EVENTMASK;
1808
1809 if (events != events0) {
1810 int removes = events0 & ~events;
1811 int adds = events & ~events0;
1812 if (removes) {
1813 D("fdevent_update: remove %x from %d\n", removes, fde->fd);
1814 event_looper_unhook( looper, fde->fd, removes );
1815 }
1816 if (adds) {
1817 D("fdevent_update: add %x to %d\n", adds, fde->fd);
1818 event_looper_hook ( looper, fde->fd, adds );
1819 }
1820 }
1821}
1822
1823static void fdevent_process()
1824{
1825 EventLooper looper = &win32_looper;
1826 EventHook hook;
1827 int gotone = 0;
1828
1829 /* if we have at least one ready hook, execute it/them */
1830 for (hook = looper->hooks; hook; hook = hook->next) {
1831 hook->ready = 0;
1832 if (hook->prepare) {
1833 hook->prepare(hook);
1834 if (hook->ready != 0) {
1835 event_hook_signal( hook );
1836 gotone = 1;
1837 }
1838 }
1839 }
1840
1841 /* nothing's ready yet, so wait for something to happen */
1842 if (!gotone)
1843 {
1844 looper->htab_count = 0;
1845
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001846 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001847 {
1848 if (hook->start && !hook->start(hook)) {
1849 D( "fdevent_process: error when starting a hook\n" );
1850 return;
1851 }
1852 if (hook->h != INVALID_HANDLE_VALUE) {
1853 int nn;
1854
1855 for (nn = 0; nn < looper->htab_count; nn++)
1856 {
1857 if ( looper->htab[nn] == hook->h )
1858 goto DontAdd;
1859 }
1860 looper->htab[ looper->htab_count++ ] = hook->h;
1861 DontAdd:
1862 ;
1863 }
1864 }
1865
1866 if (looper->htab_count == 0) {
1867 D( "fdevent_process: nothing to wait for !!\n" );
1868 return;
1869 }
1870
1871 do
1872 {
1873 int wait_ret;
1874
1875 D( "adb_win32: waiting for %d events\n", looper->htab_count );
1876 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001877 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
1878 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1879 } else {
1880 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001881 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001882 if (wait_ret == (int)WAIT_FAILED) {
1883 D( "adb_win32: wait failed, error %ld\n", GetLastError() );
1884 } else {
1885 D( "adb_win32: got one (index %d)\n", wait_ret );
1886
1887 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1888 * like mouse movements. we need to filter these with the "check" function
1889 */
1890 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1891 {
1892 for (hook = looper->hooks; hook; hook = hook->next)
1893 {
1894 if ( looper->htab[wait_ret] == hook->h &&
1895 (!hook->check || hook->check(hook)) )
1896 {
1897 D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
1898 event_hook_signal( hook );
1899 gotone = 1;
1900 break;
1901 }
1902 }
1903 }
1904 }
1905 }
1906 while (!gotone);
1907
1908 for (hook = looper->hooks; hook; hook = hook->next) {
1909 if (hook->stop)
1910 hook->stop( hook );
1911 }
1912 }
1913
1914 for (hook = looper->hooks; hook; hook = hook->next) {
1915 if (hook->peek && hook->peek(hook))
1916 event_hook_signal( hook );
1917 }
1918}
1919
1920
1921static void fdevent_register(fdevent *fde)
1922{
1923 int fd = fde->fd - WIN32_FH_BASE;
1924
1925 if(fd < 0) {
1926 FATAL("bogus negative fd (%d)\n", fde->fd);
1927 }
1928
1929 if(fd >= fd_table_max) {
1930 int oldmax = fd_table_max;
1931 if(fde->fd > 32000) {
1932 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1933 }
1934 if(fd_table_max == 0) {
1935 fdevent_init();
1936 fd_table_max = 256;
1937 }
1938 while(fd_table_max <= fd) {
1939 fd_table_max *= 2;
1940 }
Elliott Hughes6a096932015-04-16 16:47:02 -07001941 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001942 if(fd_table == 0) {
1943 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1944 }
1945 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
1946 }
1947
1948 fd_table[fd] = fde;
1949}
1950
1951static void fdevent_unregister(fdevent *fde)
1952{
1953 int fd = fde->fd - WIN32_FH_BASE;
1954
1955 if((fd < 0) || (fd >= fd_table_max)) {
1956 FATAL("fd out of range (%d)\n", fde->fd);
1957 }
1958
1959 if(fd_table[fd] != fde) {
1960 FATAL("fd_table out of sync");
1961 }
1962
1963 fd_table[fd] = 0;
1964
1965 if(!(fde->state & FDE_DONT_CLOSE)) {
1966 dump_fde(fde, "close");
1967 adb_close(fde->fd);
1968 }
1969}
1970
1971static void fdevent_plist_enqueue(fdevent *node)
1972{
1973 fdevent *list = &list_pending;
1974
1975 node->next = list;
1976 node->prev = list->prev;
1977 node->prev->next = node;
1978 list->prev = node;
1979}
1980
1981static void fdevent_plist_remove(fdevent *node)
1982{
1983 node->prev->next = node->next;
1984 node->next->prev = node->prev;
1985 node->next = 0;
1986 node->prev = 0;
1987}
1988
1989static fdevent *fdevent_plist_dequeue(void)
1990{
1991 fdevent *list = &list_pending;
1992 fdevent *node = list->next;
1993
1994 if(node == list) return 0;
1995
1996 list->next = node->next;
1997 list->next->prev = list;
1998 node->next = 0;
1999 node->prev = 0;
2000
2001 return node;
2002}
2003
2004fdevent *fdevent_create(int fd, fd_func func, void *arg)
2005{
2006 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2007 if(fde == 0) return 0;
2008 fdevent_install(fde, fd, func, arg);
2009 fde->state |= FDE_CREATED;
2010 return fde;
2011}
2012
2013void fdevent_destroy(fdevent *fde)
2014{
2015 if(fde == 0) return;
2016 if(!(fde->state & FDE_CREATED)) {
2017 FATAL("fde %p not created by fdevent_create()\n", fde);
2018 }
2019 fdevent_remove(fde);
2020}
2021
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002022void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002023{
2024 memset(fde, 0, sizeof(fdevent));
2025 fde->state = FDE_ACTIVE;
2026 fde->fd = fd;
2027 fde->func = func;
2028 fde->arg = arg;
2029
2030 fdevent_register(fde);
2031 dump_fde(fde, "connect");
2032 fdevent_connect(fde);
2033 fde->state |= FDE_ACTIVE;
2034}
2035
2036void fdevent_remove(fdevent *fde)
2037{
2038 if(fde->state & FDE_PENDING) {
2039 fdevent_plist_remove(fde);
2040 }
2041
2042 if(fde->state & FDE_ACTIVE) {
2043 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002044 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002045 fdevent_unregister(fde);
2046 }
2047
2048 fde->state = 0;
2049 fde->events = 0;
2050}
2051
2052
2053void fdevent_set(fdevent *fde, unsigned events)
2054{
2055 events &= FDE_EVENTMASK;
2056
2057 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2058
2059 if(fde->state & FDE_ACTIVE) {
2060 fdevent_update(fde, events);
2061 dump_fde(fde, "update");
2062 }
2063
2064 fde->state = (fde->state & FDE_STATEMASK) | events;
2065
2066 if(fde->state & FDE_PENDING) {
2067 /* if we're pending, make sure
2068 ** we don't signal an event that
2069 ** is no longer wanted.
2070 */
2071 fde->events &= (~events);
2072 if(fde->events == 0) {
2073 fdevent_plist_remove(fde);
2074 fde->state &= (~FDE_PENDING);
2075 }
2076 }
2077}
2078
2079void fdevent_add(fdevent *fde, unsigned events)
2080{
2081 fdevent_set(
2082 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2083}
2084
2085void fdevent_del(fdevent *fde, unsigned events)
2086{
2087 fdevent_set(
2088 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2089}
2090
2091void fdevent_loop()
2092{
2093 fdevent *fde;
2094
2095 for(;;) {
2096#if DEBUG
2097 fprintf(stderr,"--- ---- waiting for events\n");
2098#endif
2099 fdevent_process();
2100
2101 while((fde = fdevent_plist_dequeue())) {
2102 unsigned events = fde->events;
2103 fde->events = 0;
2104 fde->state &= (~FDE_PENDING);
2105 dump_fde(fde, "callback");
2106 fde->func(fde->fd, events, fde->arg);
2107 }
2108 }
2109}
2110
2111/** FILE EVENT HOOKS
2112 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002113
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002114static void _event_file_prepare( EventHook hook )
2115{
2116 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2117 /* we can always read/write */
2118 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2119 }
2120}
2121
2122static int _event_file_peek( EventHook hook )
2123{
2124 return (hook->wanted & (FDE_READ|FDE_WRITE));
2125}
2126
2127static void _fh_file_hook( FH f, int events, EventHook hook )
2128{
2129 hook->h = f->fh_handle;
2130 hook->prepare = _event_file_prepare;
2131 hook->peek = _event_file_peek;
2132}
2133
2134/** SOCKET EVENT HOOKS
2135 **/
2136
2137static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2138{
2139 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2140 if (hook->wanted & FDE_READ)
2141 hook->ready |= FDE_READ;
2142 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2143 hook->ready |= FDE_ERROR;
2144 }
2145 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2146 if (hook->wanted & FDE_WRITE)
2147 hook->ready |= FDE_WRITE;
2148 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2149 hook->ready |= FDE_ERROR;
2150 }
2151 if ( evts->lNetworkEvents & FD_OOB ) {
2152 if (hook->wanted & FDE_ERROR)
2153 hook->ready |= FDE_ERROR;
2154 }
2155}
2156
2157static void _event_socket_prepare( EventHook hook )
2158{
2159 WSANETWORKEVENTS evts;
2160
2161 /* look if some of the events we want already happened ? */
2162 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2163 _event_socket_verify( hook, &evts );
2164}
2165
2166static int _socket_wanted_to_flags( int wanted )
2167{
2168 int flags = 0;
2169 if (wanted & FDE_READ)
2170 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2171
2172 if (wanted & FDE_WRITE)
2173 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2174
2175 if (wanted & FDE_ERROR)
2176 flags |= FD_OOB;
2177
2178 return flags;
2179}
2180
2181static int _event_socket_start( EventHook hook )
2182{
2183 /* create an event which we're going to wait for */
2184 FH fh = hook->fh;
2185 long flags = _socket_wanted_to_flags( hook->wanted );
2186
2187 hook->h = fh->event;
2188 if (hook->h == INVALID_HANDLE_VALUE) {
2189 D( "_event_socket_start: no event for %s\n", fh->name );
2190 return 0;
2191 }
2192
2193 if ( flags != fh->mask ) {
2194 D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
2195 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
2196 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
2197 CloseHandle( hook->h );
2198 hook->h = INVALID_HANDLE_VALUE;
2199 exit(1);
2200 return 0;
2201 }
2202 fh->mask = flags;
2203 }
2204 return 1;
2205}
2206
2207static void _event_socket_stop( EventHook hook )
2208{
2209 hook->h = INVALID_HANDLE_VALUE;
2210}
2211
2212static int _event_socket_check( EventHook hook )
2213{
2214 int result = 0;
2215 FH fh = hook->fh;
2216 WSANETWORKEVENTS evts;
2217
2218 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2219 _event_socket_verify( hook, &evts );
2220 result = (hook->ready != 0);
2221 if (result) {
2222 ResetEvent( hook->h );
2223 }
2224 }
2225 D( "_event_socket_check %s returns %d\n", fh->name, result );
2226 return result;
2227}
2228
2229static int _event_socket_peek( EventHook hook )
2230{
2231 WSANETWORKEVENTS evts;
2232 FH fh = hook->fh;
2233
2234 /* look if some of the events we want already happened ? */
2235 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2236 _event_socket_verify( hook, &evts );
2237 if (hook->ready)
2238 ResetEvent( hook->h );
2239 }
2240
2241 return hook->ready != 0;
2242}
2243
2244
2245
2246static void _fh_socket_hook( FH f, int events, EventHook hook )
2247{
2248 hook->prepare = _event_socket_prepare;
2249 hook->start = _event_socket_start;
2250 hook->stop = _event_socket_stop;
2251 hook->check = _event_socket_check;
2252 hook->peek = _event_socket_peek;
2253
Spencer Low753d4852015-07-30 23:07:55 -07002254 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002255 _event_socket_start( hook );
2256}
2257
2258/** SOCKETPAIR EVENT HOOKS
2259 **/
2260
2261static void _event_socketpair_prepare( EventHook hook )
2262{
2263 FH fh = hook->fh;
2264 SocketPair pair = fh->fh_pair;
2265 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2266 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2267
2268 if (hook->wanted & FDE_READ && rbip->can_read)
2269 hook->ready |= FDE_READ;
2270
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002271 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002272 hook->ready |= FDE_WRITE;
2273 }
2274
2275 static int _event_socketpair_start( EventHook hook )
2276 {
2277 FH fh = hook->fh;
2278 SocketPair pair = fh->fh_pair;
2279 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2280 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2281
2282 if (hook->wanted == FDE_READ)
2283 hook->h = rbip->evt_read;
2284
2285 else if (hook->wanted == FDE_WRITE)
2286 hook->h = wbip->evt_write;
2287
2288 else {
2289 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
2290 return 0;
2291 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002292 D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002293 hook->fh->name, _fh_to_int(fh), hook->wanted);
2294 return 1;
2295}
2296
2297static int _event_socketpair_peek( EventHook hook )
2298{
2299 _event_socketpair_prepare( hook );
2300 return hook->ready != 0;
2301}
2302
2303static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2304{
2305 hook->prepare = _event_socketpair_prepare;
2306 hook->start = _event_socketpair_start;
2307 hook->peek = _event_socketpair_peek;
2308}
2309
2310
2311void
2312adb_sysdeps_init( void )
2313{
2314#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2315#include "mutex_list.h"
2316 InitializeCriticalSection( &_win32_lock );
2317}
2318
Spencer Lowbeb61982015-03-01 15:06:21 -08002319/**************************************************************************/
2320/**************************************************************************/
2321/***** *****/
2322/***** Console Window Terminal Emulation *****/
2323/***** *****/
2324/**************************************************************************/
2325/**************************************************************************/
2326
2327// This reads input from a Win32 console window and translates it into Unix
2328// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2329// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2330// is emulated instead of xterm because it is probably more popular than xterm:
2331// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2332// supports modern fonts, etc. It seems best to emulate the terminal that most
2333// Android developers use because they'll fix apps (the shell, etc.) to keep
2334// working with that terminal's emulation.
2335//
2336// The point of this emulation is not to be perfect or to solve all issues with
2337// console windows on Windows, but to be better than the original code which
2338// just called read() (which called ReadFile(), which called ReadConsoleA())
2339// which did not support Ctrl-C, tab completion, shell input line editing
2340// keys, server echo, and more.
2341//
2342// This implementation reconfigures the console with SetConsoleMode(), then
2343// calls ReadConsoleInput() to get raw input which it remaps to Unix
2344// terminal-style sequences which is returned via unix_read() which is used
2345// by the 'adb shell' command.
2346//
2347// Code organization:
2348//
2349// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2350// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2351// * _console_read() is the main code of the emulation.
2352
2353
2354// Read an input record from the console; one that should be processed.
2355static bool _get_interesting_input_record_uncached(const HANDLE console,
2356 INPUT_RECORD* const input_record) {
2357 for (;;) {
2358 DWORD read_count = 0;
2359 memset(input_record, 0, sizeof(*input_record));
2360 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2361 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
Spencer Low1711e012015-08-02 18:50:17 -07002362 "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002363 errno = EIO;
2364 return false;
2365 }
2366
2367 if (read_count == 0) { // should be impossible
2368 fatal("ReadConsoleInputA returned 0");
2369 }
2370
2371 if (read_count != 1) { // should be impossible
2372 fatal("ReadConsoleInputA did not return one input record");
2373 }
2374
2375 if ((input_record->EventType == KEY_EVENT) &&
2376 (input_record->Event.KeyEvent.bKeyDown)) {
2377 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2378 fatal("ReadConsoleInputA returned a key event with zero repeat"
2379 " count");
2380 }
2381
2382 // Got an interesting INPUT_RECORD, so return
2383 return true;
2384 }
2385 }
2386}
2387
2388// Cached input record (in case _console_read() is passed a buffer that doesn't
2389// have enough space to fit wRepeatCount number of key sequences). A non-zero
2390// wRepeatCount indicates that a record is cached.
2391static INPUT_RECORD _win32_input_record;
2392
2393// Get the next KEY_EVENT_RECORD that should be processed.
2394static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2395 // If nothing cached, read directly from the console until we get an
2396 // interesting record.
2397 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2398 if (!_get_interesting_input_record_uncached(console,
2399 &_win32_input_record)) {
2400 // There was an error, so make sure wRepeatCount is zero because
2401 // that signifies no cached input record.
2402 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2403 return NULL;
2404 }
2405 }
2406
2407 return &_win32_input_record.Event.KeyEvent;
2408}
2409
2410static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2411 return (control_key_state & SHIFT_PRESSED) != 0;
2412}
2413
2414static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2415 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2416}
2417
2418static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2419 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2420}
2421
2422static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2423 return (control_key_state & NUMLOCK_ON) != 0;
2424}
2425
2426static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2427 return (control_key_state & CAPSLOCK_ON) != 0;
2428}
2429
2430static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2431 return (control_key_state & ENHANCED_KEY) != 0;
2432}
2433
2434// Constants from MSDN for ToAscii().
2435static const BYTE TOASCII_KEY_OFF = 0x00;
2436static const BYTE TOASCII_KEY_DOWN = 0x80;
2437static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2438
2439// Given a key event, ignore a modifier key and return the character that was
2440// entered without the modifier. Writes to *ch and returns the number of bytes
2441// written.
2442static size_t _get_char_ignoring_modifier(char* const ch,
2443 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2444 const WORD modifier) {
2445 // If there is no character from Windows, try ignoring the specified
2446 // modifier and look for a character. Note that if AltGr is being used,
2447 // there will be a character from Windows.
2448 if (key_event->uChar.AsciiChar == '\0') {
2449 // Note that we read the control key state from the passed in argument
2450 // instead of from key_event since the argument has been normalized.
2451 if (((modifier == VK_SHIFT) &&
2452 _is_shift_pressed(control_key_state)) ||
2453 ((modifier == VK_CONTROL) &&
2454 _is_ctrl_pressed(control_key_state)) ||
2455 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2456
2457 BYTE key_state[256] = {0};
2458 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2459 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2460 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2461 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2462 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2463 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2464 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2465 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2466
2467 // cause this modifier to be ignored
2468 key_state[modifier] = TOASCII_KEY_OFF;
2469
2470 WORD translated = 0;
2471 if (ToAscii(key_event->wVirtualKeyCode,
2472 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2473 // Ignoring the modifier, we found a character.
2474 *ch = (CHAR)translated;
2475 return 1;
2476 }
2477 }
2478 }
2479
2480 // Just use whatever Windows told us originally.
2481 *ch = key_event->uChar.AsciiChar;
2482
2483 // If the character from Windows is NULL, return a size of zero.
2484 return (*ch == '\0') ? 0 : 1;
2485}
2486
2487// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2488// but taking into account the shift key. This is because for a sequence like
2489// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2490// we want to find the character ')'.
2491//
2492// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2493// because it is the default key-sequence to switch the input language.
2494// This is configurable in the Region and Language control panel.
2495static __inline__ size_t _get_non_control_char(char* const ch,
2496 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2497 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2498 VK_CONTROL);
2499}
2500
2501// Get without Alt.
2502static __inline__ size_t _get_non_alt_char(char* const ch,
2503 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2504 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2505 VK_MENU);
2506}
2507
2508// Ignore the control key, find the character from Windows, and apply any
2509// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2510// *pch and returns number of bytes written.
2511static size_t _get_control_character(char* const pch,
2512 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2513 const size_t len = _get_non_control_char(pch, key_event,
2514 control_key_state);
2515
2516 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2517 char ch = *pch;
2518 switch (ch) {
2519 case '2':
2520 case '@':
2521 case '`':
2522 ch = '\0';
2523 break;
2524 case '3':
2525 case '[':
2526 case '{':
2527 ch = '\x1b';
2528 break;
2529 case '4':
2530 case '\\':
2531 case '|':
2532 ch = '\x1c';
2533 break;
2534 case '5':
2535 case ']':
2536 case '}':
2537 ch = '\x1d';
2538 break;
2539 case '6':
2540 case '^':
2541 case '~':
2542 ch = '\x1e';
2543 break;
2544 case '7':
2545 case '-':
2546 case '_':
2547 ch = '\x1f';
2548 break;
2549 case '8':
2550 ch = '\x7f';
2551 break;
2552 case '/':
2553 if (!_is_alt_pressed(control_key_state)) {
2554 ch = '\x1f';
2555 }
2556 break;
2557 case '?':
2558 if (!_is_alt_pressed(control_key_state)) {
2559 ch = '\x7f';
2560 }
2561 break;
2562 }
2563 *pch = ch;
2564 }
2565
2566 return len;
2567}
2568
2569static DWORD _normalize_altgr_control_key_state(
2570 const KEY_EVENT_RECORD* const key_event) {
2571 DWORD control_key_state = key_event->dwControlKeyState;
2572
2573 // If we're in an AltGr situation where the AltGr key is down (depending on
2574 // the keyboard layout, that might be the physical right alt key which
2575 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2576 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2577 // a character (which indicates that there was an AltGr mapping), then act
2578 // as if alt and control are not really down for the purposes of modifiers.
2579 // This makes it so that if the user with, say, a German keyboard layout
2580 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2581 // output the key and we don't see the Alt and Ctrl keys.
2582 if (_is_ctrl_pressed(control_key_state) &&
2583 _is_alt_pressed(control_key_state)
2584 && (key_event->uChar.AsciiChar != '\0')) {
2585 // Try to remove as few bits as possible to improve our chances of
2586 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2587 // Left-Alt + Right-Ctrl + AltGr.
2588 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2589 // Remove Right-Alt.
2590 control_key_state &= ~RIGHT_ALT_PRESSED;
2591 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2592 // pressed, Left-Ctrl is almost always set, except if the user
2593 // presses Right-Ctrl, then AltGr (in that specific order) for
2594 // whatever reason. At any rate, make sure the bit is not set.
2595 control_key_state &= ~LEFT_CTRL_PRESSED;
2596 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2597 // Remove Left-Alt.
2598 control_key_state &= ~LEFT_ALT_PRESSED;
2599 // Whichever Ctrl key is down, remove it from the state. We only
2600 // remove one key, to improve our chances of detecting the
2601 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2602 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2603 // Remove Left-Ctrl.
2604 control_key_state &= ~LEFT_CTRL_PRESSED;
2605 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2606 // Remove Right-Ctrl.
2607 control_key_state &= ~RIGHT_CTRL_PRESSED;
2608 }
2609 }
2610
2611 // Note that this logic isn't 100% perfect because Windows doesn't
2612 // allow us to detect all combinations because a physical AltGr key
2613 // press shows up as two bits, plus some combinations are ambiguous
2614 // about what is actually physically pressed.
2615 }
2616
2617 return control_key_state;
2618}
2619
2620// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2621// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2622// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2623// appropriately.
2624static DWORD _normalize_keypad_control_key_state(const WORD vk,
2625 const DWORD control_key_state) {
2626 if (!_is_numlock_on(control_key_state)) {
2627 return control_key_state;
2628 }
2629 if (!_is_enhanced_key(control_key_state)) {
2630 switch (vk) {
2631 case VK_INSERT: // 0
2632 case VK_DELETE: // .
2633 case VK_END: // 1
2634 case VK_DOWN: // 2
2635 case VK_NEXT: // 3
2636 case VK_LEFT: // 4
2637 case VK_CLEAR: // 5
2638 case VK_RIGHT: // 6
2639 case VK_HOME: // 7
2640 case VK_UP: // 8
2641 case VK_PRIOR: // 9
2642 return control_key_state | SHIFT_PRESSED;
2643 }
2644 }
2645
2646 return control_key_state;
2647}
2648
2649static const char* _get_keypad_sequence(const DWORD control_key_state,
2650 const char* const normal, const char* const shifted) {
2651 if (_is_shift_pressed(control_key_state)) {
2652 // Shift is pressed and NumLock is off
2653 return shifted;
2654 } else {
2655 // Shift is not pressed and NumLock is off, or,
2656 // Shift is pressed and NumLock is on, in which case we want the
2657 // NumLock and Shift to neutralize each other, thus, we want the normal
2658 // sequence.
2659 return normal;
2660 }
2661 // If Shift is not pressed and NumLock is on, a different virtual key code
2662 // is returned by Windows, which can be taken care of by a different case
2663 // statement in _console_read().
2664}
2665
2666// Write sequence to buf and return the number of bytes written.
2667static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2668 DWORD control_key_state, const char* const normal) {
2669 // Copy the base sequence into buf.
2670 const size_t len = strlen(normal);
2671 memcpy(buf, normal, len);
2672
2673 int code = 0;
2674
2675 control_key_state = _normalize_keypad_control_key_state(vk,
2676 control_key_state);
2677
2678 if (_is_shift_pressed(control_key_state)) {
2679 code |= 0x1;
2680 }
2681 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2682 code |= 0x2;
2683 }
2684 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2685 code |= 0x4;
2686 }
2687 // If some modifier was held down, then we need to insert the modifier code
2688 if (code != 0) {
2689 if (len == 0) {
2690 // Should be impossible because caller should pass a string of
2691 // non-zero length.
2692 return 0;
2693 }
2694 size_t index = len - 1;
2695 const char lastChar = buf[index];
2696 if (lastChar != '~') {
2697 buf[index++] = '1';
2698 }
2699 buf[index++] = ';'; // modifier separator
2700 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2701 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2702 buf[index++] = '1' + code;
2703 buf[index++] = lastChar; // move ~ (or other last char) to the end
2704 return index;
2705 }
2706 return len;
2707}
2708
2709// Write sequence to buf and return the number of bytes written.
2710static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2711 const DWORD control_key_state, const char* const normal,
2712 const char shifted) {
2713 if (_is_shift_pressed(control_key_state)) {
2714 // Shift is pressed and NumLock is off
2715 if (shifted != '\0') {
2716 buf[0] = shifted;
2717 return sizeof(buf[0]);
2718 } else {
2719 return 0;
2720 }
2721 } else {
2722 // Shift is not pressed and NumLock is off, or,
2723 // Shift is pressed and NumLock is on, in which case we want the
2724 // NumLock and Shift to neutralize each other, thus, we want the normal
2725 // sequence.
2726 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2727 }
2728 // If Shift is not pressed and NumLock is on, a different virtual key code
2729 // is returned by Windows, which can be taken care of by a different case
2730 // statement in _console_read().
2731}
2732
2733// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2734// Standard German. Figure this out at runtime so we know what to output for
2735// Shift-VK_DELETE.
2736static char _get_decimal_char() {
2737 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2738}
2739
2740// Prefix the len bytes in buf with the escape character, and then return the
2741// new buffer length.
2742size_t _escape_prefix(char* const buf, const size_t len) {
2743 // If nothing to prefix, don't do anything. We might be called with
2744 // len == 0, if alt was held down with a dead key which produced nothing.
2745 if (len == 0) {
2746 return 0;
2747 }
2748
2749 memmove(&buf[1], buf, len);
2750 buf[0] = '\x1b';
2751 return len + 1;
2752}
2753
2754// Writes to buffer buf (of length len), returning number of bytes written or
2755// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2756// (as far as I can tell).
2757static int _console_read(const HANDLE console, void* buf, size_t len) {
2758 for (;;) {
2759 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2760 if (key_event == NULL) {
2761 return -1;
2762 }
2763
2764 const WORD vk = key_event->wVirtualKeyCode;
2765 const CHAR ch = key_event->uChar.AsciiChar;
2766 const DWORD control_key_state = _normalize_altgr_control_key_state(
2767 key_event);
2768
2769 // The following emulation code should write the output sequence to
2770 // either seqstr or to seqbuf and seqbuflen.
2771 const char* seqstr = NULL; // NULL terminated C-string
2772 // Enough space for max sequence string below, plus modifiers and/or
2773 // escape prefix.
2774 char seqbuf[16];
2775 size_t seqbuflen = 0; // Space used in seqbuf.
2776
2777#define MATCH(vk, normal) \
2778 case (vk): \
2779 { \
2780 seqstr = (normal); \
2781 } \
2782 break;
2783
2784 // Modifier keys should affect the output sequence.
2785#define MATCH_MODIFIER(vk, normal) \
2786 case (vk): \
2787 { \
2788 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2789 control_key_state, (normal)); \
2790 } \
2791 break;
2792
2793 // The shift key should affect the output sequence.
2794#define MATCH_KEYPAD(vk, normal, shifted) \
2795 case (vk): \
2796 { \
2797 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2798 (shifted)); \
2799 } \
2800 break;
2801
2802 // The shift key and other modifier keys should affect the output
2803 // sequence.
2804#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2805 case (vk): \
2806 { \
2807 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2808 control_key_state, (normal), (shifted)); \
2809 } \
2810 break;
2811
2812#define ESC "\x1b"
2813#define CSI ESC "["
2814#define SS3 ESC "O"
2815
2816 // Only support normal mode, not application mode.
2817
2818 // Enhanced keys:
2819 // * 6-pack: insert, delete, home, end, page up, page down
2820 // * cursor keys: up, down, right, left
2821 // * keypad: divide, enter
2822 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2823 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2824 if (_is_enhanced_key(control_key_state)) {
2825 switch (vk) {
2826 case VK_RETURN: // Enter key on keypad
2827 if (_is_ctrl_pressed(control_key_state)) {
2828 seqstr = "\n";
2829 } else {
2830 seqstr = "\r";
2831 }
2832 break;
2833
2834 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2835 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2836
2837 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2838 // will be fixed soon to match xterm which sends CSI "F" and
2839 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2840 MATCH(VK_END, CSI "F");
2841 MATCH(VK_HOME, CSI "H");
2842
2843 MATCH_MODIFIER(VK_LEFT, CSI "D");
2844 MATCH_MODIFIER(VK_UP, CSI "A");
2845 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2846 MATCH_MODIFIER(VK_DOWN, CSI "B");
2847
2848 MATCH_MODIFIER(VK_INSERT, CSI "2~");
2849 MATCH_MODIFIER(VK_DELETE, CSI "3~");
2850
2851 MATCH(VK_DIVIDE, "/");
2852 }
2853 } else { // Non-enhanced keys:
2854 switch (vk) {
2855 case VK_BACK: // backspace
2856 if (_is_alt_pressed(control_key_state)) {
2857 seqstr = ESC "\x7f";
2858 } else {
2859 seqstr = "\x7f";
2860 }
2861 break;
2862
2863 case VK_TAB:
2864 if (_is_shift_pressed(control_key_state)) {
2865 seqstr = CSI "Z";
2866 } else {
2867 seqstr = "\t";
2868 }
2869 break;
2870
2871 // Number 5 key in keypad when NumLock is off, or if NumLock is
2872 // on and Shift is down.
2873 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2874
2875 case VK_RETURN: // Enter key on main keyboard
2876 if (_is_alt_pressed(control_key_state)) {
2877 seqstr = ESC "\n";
2878 } else if (_is_ctrl_pressed(control_key_state)) {
2879 seqstr = "\n";
2880 } else {
2881 seqstr = "\r";
2882 }
2883 break;
2884
2885 // VK_ESCAPE: Don't do any special handling. The OS uses many
2886 // of the sequences with Escape and many of the remaining
2887 // sequences don't produce bKeyDown messages, only !bKeyDown
2888 // for whatever reason.
2889
2890 case VK_SPACE:
2891 if (_is_alt_pressed(control_key_state)) {
2892 seqstr = ESC " ";
2893 } else if (_is_ctrl_pressed(control_key_state)) {
2894 seqbuf[0] = '\0'; // NULL char
2895 seqbuflen = 1;
2896 } else {
2897 seqstr = " ";
2898 }
2899 break;
2900
2901 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2902 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
2903
2904 MATCH_KEYPAD(VK_END, CSI "4~", "1");
2905 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2906
2907 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
2908 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
2909 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2910 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
2911
2912 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2913 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2914 _get_decimal_char());
2915
2916 case 0x30: // 0
2917 case 0x31: // 1
2918 case 0x39: // 9
2919 case VK_OEM_1: // ;:
2920 case VK_OEM_PLUS: // =+
2921 case VK_OEM_COMMA: // ,<
2922 case VK_OEM_PERIOD: // .>
2923 case VK_OEM_7: // '"
2924 case VK_OEM_102: // depends on keyboard, could be <> or \|
2925 case VK_OEM_2: // /?
2926 case VK_OEM_3: // `~
2927 case VK_OEM_4: // [{
2928 case VK_OEM_5: // \|
2929 case VK_OEM_6: // ]}
2930 {
2931 seqbuflen = _get_control_character(seqbuf, key_event,
2932 control_key_state);
2933
2934 if (_is_alt_pressed(control_key_state)) {
2935 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2936 }
2937 }
2938 break;
2939
2940 case 0x32: // 2
2941 case 0x36: // 6
2942 case VK_OEM_MINUS: // -_
2943 {
2944 seqbuflen = _get_control_character(seqbuf, key_event,
2945 control_key_state);
2946
2947 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2948 // prefix with escape.
2949 if (_is_alt_pressed(control_key_state) &&
2950 !(_is_ctrl_pressed(control_key_state) &&
2951 !_is_shift_pressed(control_key_state))) {
2952 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2953 }
2954 }
2955 break;
2956
2957 case 0x33: // 3
2958 case 0x34: // 4
2959 case 0x35: // 5
2960 case 0x37: // 7
2961 case 0x38: // 8
2962 {
2963 seqbuflen = _get_control_character(seqbuf, key_event,
2964 control_key_state);
2965
2966 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2967 // prefix with escape.
2968 if (_is_alt_pressed(control_key_state) &&
2969 !(_is_ctrl_pressed(control_key_state) &&
2970 !_is_shift_pressed(control_key_state))) {
2971 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2972 }
2973 }
2974 break;
2975
2976 case 0x41: // a
2977 case 0x42: // b
2978 case 0x43: // c
2979 case 0x44: // d
2980 case 0x45: // e
2981 case 0x46: // f
2982 case 0x47: // g
2983 case 0x48: // h
2984 case 0x49: // i
2985 case 0x4a: // j
2986 case 0x4b: // k
2987 case 0x4c: // l
2988 case 0x4d: // m
2989 case 0x4e: // n
2990 case 0x4f: // o
2991 case 0x50: // p
2992 case 0x51: // q
2993 case 0x52: // r
2994 case 0x53: // s
2995 case 0x54: // t
2996 case 0x55: // u
2997 case 0x56: // v
2998 case 0x57: // w
2999 case 0x58: // x
3000 case 0x59: // y
3001 case 0x5a: // z
3002 {
3003 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3004 control_key_state);
3005
3006 // If Alt is pressed, then prefix with escape.
3007 if (_is_alt_pressed(control_key_state)) {
3008 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3009 }
3010 }
3011 break;
3012
3013 // These virtual key codes are generated by the keys on the
3014 // keypad *when NumLock is on* and *Shift is up*.
3015 MATCH(VK_NUMPAD0, "0");
3016 MATCH(VK_NUMPAD1, "1");
3017 MATCH(VK_NUMPAD2, "2");
3018 MATCH(VK_NUMPAD3, "3");
3019 MATCH(VK_NUMPAD4, "4");
3020 MATCH(VK_NUMPAD5, "5");
3021 MATCH(VK_NUMPAD6, "6");
3022 MATCH(VK_NUMPAD7, "7");
3023 MATCH(VK_NUMPAD8, "8");
3024 MATCH(VK_NUMPAD9, "9");
3025
3026 MATCH(VK_MULTIPLY, "*");
3027 MATCH(VK_ADD, "+");
3028 MATCH(VK_SUBTRACT, "-");
3029 // VK_DECIMAL is generated by the . key on the keypad *when
3030 // NumLock is on* and *Shift is up* and the sequence is not
3031 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3032 // Windows Security screen to come up).
3033 case VK_DECIMAL:
3034 // U.S. English uses '.', Germany German uses ','.
3035 seqbuflen = _get_non_control_char(seqbuf, key_event,
3036 control_key_state);
3037 break;
3038
3039 MATCH_MODIFIER(VK_F1, SS3 "P");
3040 MATCH_MODIFIER(VK_F2, SS3 "Q");
3041 MATCH_MODIFIER(VK_F3, SS3 "R");
3042 MATCH_MODIFIER(VK_F4, SS3 "S");
3043 MATCH_MODIFIER(VK_F5, CSI "15~");
3044 MATCH_MODIFIER(VK_F6, CSI "17~");
3045 MATCH_MODIFIER(VK_F7, CSI "18~");
3046 MATCH_MODIFIER(VK_F8, CSI "19~");
3047 MATCH_MODIFIER(VK_F9, CSI "20~");
3048 MATCH_MODIFIER(VK_F10, CSI "21~");
3049 MATCH_MODIFIER(VK_F11, CSI "23~");
3050 MATCH_MODIFIER(VK_F12, CSI "24~");
3051
3052 MATCH_MODIFIER(VK_F13, CSI "25~");
3053 MATCH_MODIFIER(VK_F14, CSI "26~");
3054 MATCH_MODIFIER(VK_F15, CSI "28~");
3055 MATCH_MODIFIER(VK_F16, CSI "29~");
3056 MATCH_MODIFIER(VK_F17, CSI "31~");
3057 MATCH_MODIFIER(VK_F18, CSI "32~");
3058 MATCH_MODIFIER(VK_F19, CSI "33~");
3059 MATCH_MODIFIER(VK_F20, CSI "34~");
3060
3061 // MATCH_MODIFIER(VK_F21, ???);
3062 // MATCH_MODIFIER(VK_F22, ???);
3063 // MATCH_MODIFIER(VK_F23, ???);
3064 // MATCH_MODIFIER(VK_F24, ???);
3065 }
3066 }
3067
3068#undef MATCH
3069#undef MATCH_MODIFIER
3070#undef MATCH_KEYPAD
3071#undef MATCH_MODIFIER_KEYPAD
3072#undef ESC
3073#undef CSI
3074#undef SS3
3075
3076 const char* out;
3077 size_t outlen;
3078
3079 // Check for output in any of:
3080 // * seqstr is set (and strlen can be used to determine the length).
3081 // * seqbuf and seqbuflen are set
3082 // Fallback to ch from Windows.
3083 if (seqstr != NULL) {
3084 out = seqstr;
3085 outlen = strlen(seqstr);
3086 } else if (seqbuflen > 0) {
3087 out = seqbuf;
3088 outlen = seqbuflen;
3089 } else if (ch != '\0') {
3090 // Use whatever Windows told us it is.
3091 seqbuf[0] = ch;
3092 seqbuflen = 1;
3093 out = seqbuf;
3094 outlen = seqbuflen;
3095 } else {
3096 // No special handling for the virtual key code and Windows isn't
3097 // telling us a character code, then we don't know how to translate
3098 // the key press.
3099 //
3100 // Consume the input and 'continue' to cause us to get a new key
3101 // event.
3102 D("_console_read: unknown virtual key code: %d, enhanced: %s\n",
3103 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3104 key_event->wRepeatCount = 0;
3105 continue;
3106 }
3107
3108 int bytesRead = 0;
3109
3110 // put output wRepeatCount times into buf/len
3111 while (key_event->wRepeatCount > 0) {
3112 if (len >= outlen) {
3113 // Write to buf/len
3114 memcpy(buf, out, outlen);
3115 buf = (void*)((char*)buf + outlen);
3116 len -= outlen;
3117 bytesRead += outlen;
3118
3119 // consume the input
3120 --key_event->wRepeatCount;
3121 } else {
3122 // Not enough space, so just leave it in _win32_input_record
3123 // for a subsequent retrieval.
3124 if (bytesRead == 0) {
3125 // We didn't write anything because there wasn't enough
3126 // space to even write one sequence. This should never
3127 // happen if the caller uses sensible buffer sizes
3128 // (i.e. >= maximum sequence length which is probably a
3129 // few bytes long).
3130 D("_console_read: no buffer space to write one sequence; "
3131 "buffer: %ld, sequence: %ld\n", (long)len,
3132 (long)outlen);
3133 errno = ENOMEM;
3134 return -1;
3135 } else {
3136 // Stop trying to write to buf/len, just return whatever
3137 // we wrote so far.
3138 break;
3139 }
3140 }
3141 }
3142
3143 return bytesRead;
3144 }
3145}
3146
3147static DWORD _old_console_mode; // previous GetConsoleMode() result
3148static HANDLE _console_handle; // when set, console mode should be restored
3149
3150void stdin_raw_init(const int fd) {
3151 if (STDIN_FILENO == fd) {
3152 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3153 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3154 return;
3155 }
3156
3157 if (GetFileType(in) != FILE_TYPE_CHAR) {
3158 // stdin might be a file or pipe.
3159 return;
3160 }
3161
3162 if (!GetConsoleMode(in, &_old_console_mode)) {
3163 // If GetConsoleMode() fails, stdin is probably is not a console.
3164 return;
3165 }
3166
3167 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3168 // calling the process Ctrl-C routine (configured by
3169 // SetConsoleCtrlHandler()).
3170 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3171 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3172 // flag also seems necessary to have proper line-ending processing.
3173 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3174 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3175 // This really should not fail.
Spencer Low1711e012015-08-02 18:50:17 -07003176 D("stdin_raw_init: SetConsoleMode() failed: %s\n",
3177 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003178 }
3179
3180 // Once this is set, it means that stdin has been configured for
3181 // reading from and that the old console mode should be restored later.
3182 _console_handle = in;
3183
3184 // Note that we don't need to configure C Runtime line-ending
3185 // translation because _console_read() does not call the C Runtime to
3186 // read from the console.
3187 }
3188}
3189
3190void stdin_raw_restore(const int fd) {
3191 if (STDIN_FILENO == fd) {
3192 if (_console_handle != NULL) {
3193 const HANDLE in = _console_handle;
3194 _console_handle = NULL; // clear state
3195
3196 if (!SetConsoleMode(in, _old_console_mode)) {
3197 // This really should not fail.
Spencer Low1711e012015-08-02 18:50:17 -07003198 D("stdin_raw_restore: SetConsoleMode() failed: %s\n",
3199 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003200 }
3201 }
3202 }
3203}
3204
Spencer Low3a2421b2015-05-22 20:09:06 -07003205// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003206int unix_read(int fd, void* buf, size_t len) {
3207 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3208 // If it is a request to read from stdin, and stdin_raw_init() has been
3209 // called, and it successfully configured the console, then read from
3210 // the console using Win32 console APIs and partially emulate a unix
3211 // terminal.
3212 return _console_read(_console_handle, buf, len);
3213 } else {
3214 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003215 // can do LF/CR translation (which is overridable with _setmode()).
3216 // Undefine the macro that is set in sysdeps.h which bans calls to
3217 // plain read() in favor of unix_read() or adb_read().
3218#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003219#undef read
3220 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003221#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003222 }
3223}
Spencer Low6815c072015-05-11 01:08:48 -07003224
3225/**************************************************************************/
3226/**************************************************************************/
3227/***** *****/
3228/***** Unicode support *****/
3229/***** *****/
3230/**************************************************************************/
3231/**************************************************************************/
3232
3233// This implements support for using files with Unicode filenames and for
3234// outputting Unicode text to a Win32 console window. This is inspired from
3235// http://utf8everywhere.org/.
3236//
3237// Background
3238// ----------
3239//
3240// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3241// filenames to APIs such as open(). This works because filenames are largely
3242// opaque 'cookies' (perhaps excluding path separators).
3243//
3244// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3245// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3246// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3247// CreateFile() API is really just a macro that adds the W/A based on whether
3248// the UNICODE preprocessor symbol is defined).
3249//
3250// Options
3251// -------
3252//
3253// Thus, to write a portable program, there are a few options:
3254//
3255// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3256// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3257// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3258// open() API.
3259//
3260// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3261// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3262// potentially touching a lot of code.
3263//
3264// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3265// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3266// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3267// or C Runtime API.
3268//
3269// The Choice
3270// ----------
3271//
3272// The code below chooses option 3, the UTF-8 everywhere strategy. It
3273// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3274// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3275// args that are passed to main() at the beginning of program startup. We also
3276// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3277// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3278//
3279// Unicode console output
3280// ----------------------
3281//
3282// The way to output Unicode to a Win32 console window is to call
3283// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003284// such as Lucida Console or Consolas, and in the case of East Asian languages
3285// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3286// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3287// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003288//
3289// The problem is getting the C Runtime to make fprintf and related APIs call
3290// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3291// promising, but the various modes have issues:
3292//
3293// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3294// UTF-16 do not display properly.
3295// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3296// totally wrong.
3297// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3298// handler to be called (upon a later I/O call), aborting the process.
3299// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3300// to output nothing.
3301//
3302// So the only solution is to write our own adb_fprintf() that converts UTF-8
3303// to UTF-16 and then calls WriteConsoleW().
3304
3305
3306// Function prototype because attributes cannot be placed on func definitions.
3307static void _widen_fatal(const char *fmt, ...)
3308 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3309
3310// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3311// called from those functions.
3312static void _widen_fatal(const char *fmt, ...) {
3313 va_list ap;
3314 va_start(ap, fmt);
3315 // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3316 // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3317 // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3318 // By directly calling real C Runtime APIs that don't properly output
3319 // Unicode, but will be able to get a comprehendible message out. To do
3320 // this, make sure we don't call (v)fprintf macros by undefining them.
3321#pragma push_macro("fprintf")
3322#pragma push_macro("vfprintf")
3323#undef fprintf
3324#undef vfprintf
3325 fprintf(stderr, "error: ");
3326 vfprintf(stderr, fmt, ap);
3327 fprintf(stderr, "\n");
3328#pragma pop_macro("vfprintf")
3329#pragma pop_macro("fprintf")
3330 va_end(ap);
3331 exit(-1);
3332}
3333
3334// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3335// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3336
3337// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3338// string. Any other size specifies the number of chars to convert, excluding
3339// any NULL terminator (if you're passing an explicit size, you probably don't
3340// have a NULL terminated string in the first place).
3341std::wstring widen(const char* utf8, const int size) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003342 // Note: Do not call SystemErrorCodeToString() from widen() because
3343 // SystemErrorCodeToString() calls narrow() which may call fatal() which
3344 // calls adb_vfprintf() which calls widen(), potentially causing infinite
3345 // recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003346 const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3347 NULL, 0);
3348 if (chars_to_convert <= 0) {
3349 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3350 _widen_fatal("MultiByteToWideChar failed counting: %d, "
3351 "GetLastError: %lu", chars_to_convert, GetLastError());
3352 }
3353
3354 std::wstring utf16;
3355 size_t chars_to_allocate = chars_to_convert;
3356 if (size == -1) {
3357 // chars_to_convert includes a NULL terminator, so subtract space
3358 // for that because resize() includes that itself.
3359 --chars_to_allocate;
3360 }
3361 utf16.resize(chars_to_allocate);
3362
3363 // This uses &string[0] to get write-access to the entire string buffer
3364 // which may be assuming that the chars are all contiguous, but it seems
3365 // to work and saves us the hassle of using a temporary
3366 // std::vector<wchar_t>.
3367 const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3368 chars_to_convert);
3369 if (result != chars_to_convert) {
3370 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3371 _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3372 "GetLastError: %lu", result, GetLastError());
3373 }
3374
3375 // If a size was passed in (size != -1), then the string is NULL terminated
3376 // by a NULL char that was written by std::string::resize(). If size == -1,
3377 // then MultiByteToWideChar() read a NULL terminator from the original
3378 // string and converted it to a NULL UTF-16 char in the output.
3379
3380 return utf16;
3381}
3382
3383// Convert a NULL terminated string from UTF-8 to UTF-16.
3384std::wstring widen(const char* utf8) {
3385 // Pass -1 to let widen() determine the string length.
3386 return widen(utf8, -1);
3387}
3388
3389// Convert from UTF-8 to UTF-16.
3390std::wstring widen(const std::string& utf8) {
3391 return widen(utf8.c_str(), utf8.length());
3392}
3393
3394// Convert from UTF-16 to UTF-8.
3395std::string narrow(const std::wstring& utf16) {
3396 return narrow(utf16.c_str());
3397}
3398
3399// Convert from UTF-16 to UTF-8.
3400std::string narrow(const wchar_t* utf16) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003401 // Note: Do not call SystemErrorCodeToString() from narrow() because
Elliott Hughes1ba53092015-08-03 16:26:13 -07003402 // SystemErrorCodeToString() calls narrow() and we don't want potential
Spencer Lowcc467f12015-08-02 18:13:54 -07003403 // infinite recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003404 const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3405 0, NULL, NULL);
3406 if (chars_required <= 0) {
3407 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003408 fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003409 chars_required, GetLastError());
3410 }
3411
3412 std::string utf8;
3413 // Subtract space for the NULL terminator because resize() includes
3414 // that itself. Note that this could potentially throw a std::bad_alloc
3415 // exception.
3416 utf8.resize(chars_required - 1);
3417
3418 // This uses &string[0] to get write-access to the entire string buffer
3419 // which may be assuming that the chars are all contiguous, but it seems
3420 // to work and saves us the hassle of using a temporary
3421 // std::vector<char>.
3422 const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3423 chars_required, NULL, NULL);
3424 if (result != chars_required) {
3425 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003426 fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003427 result, GetLastError());
3428 }
3429
3430 return utf8;
3431}
3432
3433// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3434// be passed to main().
3435NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3436 narrow_args = new char*[argc + 1];
3437
3438 for (int i = 0; i < argc; ++i) {
3439 narrow_args[i] = strdup(narrow(argv[i]).c_str());
3440 }
3441 narrow_args[argc] = nullptr; // terminate
3442}
3443
3444NarrowArgs::~NarrowArgs() {
3445 if (narrow_args != nullptr) {
3446 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3447 free(*argp);
3448 }
3449 delete[] narrow_args;
3450 narrow_args = nullptr;
3451 }
3452}
3453
3454int unix_open(const char* path, int options, ...) {
3455 if ((options & O_CREAT) == 0) {
3456 return _wopen(widen(path).c_str(), options);
3457 } else {
3458 int mode;
3459 va_list args;
3460 va_start(args, options);
3461 mode = va_arg(args, int);
3462 va_end(args);
3463 return _wopen(widen(path).c_str(), options, mode);
3464 }
3465}
3466
3467// Version of stat() that takes a UTF-8 path.
3468int adb_stat(const char* f, struct adb_stat* s) {
3469#pragma push_macro("wstat")
3470// This definition of wstat seems to be missing from <sys/stat.h>.
3471#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3472#ifdef _USE_32BIT_TIME_T
3473#define wstat _wstat32i64
3474#else
3475#define wstat _wstat64
3476#endif
3477#else
3478// <sys/stat.h> has a function prototype for wstat() that should be available.
3479#endif
3480
3481 return wstat(widen(f).c_str(), s);
3482
3483#pragma pop_macro("wstat")
3484}
3485
3486// Version of opendir() that takes a UTF-8 path.
3487DIR* adb_opendir(const char* name) {
3488 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3489 // the fields, but right now all the callers treat the structure as
3490 // opaque.
3491 return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3492}
3493
3494// Version of readdir() that returns UTF-8 paths.
3495struct dirent* adb_readdir(DIR* dir) {
3496 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3497 struct _wdirent* const went = _wreaddir(wdir);
3498 if (went == nullptr) {
3499 return nullptr;
3500 }
3501 // Convert from UTF-16 to UTF-8.
3502 const std::string name_utf8(narrow(went->d_name));
3503
3504 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3505 // space for UTF-16 wchar_t's) with UTF-8 char's.
3506 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3507
3508 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3509 // Name too big to fit in existing buffer.
3510 errno = ENOMEM;
3511 return nullptr;
3512 }
3513
3514 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3515 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3516 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3517 // bigger than the caller expects because they expect a dirent structure
3518 // which has a smaller d_name field. Ignore this since the caller should be
3519 // resilient.
3520
3521 // Rewrite the UTF-16 d_name field to UTF-8.
3522 strcpy(ent->d_name, name_utf8.c_str());
3523
3524 return ent;
3525}
3526
3527// Version of closedir() to go with our version of adb_opendir().
3528int adb_closedir(DIR* dir) {
3529 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3530}
3531
3532// Version of unlink() that takes a UTF-8 path.
3533int adb_unlink(const char* path) {
3534 const std::wstring wpath(widen(path));
3535
3536 int rc = _wunlink(wpath.c_str());
3537
3538 if (rc == -1 && errno == EACCES) {
3539 /* unlink returns EACCES when the file is read-only, so we first */
3540 /* try to make it writable, then unlink again... */
3541 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3542 if (rc == 0)
3543 rc = _wunlink(wpath.c_str());
3544 }
3545 return rc;
3546}
3547
3548// Version of mkdir() that takes a UTF-8 path.
3549int adb_mkdir(const std::string& path, int mode) {
3550 return _wmkdir(widen(path.c_str()).c_str());
3551}
3552
3553// Version of utime() that takes a UTF-8 path.
3554int adb_utime(const char* path, struct utimbuf* u) {
3555 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3556 "utimbuf and _utimbuf should be the same size because they both "
3557 "contain the same types, namely time_t");
3558 return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3559}
3560
3561// Version of chmod() that takes a UTF-8 path.
3562int adb_chmod(const char* path, int mode) {
3563 return _wchmod(widen(path).c_str(), mode);
3564}
3565
3566// Internal function to get a Win32 console HANDLE from a C Runtime FILE*.
3567static HANDLE _get_console_handle(FILE* const stream) {
3568 // Get a C Runtime file descriptor number from the FILE* structure.
3569 const int fd = fileno(stream);
3570 if (fd < 0) {
3571 return NULL;
3572 }
3573
3574 // If it is not a "character device", it is probably a file and not a
3575 // console. Do this check early because it is probably cheap. Still do more
3576 // checks after this since there are devices that pass this test, but are
3577 // not a console, such as NUL, the Windows /dev/null equivalent (I think).
3578 if (!isatty(fd)) {
3579 return NULL;
3580 }
3581
3582 // Given a C Runtime file descriptor number, get the underlying OS
3583 // file handle.
3584 const intptr_t osfh = _get_osfhandle(fd);
3585 if (osfh == -1) {
3586 return NULL;
3587 }
3588
3589 const HANDLE h = reinterpret_cast<const HANDLE>(osfh);
3590
3591 DWORD old_mode = 0;
3592 if (!GetConsoleMode(h, &old_mode)) {
3593 return NULL;
3594 }
3595
3596 // If GetConsoleMode() was successful, assume this is a console.
3597 return h;
3598}
3599
3600// Internal helper function to write UTF-8 bytes to a console. Returns -1
3601// on error.
3602static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3603 HANDLE console) {
3604 // Convert from UTF-8 to UTF-16.
3605 // This could throw std::bad_alloc.
3606 const std::wstring output(widen(buf, size));
3607
3608 // Note that this does not do \n => \r\n translation because that
3609 // doesn't seem necessary for the Windows console. For the Windows
3610 // console \r moves to the beginning of the line and \n moves to a new
3611 // line.
3612
3613 // Flush any stream buffering so that our output is afterwards which
3614 // makes sense because our call is afterwards.
3615 (void)fflush(stream);
3616
3617 // Write UTF-16 to the console.
3618 DWORD written = 0;
3619 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3620 NULL)) {
3621 errno = EIO;
3622 return -1;
3623 }
3624
3625 // This is the number of UTF-16 chars written, which might be different
3626 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3627 // get this count correct.
3628 return written;
3629}
3630
3631// Function prototype because attributes cannot be placed on func definitions.
3632static int _console_vfprintf(const HANDLE console, FILE* stream,
3633 const char *format, va_list ap)
3634 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3635
3636// Internal function to format a UTF-8 string and write it to a Win32 console.
3637// Returns -1 on error.
3638static int _console_vfprintf(const HANDLE console, FILE* stream,
3639 const char *format, va_list ap) {
3640 std::string output_utf8;
3641
3642 // Format the string.
3643 // This could throw std::bad_alloc.
3644 android::base::StringAppendV(&output_utf8, format, ap);
3645
3646 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3647 stream, console);
3648}
3649
3650// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3651// Windows console.
3652int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3653 const HANDLE console = _get_console_handle(stream);
3654
3655 // If there is an associated Win32 console, write to it specially,
3656 // otherwise defer to the regular C Runtime, passing it UTF-8.
3657 if (console != NULL) {
3658 return _console_vfprintf(console, stream, format, ap);
3659 } else {
3660 // If vfprintf is a macro, undefine it, so we can call the real
3661 // C Runtime API.
3662#pragma push_macro("vfprintf")
3663#undef vfprintf
3664 return vfprintf(stream, format, ap);
3665#pragma pop_macro("vfprintf")
3666 }
3667}
3668
3669// Version of fprintf() that takes UTF-8 and can write Unicode to a
3670// Windows console.
3671int adb_fprintf(FILE *stream, const char *format, ...) {
3672 va_list ap;
3673 va_start(ap, format);
3674 const int result = adb_vfprintf(stream, format, ap);
3675 va_end(ap);
3676
3677 return result;
3678}
3679
3680// Version of printf() that takes UTF-8 and can write Unicode to a
3681// Windows console.
3682int adb_printf(const char *format, ...) {
3683 va_list ap;
3684 va_start(ap, format);
3685 const int result = adb_vfprintf(stdout, format, ap);
3686 va_end(ap);
3687
3688 return result;
3689}
3690
3691// Version of fputs() that takes UTF-8 and can write Unicode to a
3692// Windows console.
3693int adb_fputs(const char* buf, FILE* stream) {
3694 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3695 // which fputs (and hence adb_fputs) should return on error.
3696 return adb_fprintf(stream, "%s", buf);
3697}
3698
3699// Version of fputc() that takes UTF-8 and can write Unicode to a
3700// Windows console.
3701int adb_fputc(int ch, FILE* stream) {
3702 const int result = adb_fprintf(stream, "%c", ch);
3703 if (result <= 0) {
3704 // If there was an error, or if nothing was printed (which should be an
3705 // error), return an error, which fprintf signifies with EOF.
3706 return EOF;
3707 }
3708 // For success, fputc returns the char, cast to unsigned char, then to int.
3709 return static_cast<unsigned char>(ch);
3710}
3711
3712// Internal function to write UTF-8 to a Win32 console. Returns the number of
3713// items (of length size) written. On error, returns a short item count or 0.
3714static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3715 FILE* stream, HANDLE console) {
3716 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3717 // if we're passed only some of the bytes of a character (for example, from
3718 // the network socket for adb shell), we won't be able to convert the char
3719 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3720 // right.
3721 //
3722 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3723 //
3724 // For now we ignore this problem because the alternative is that we'd have
3725 // to parse UTF-8 and buffer things up (doable). At least this is better
3726 // than what we had before -- always incorrect multi-byte UTF-8 output.
3727 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3728 size * nmemb, stream, console);
3729 if (result == -1) {
3730 return 0;
3731 }
3732 return result / size;
3733}
3734
3735// Version of fwrite() that takes UTF-8 and can write Unicode to a
3736// Windows console.
3737size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3738 const HANDLE console = _get_console_handle(stream);
3739
3740 // If there is an associated Win32 console, write to it specially,
3741 // otherwise defer to the regular C Runtime, passing it UTF-8.
3742 if (console != NULL) {
3743 return _console_fwrite(ptr, size, nmemb, stream, console);
3744 } else {
3745 // If fwrite is a macro, undefine it, so we can call the real
3746 // C Runtime API.
3747#pragma push_macro("fwrite")
3748#undef fwrite
3749 return fwrite(ptr, size, nmemb, stream);
3750#pragma pop_macro("fwrite")
3751 }
3752}
3753
3754// Version of fopen() that takes a UTF-8 filename and can access a file with
3755// a Unicode filename.
3756FILE* adb_fopen(const char* f, const char* m) {
3757 return _wfopen(widen(f).c_str(), widen(m).c_str());
3758}
3759
3760// Shadow UTF-8 environment variable name/value pairs that are created from
3761// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003762// currently updated if putenv, setenv, unsetenv are called. Note that no
3763// thread synchronization is done, but we're called early enough in
3764// single-threaded startup that things work ok.
Spencer Low6815c072015-05-11 01:08:48 -07003765static std::unordered_map<std::string, char*> g_environ_utf8;
3766
3767// Make sure that shadow UTF-8 environment variables are setup.
3768static void _ensure_env_setup() {
3769 // If some name/value pairs exist, then we've already done the setup below.
3770 if (g_environ_utf8.size() != 0) {
3771 return;
3772 }
3773
3774 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3775 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3776 // to use the D() macro here because that tracing only works if the
3777 // ADB_TRACE environment variable is setup, but that env var can't be read
3778 // until this code completes.
3779 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3780 wchar_t* const equal = wcschr(*env, L'=');
3781 if (equal == nullptr) {
3782 // Malformed environment variable with no equal sign. Shouldn't
3783 // really happen, but we should be resilient to this.
3784 continue;
3785 }
3786
3787 const std::string name_utf8(narrow(std::wstring(*env, equal - *env)));
3788 char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3789
3790 // Overwrite any duplicate name, but there shouldn't be a dup in the
3791 // first place.
3792 g_environ_utf8[name_utf8] = value_utf8;
3793 }
3794}
3795
3796// Version of getenv() that takes a UTF-8 environment variable name and
3797// retrieves a UTF-8 value.
3798char* adb_getenv(const char* name) {
3799 _ensure_env_setup();
3800
Spencer Lowcc467f12015-08-02 18:13:54 -07003801 const auto it = g_environ_utf8.find(std::string(name));
Spencer Low6815c072015-05-11 01:08:48 -07003802 if (it == g_environ_utf8.end()) {
3803 return nullptr;
3804 }
3805
3806 return it->second;
3807}
3808
3809// Version of getcwd() that returns the current working directory in UTF-8.
3810char* adb_getcwd(char* buf, int size) {
3811 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3812 if (wbuf == nullptr) {
3813 return nullptr;
3814 }
3815
3816 const std::string buf_utf8(narrow(wbuf));
3817 free(wbuf);
3818 wbuf = nullptr;
3819
3820 // If size was specified, make sure all the chars will fit.
3821 if (size != 0) {
3822 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3823 errno = ERANGE;
3824 return nullptr;
3825 }
3826 }
3827
3828 // If buf was not specified, allocate storage.
3829 if (buf == nullptr) {
3830 if (size == 0) {
3831 size = buf_utf8.length() + 1;
3832 }
3833 buf = reinterpret_cast<char*>(malloc(size));
3834 if (buf == nullptr) {
3835 return nullptr;
3836 }
3837 }
3838
3839 // Destination buffer was allocated with enough space, or we've already
3840 // checked an existing buffer size for enough space.
3841 strcpy(buf, buf_utf8.c_str());
3842
3843 return buf;
3844}