blob: dece96f6dfe75fb70328389a43bab44bac2efde2 [file] [log] [blame]
Dan Albert33134262015-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
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
30#include <string>
Spencer Lowcf4ff642015-05-11 01:08:48 -070031#include <unordered_map>
Spencer Low5200c662015-07-30 23:07:55 -070032
Elliott Hughesd48dbd82015-07-24 11:35:40 -070033#include <cutils/sockets.h>
34
David Pursell5f787ed2016-01-27 08:52:53 -080035#include <android-base/errors.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080036#include <android-base/logging.h>
37#include <android-base/stringprintf.h>
38#include <android-base/strings.h>
39#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070040
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080041#include "adb.h"
42
43extern void fatal(const char *fmt, ...);
44
Elliott Hughesa2f2e562015-04-16 16:47:02 -070045/* forward declarations */
46
47typedef const struct FHClassRec_* FHClass;
48typedef struct FHRec_* FH;
49typedef struct EventHookRec_* EventHook;
50
51typedef struct FHClassRec_ {
52 void (*_fh_init)(FH);
53 int (*_fh_close)(FH);
54 int (*_fh_lseek)(FH, int, int);
55 int (*_fh_read)(FH, void*, int);
56 int (*_fh_write)(FH, const void*, int);
57 void (*_fh_hook)(FH, int, EventHook);
58} FHClassRec;
59
60static void _fh_file_init(FH);
61static int _fh_file_close(FH);
62static int _fh_file_lseek(FH, int, int);
63static int _fh_file_read(FH, void*, int);
64static int _fh_file_write(FH, const void*, int);
65static void _fh_file_hook(FH, int, EventHook);
66
67static const FHClassRec _fh_file_class = {
68 _fh_file_init,
69 _fh_file_close,
70 _fh_file_lseek,
71 _fh_file_read,
72 _fh_file_write,
73 _fh_file_hook
74};
75
76static void _fh_socket_init(FH);
77static int _fh_socket_close(FH);
78static int _fh_socket_lseek(FH, int, int);
79static int _fh_socket_read(FH, void*, int);
80static int _fh_socket_write(FH, const void*, int);
81static void _fh_socket_hook(FH, int, EventHook);
82
83static const FHClassRec _fh_socket_class = {
84 _fh_socket_init,
85 _fh_socket_close,
86 _fh_socket_lseek,
87 _fh_socket_read,
88 _fh_socket_write,
89 _fh_socket_hook
90};
91
Josh Gao56e9bb92016-01-15 15:17:37 -080092#define assert(cond) \
93 do { \
94 if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \
95 } while (0)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080096
Spencer Low2122c7a2015-08-26 18:46:09 -070097void handle_deleter::operator()(HANDLE h) {
98 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
99 // implying that NULL is a valid handle, but this is probably impossible.
100 // Other APIs like CreateEvent() are documented to return NULL on error,
101 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
102 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
103 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
104 // only need to check for INVALID_HANDLE_VALUE.
105 if (h != INVALID_HANDLE_VALUE) {
106 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700107 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800108 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700109 }
110 }
111}
112
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800113/**************************************************************************/
114/**************************************************************************/
115/***** *****/
116/***** replaces libs/cutils/load_file.c *****/
117/***** *****/
118/**************************************************************************/
119/**************************************************************************/
120
121void *load_file(const char *fn, unsigned *_sz)
122{
123 HANDLE file;
124 char *data;
125 DWORD file_size;
126
Spencer Lowd21dc822015-11-12 15:20:15 -0800127 std::wstring fn_wide;
128 if (!android::base::UTF8ToWide(fn, &fn_wide))
129 return NULL;
130
131 file = CreateFileW( fn_wide.c_str(),
Spencer Lowcf4ff642015-05-11 01:08:48 -0700132 GENERIC_READ,
133 FILE_SHARE_READ,
134 NULL,
135 OPEN_EXISTING,
136 0,
137 NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800138
139 if (file == INVALID_HANDLE_VALUE)
140 return NULL;
141
142 file_size = GetFileSize( file, NULL );
143 data = NULL;
144
145 if (file_size > 0) {
146 data = (char*) malloc( file_size + 1 );
147 if (data == NULL) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700148 D("load_file: could not allocate %ld bytes", file_size );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149 file_size = 0;
150 } else {
151 DWORD out_bytes;
152
153 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
154 out_bytes != file_size )
155 {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700156 D("load_file: could not read %ld bytes from '%s'", file_size, fn);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800157 free(data);
158 data = NULL;
159 file_size = 0;
160 }
161 }
162 }
163 CloseHandle( file );
164
165 *_sz = (unsigned) file_size;
166 return data;
167}
168
169/**************************************************************************/
170/**************************************************************************/
171/***** *****/
172/***** common file descriptor handling *****/
173/***** *****/
174/**************************************************************************/
175/**************************************************************************/
176
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800177/* used to emulate unix-domain socket pairs */
178typedef struct SocketPairRec_* SocketPair;
179
180typedef struct FHRec_
181{
182 FHClass clazz;
183 int used;
184 int eof;
185 union {
186 HANDLE handle;
187 SOCKET socket;
188 SocketPair pair;
189 } u;
190
191 HANDLE event;
192 int mask;
193
194 char name[32];
195
196} FHRec;
197
198#define fh_handle u.handle
199#define fh_socket u.socket
200#define fh_pair u.pair
201
202#define WIN32_FH_BASE 100
203
204#define WIN32_MAX_FHS 128
205
206static adb_mutex_t _win32_lock;
207static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700208static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800209
210static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700211_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800212{
213 FH f;
214
215 fd -= WIN32_FH_BASE;
216
Spencer Lowc3211552015-07-24 15:38:19 -0700217 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700218 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700219 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800220 errno = EBADF;
221 return NULL;
222 }
223
224 f = &_win32_fhs[fd];
225
226 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700227 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700228 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800229 errno = EBADF;
230 return NULL;
231 }
232
233 return f;
234}
235
236
237static int
238_fh_to_int( FH f )
239{
240 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
241 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
242
243 return -1;
244}
245
246static FH
247_fh_alloc( FHClass clazz )
248{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800249 FH f = NULL;
250
251 adb_mutex_lock( &_win32_lock );
252
Spencer Lowc3211552015-07-24 15:38:19 -0700253 // Search entire array, starting from _win32_fh_next.
254 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
255 // Keep incrementing _win32_fh_next to avoid giving out an index that
256 // was recently closed, to try to avoid use-after-free.
257 const int index = _win32_fh_next++;
258 // Handle wrap-around of _win32_fh_next.
259 if (_win32_fh_next == WIN32_MAX_FHS) {
260 _win32_fh_next = 0;
261 }
262 if (_win32_fhs[index].clazz == NULL) {
263 f = &_win32_fhs[index];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800264 goto Exit;
265 }
266 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700267 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowc3211552015-07-24 15:38:19 -0700268 errno = EMFILE; // Too many open files
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800269Exit:
270 if (f) {
Spencer Lowc3211552015-07-24 15:38:19 -0700271 f->clazz = clazz;
272 f->used = 1;
273 f->eof = 0;
274 f->name[0] = '\0';
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800275 clazz->_fh_init(f);
276 }
277 adb_mutex_unlock( &_win32_lock );
278 return f;
279}
280
281
282static int
283_fh_close( FH f )
284{
Spencer Lowc3211552015-07-24 15:38:19 -0700285 // Use lock so that closing only happens once and so that _fh_alloc can't
286 // allocate a FH that we're in the middle of closing.
287 adb_mutex_lock(&_win32_lock);
288 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800289 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700290 f->name[0] = '\0';
291 f->eof = 0;
292 f->used = 0;
293 f->clazz = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294 }
Spencer Lowc3211552015-07-24 15:38:19 -0700295 adb_mutex_unlock(&_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800296 return 0;
297}
298
Spencer Low5200c662015-07-30 23:07:55 -0700299// Deleter for unique_fh.
300class fh_deleter {
301 public:
302 void operator()(struct FHRec_* fh) {
303 // We're called from a destructor and destructors should not overwrite
304 // errno because callers may do:
305 // errno = EBLAH;
306 // return -1; // calls destructor, which should not overwrite errno
307 const int saved_errno = errno;
308 _fh_close(fh);
309 errno = saved_errno;
310 }
311};
312
313// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
314typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
315
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800316/**************************************************************************/
317/**************************************************************************/
318/***** *****/
319/***** file-based descriptor handling *****/
320/***** *****/
321/**************************************************************************/
322/**************************************************************************/
323
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700324static void _fh_file_init( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800325 f->fh_handle = INVALID_HANDLE_VALUE;
326}
327
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700328static int _fh_file_close( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800329 CloseHandle( f->fh_handle );
330 f->fh_handle = INVALID_HANDLE_VALUE;
331 return 0;
332}
333
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700334static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800335 DWORD read_bytes;
336
337 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700338 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800339 errno = EIO;
340 return -1;
341 } else if (read_bytes < (DWORD)len) {
342 f->eof = 1;
343 }
344 return (int)read_bytes;
345}
346
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700347static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800348 DWORD wrote_bytes;
349
350 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700351 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800352 errno = EIO;
353 return -1;
354 } else if (wrote_bytes < (DWORD)len) {
355 f->eof = 1;
356 }
357 return (int)wrote_bytes;
358}
359
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700360static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800361 DWORD method;
362 DWORD result;
363
364 switch (origin)
365 {
366 case SEEK_SET: method = FILE_BEGIN; break;
367 case SEEK_CUR: method = FILE_CURRENT; break;
368 case SEEK_END: method = FILE_END; break;
369 default:
370 errno = EINVAL;
371 return -1;
372 }
373
374 result = SetFilePointer( f->fh_handle, pos, NULL, method );
375 if (result == INVALID_SET_FILE_POINTER) {
376 errno = EIO;
377 return -1;
378 } else {
379 f->eof = 0;
380 }
381 return (int)result;
382}
383
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800384
385/**************************************************************************/
386/**************************************************************************/
387/***** *****/
388/***** file-based descriptor handling *****/
389/***** *****/
390/**************************************************************************/
391/**************************************************************************/
392
393int adb_open(const char* path, int options)
394{
395 FH f;
396
397 DWORD desiredAccess = 0;
398 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
399
400 switch (options) {
401 case O_RDONLY:
402 desiredAccess = GENERIC_READ;
403 break;
404 case O_WRONLY:
405 desiredAccess = GENERIC_WRITE;
406 break;
407 case O_RDWR:
408 desiredAccess = GENERIC_READ | GENERIC_WRITE;
409 break;
410 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700411 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800412 errno = EINVAL;
413 return -1;
414 }
415
416 f = _fh_alloc( &_fh_file_class );
417 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800418 return -1;
419 }
420
Spencer Lowd21dc822015-11-12 15:20:15 -0800421 std::wstring path_wide;
422 if (!android::base::UTF8ToWide(path, &path_wide)) {
423 return -1;
424 }
425 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700426 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800427
428 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700429 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800430 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700431 D( "adb_open: could not open '%s': ", path );
432 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800433 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700434 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800435 errno = ENOENT;
436 return -1;
437
438 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700439 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800440 errno = ENOTDIR;
441 return -1;
442
443 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800444 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800445 errno = ENOENT;
446 return -1;
447 }
448 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800449
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800450 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700451 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452 return _fh_to_int(f);
453}
454
455/* ignore mode on Win32 */
456int adb_creat(const char* path, int mode)
457{
458 FH f;
459
460 f = _fh_alloc( &_fh_file_class );
461 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462 return -1;
463 }
464
Spencer Lowd21dc822015-11-12 15:20:15 -0800465 std::wstring path_wide;
466 if (!android::base::UTF8ToWide(path, &path_wide)) {
467 return -1;
468 }
469 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700470 FILE_SHARE_READ | FILE_SHARE_WRITE,
471 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
472 NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473
474 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700475 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800476 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700477 D( "adb_creat: could not open '%s': ", path );
478 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700480 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800481 errno = ENOENT;
482 return -1;
483
484 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700485 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800486 errno = ENOTDIR;
487 return -1;
488
489 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800490 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491 errno = ENOENT;
492 return -1;
493 }
494 }
495 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700496 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497 return _fh_to_int(f);
498}
499
500
501int adb_read(int fd, void* buf, int len)
502{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700503 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800504
505 if (f == NULL) {
506 return -1;
507 }
508
509 return f->clazz->_fh_read( f, buf, len );
510}
511
512
513int adb_write(int fd, const void* buf, int len)
514{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700515 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800516
517 if (f == NULL) {
518 return -1;
519 }
520
521 return f->clazz->_fh_write(f, buf, len);
522}
523
524
525int adb_lseek(int fd, int pos, int where)
526{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700527 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800528
529 if (!f) {
530 return -1;
531 }
532
533 return f->clazz->_fh_lseek(f, pos, where);
534}
535
536
537int adb_close(int fd)
538{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700539 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800540
541 if (!f) {
542 return -1;
543 }
544
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700545 D( "adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800546 _fh_close(f);
547 return 0;
548}
549
Spencer Low0a796002015-10-18 16:45:09 -0700550// Overrides strerror() to handle error codes not supported by the Windows C
551// Runtime (MSVCRT.DLL).
552char* adb_strerror(int err) {
553 // sysdeps.h defines strerror to adb_strerror, but in this function, we
554 // want to call the real C Runtime strerror().
555#pragma push_macro("strerror")
556#undef strerror
557 const int saved_err = errno; // Save because we overwrite it later.
558
559 // Lookup the string for an unknown error.
560 char* errmsg = strerror(-1);
Elliott Hughes6d929972015-10-27 13:40:35 -0700561 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low0a796002015-10-18 16:45:09 -0700562
563 // Lookup the string for this error to see if the C Runtime has it.
564 errmsg = strerror(err);
Elliott Hughes6d929972015-10-27 13:40:35 -0700565 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low0a796002015-10-18 16:45:09 -0700566 // The CRT returned an error message and it is different than the error
567 // message for an unknown error, so it is probably valid, so use it.
568 } else {
569 // Check if we have a string for this error code.
570 const char* custom_msg = nullptr;
571 switch (err) {
572#pragma push_macro("ERR")
573#undef ERR
574#define ERR(errnum, desc) case errnum: custom_msg = desc; break
575 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
576 // Note that these cannot be longer than 94 characters because we
577 // pass this to _strerror() which has that requirement.
578 ERR(ECONNRESET, "Connection reset by peer");
579 ERR(EHOSTUNREACH, "No route to host");
580 ERR(ENETDOWN, "Network is down");
581 ERR(ENETRESET, "Network dropped connection because of reset");
582 ERR(ENOBUFS, "No buffer space available");
583 ERR(ENOPROTOOPT, "Protocol not available");
584 ERR(ENOTCONN, "Transport endpoint is not connected");
585 ERR(ENOTSOCK, "Socket operation on non-socket");
586 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
587#pragma pop_macro("ERR")
588 }
589
590 if (custom_msg != nullptr) {
591 // Use _strerror() to write our string into the writable per-thread
592 // buffer used by strerror()/_strerror(). _strerror() appends the
593 // msg for the current value of errno, so set errno to a consistent
594 // value for every call so that our code-path is always the same.
595 errno = 0;
596 errmsg = _strerror(custom_msg);
597 const size_t custom_msg_len = strlen(custom_msg);
598 // Just in case _strerror() returned a read-only string, check if
599 // the returned string starts with our custom message because that
600 // implies that the string is not read-only.
601 if ((errmsg != nullptr) &&
602 !strncmp(custom_msg, errmsg, custom_msg_len)) {
603 // _strerror() puts other text after our custom message, so
604 // remove that by terminating after our message.
605 errmsg[custom_msg_len] = '\0';
606 } else {
607 // For some reason nullptr was returned or a pointer to a
608 // read-only string was returned, so fallback to whatever
609 // strerror() can muster (probably "Unknown error" or some
610 // generic CRT error string).
611 errmsg = strerror(err);
612 }
613 } else {
614 // We don't have a custom message, so use whatever strerror(err)
615 // returned earlier.
616 }
617 }
618
619 errno = saved_err; // restore
620
621 return errmsg;
622#pragma pop_macro("strerror")
623}
624
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800625/**************************************************************************/
626/**************************************************************************/
627/***** *****/
628/***** socket-based file descriptors *****/
629/***** *****/
630/**************************************************************************/
631/**************************************************************************/
632
Spencer Lowf055c192015-01-25 14:40:16 -0800633#undef setsockopt
634
Spencer Low5200c662015-07-30 23:07:55 -0700635static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700636 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
637 // lot of POSIX and socket error codes, some of the resulting error codes
638 // are mapped to strings by adb_strerror() above.
Spencer Low5200c662015-07-30 23:07:55 -0700639 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700641 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
642 // case WSAEINTR: errno = EINTR; break;
643 case WSAEFAULT: errno = EFAULT; break;
644 case WSAEINVAL: errno = EINVAL; break;
645 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700646 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
647 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
648 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800649 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700650 case WSAENOTSOCK: errno = ENOTSOCK; break;
651 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
652 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
653 case WSAENETDOWN: errno = ENETDOWN; break;
654 case WSAENETRESET: errno = ENETRESET; break;
655 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
656 // to use EPIPE for these situations and there are some callers that look
657 // for EPIPE.
658 case WSAECONNABORTED: errno = EPIPE; break;
659 case WSAECONNRESET: errno = ECONNRESET; break;
660 case WSAENOBUFS: errno = ENOBUFS; break;
661 case WSAENOTCONN: errno = ENOTCONN; break;
662 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
663 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
664 // considerations: Reportedly send() can return zero on timeout, and POSIX
665 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
666 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
667 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800668 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800669 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700670 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700671 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800672 }
673}
674
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700675static void _fh_socket_init( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800676 f->fh_socket = INVALID_SOCKET;
677 f->event = WSACreateEvent();
Spencer Low5200c662015-07-30 23:07:55 -0700678 if (f->event == WSA_INVALID_EVENT) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700679 D("WSACreateEvent failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800680 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700681
682 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
683 // on failure, instead of NULL which is what Windows really returns on
684 // error. It might be better to change all the other code to look for
685 // NULL, but that is a much riskier change.
686 f->event = INVALID_HANDLE_VALUE;
687 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800688 f->mask = 0;
689}
690
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700691static int _fh_socket_close( FH f ) {
Spencer Low5200c662015-07-30 23:07:55 -0700692 if (f->fh_socket != INVALID_SOCKET) {
693 /* gently tell any peer that we're closing the socket */
694 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
695 // If the socket is not connected, this returns an error. We want to
696 // minimize logging spam, so don't log these errors for now.
697#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700698 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800699 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700700#endif
701 }
702 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700703 D("closesocket failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800704 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700705 }
706 f->fh_socket = INVALID_SOCKET;
707 }
708 if (f->event != NULL) {
709 if (!CloseHandle(f->event)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700710 D("CloseHandle failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800711 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700712 }
713 f->event = NULL;
714 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715 f->mask = 0;
716 return 0;
717}
718
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700719static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800720 errno = EPIPE;
721 return -1;
722}
723
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700724static int _fh_socket_read(FH f, void* buf, int len) {
725 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700727 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700728 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
729 // that to reduce spam and confusion.
730 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700731 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800732 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700733 }
Spencer Low5200c662015-07-30 23:07:55 -0700734 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 result = -1;
736 }
737 return result;
738}
739
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700740static int _fh_socket_write(FH f, const void* buf, int len) {
741 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800742 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700743 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700744 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
745 // that to reduce spam and confusion.
746 if (err != WSAEWOULDBLOCK) {
747 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800748 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700749 }
Spencer Low5200c662015-07-30 23:07:55 -0700750 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800751 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700752 } else {
753 // According to https://code.google.com/p/chromium/issues/detail?id=27870
754 // Winsock Layered Service Providers may cause this.
755 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
756 << f->name << ", but " << result
757 << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800758 }
759 return result;
760}
761
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800762/**************************************************************************/
763/**************************************************************************/
764/***** *****/
765/***** replacement for libs/cutils/socket_xxxx.c *****/
766/***** *****/
767/**************************************************************************/
768/**************************************************************************/
769
770#include <winsock2.h>
771
772static int _winsock_init;
773
774static void
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800775_init_winsock( void )
776{
Spencer Low5200c662015-07-30 23:07:55 -0700777 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Low87e97ee2015-08-12 18:19:16 -0700778 // to WSAStartup() which offers no real benefit.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800779 if (!_winsock_init) {
780 WSADATA wsaData;
781 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
782 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800783 fatal("adb: could not initialize Winsock: %s",
784 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800785 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786 _winsock_init = 1;
Spencer Low87e97ee2015-08-12 18:19:16 -0700787
788 // Note that we do not call atexit() to register WSACleanup to be called
789 // at normal process termination because:
790 // 1) When exit() is called, there are still threads actively using
791 // Winsock because we don't cleanly shutdown all threads, so it
792 // doesn't make sense to call WSACleanup() and may cause problems
793 // with those threads.
794 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
795 // calls WSACleanup() which tries to unload a DLL, which tries to
796 // grab the LoaderLock. This conflicts with the device_poll_thread
797 // which holds the LoaderLock because AdbWinApi.dll calls
798 // setupapi.dll which tries to load wintrust.dll which tries to load
799 // crypt32.dll which calls atexit() which tries to acquire the C
800 // Runtime lock that the other thread holds.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800801 }
802}
803
Spencer Low677fb432015-09-29 15:05:29 -0700804// Map a socket type to an explicit socket protocol instead of using the socket
805// protocol of 0. Explicit socket protocols are used by most apps and we should
806// do the same to reduce the chance of exercising uncommon code-paths that might
807// have problems or that might load different Winsock service providers that
808// have problems.
809static int GetSocketProtocolFromSocketType(int type) {
810 switch (type) {
811 case SOCK_STREAM:
812 return IPPROTO_TCP;
813 case SOCK_DGRAM:
814 return IPPROTO_UDP;
815 default:
816 LOG(FATAL) << "Unknown socket type: " << type;
817 return 0;
818 }
819}
820
Spencer Low5200c662015-07-30 23:07:55 -0700821int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 struct sockaddr_in addr;
823 SOCKET s;
824
Spencer Low5200c662015-07-30 23:07:55 -0700825 unique_fh f(_fh_alloc(&_fh_socket_class));
826 if (!f) {
827 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700829 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800830
831 if (!_winsock_init)
832 _init_winsock();
833
834 memset(&addr, 0, sizeof(addr));
835 addr.sin_family = AF_INET;
836 addr.sin_port = htons(port);
837 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
838
Spencer Low677fb432015-09-29 15:05:29 -0700839 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800840 if(s == INVALID_SOCKET) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700841 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800842 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700843 D("%s", error->c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700844 return -1;
845 }
846 f->fh_socket = s;
847
848 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700849 // Save err just in case inet_ntoa() or ntohs() changes the last error.
850 const DWORD err = WSAGetLastError();
851 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
852 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
David Pursell5f787ed2016-01-27 08:52:53 -0800853 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700854 D("could not connect to %s:%d: %s",
Spencer Low5200c662015-07-30 23:07:55 -0700855 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800856 return -1;
857 }
858
Spencer Low5200c662015-07-30 23:07:55 -0700859 const int fd = _fh_to_int(f.get());
860 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
861 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700862 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low5200c662015-07-30 23:07:55 -0700863 fd );
864 f.release();
865 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866}
867
868#define LISTEN_BACKLOG 4
869
Spencer Low5200c662015-07-30 23:07:55 -0700870// interface_address is INADDR_LOOPBACK or INADDR_ANY.
871static int _network_server(int port, int type, u_long interface_address,
872 std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800873 struct sockaddr_in addr;
874 SOCKET s;
875 int n;
876
Spencer Low5200c662015-07-30 23:07:55 -0700877 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800878 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700879 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800880 return -1;
881 }
882
883 if (!_winsock_init)
884 _init_winsock();
885
886 memset(&addr, 0, sizeof(addr));
887 addr.sin_family = AF_INET;
888 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700889 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800890
Spencer Low5200c662015-07-30 23:07:55 -0700891 // TODO: Consider using dual-stack socket that can simultaneously listen on
892 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700893 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700894 if (s == INVALID_SOCKET) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700895 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800896 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700897 D("%s", error->c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700898 return -1;
899 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800900
901 f->fh_socket = s;
902
Spencer Lowbf7c6052015-08-11 16:45:32 -0700903 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
904 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800905 n = 1;
Spencer Low5200c662015-07-30 23:07:55 -0700906 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
907 sizeof(n)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700908 *error = android::base::StringPrintf(
909 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800910 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700911 D("%s", error->c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700912 return -1;
913 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800914
Spencer Lowbf7c6052015-08-11 16:45:32 -0700915 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
916 // Save err just in case inet_ntoa() or ntohs() changes the last error.
917 const DWORD err = WSAGetLastError();
918 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
919 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
David Pursell5f787ed2016-01-27 08:52:53 -0800920 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700921 D("could not bind to %s:%d: %s",
Spencer Low5200c662015-07-30 23:07:55 -0700922 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800923 return -1;
924 }
925 if (type == SOCK_STREAM) {
Spencer Low5200c662015-07-30 23:07:55 -0700926 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700927 *error = android::base::StringPrintf("cannot listen on socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800928 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700929 D("could not listen on %s:%d: %s",
Spencer Low5200c662015-07-30 23:07:55 -0700930 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800931 return -1;
932 }
933 }
Spencer Low5200c662015-07-30 23:07:55 -0700934 const int fd = _fh_to_int(f.get());
935 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
936 interface_address == INADDR_LOOPBACK ? "lo" : "any",
937 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700938 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low5200c662015-07-30 23:07:55 -0700939 fd );
940 f.release();
941 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800942}
943
Spencer Low5200c662015-07-30 23:07:55 -0700944int network_loopback_server(int port, int type, std::string* error) {
945 return _network_server(port, type, INADDR_LOOPBACK, error);
946}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800947
Spencer Low5200c662015-07-30 23:07:55 -0700948int network_inaddr_any_server(int port, int type, std::string* error) {
949 return _network_server(port, type, INADDR_ANY, error);
950}
951
952int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
953 unique_fh f(_fh_alloc(&_fh_socket_class));
954 if (!f) {
955 *error = strerror(errno);
956 return -1;
957 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800958
Elliott Hughes381cfa92015-07-23 17:12:58 -0700959 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800960
Spencer Low5200c662015-07-30 23:07:55 -0700961 struct addrinfo hints;
962 memset(&hints, 0, sizeof(hints));
963 hints.ai_family = AF_UNSPEC;
964 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700965 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700966
967 char port_str[16];
968 snprintf(port_str, sizeof(port_str), "%d", port);
969
970 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700971
972#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
973 // TODO: When the Android SDK tools increases the Windows system
Spencer Lowd21dc822015-11-12 15:20:15 -0800974 // requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700975#else
976 // Otherwise, keep using getaddrinfo(), or do runtime API detection
977 // with GetProcAddress("GetAddrInfoW").
978#endif
Spencer Low5200c662015-07-30 23:07:55 -0700979 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700980 *error = android::base::StringPrintf(
981 "cannot resolve host '%s' and port %s: %s", host.c_str(),
David Pursell5f787ed2016-01-27 08:52:53 -0800982 port_str, android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700983 D("%s", error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800984 return -1;
985 }
Spencer Low5200c662015-07-30 23:07:55 -0700986 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
987 addrinfo(addrinfo_ptr, freeaddrinfo);
988 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800989
Spencer Low5200c662015-07-30 23:07:55 -0700990 // TODO: Try all the addresses if there's more than one? This just uses
991 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
992 // which tries all addresses, takes a timeout and more.
993 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
994 addrinfo->ai_protocol);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 if(s == INVALID_SOCKET) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700996 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800997 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700998 D("%s", error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800999 return -1;
1000 }
1001 f->fh_socket = s;
1002
Spencer Low5200c662015-07-30 23:07:55 -07001003 // TODO: Implement timeouts for Windows. Seems like the default in theory
1004 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
1005 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -07001006 // TODO: Use WSAAddressToString or inet_ntop on address.
1007 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
1008 host.c_str(), port_str,
David Pursell5f787ed2016-01-27 08:52:53 -08001009 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001010 D("could not connect to %s:%s:%s: %s",
Spencer Low5200c662015-07-30 23:07:55 -07001011 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
1012 error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001013 return -1;
1014 }
1015
Spencer Low5200c662015-07-30 23:07:55 -07001016 const int fd = _fh_to_int(f.get());
1017 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
1018 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001019 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low5200c662015-07-30 23:07:55 -07001020 type != SOCK_STREAM ? "udp" : "tcp", fd );
1021 f.release();
1022 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001023}
1024
1025#undef accept
1026int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
1027{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001028 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001029
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001030 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001031 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -07001032 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001033 return -1;
1034 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001035
Spencer Low5200c662015-07-30 23:07:55 -07001036 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001037 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001038 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1039 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001040 return -1;
1041 }
1042
1043 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1044 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001045 const DWORD err = WSAGetLastError();
Spencer Low5200c662015-07-30 23:07:55 -07001046 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursell5f787ed2016-01-27 08:52:53 -08001047 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low5200c662015-07-30 23:07:55 -07001048 _socket_set_errno( err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001049 return -1;
1050 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001051
Spencer Low5200c662015-07-30 23:07:55 -07001052 const int fd = _fh_to_int(fh.get());
1053 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001054 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low5200c662015-07-30 23:07:55 -07001055 fh.release();
1056 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001057}
1058
1059
Spencer Lowf055c192015-01-25 14:40:16 -08001060int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001061{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001062 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001063
Spencer Lowf055c192015-01-25 14:40:16 -08001064 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001065 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001066 errno = EBADF;
1067 return -1;
1068 }
Spencer Low677fb432015-09-29 15:05:29 -07001069
1070 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1071 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1072 // auto-tuning.
1073
Spencer Low5200c662015-07-30 23:07:55 -07001074 int result = setsockopt( fh->fh_socket, level, optname,
1075 reinterpret_cast<const char*>(optval), optlen );
1076 if ( result == SOCKET_ERROR ) {
1077 const DWORD err = WSAGetLastError();
David Pursell5f787ed2016-01-27 08:52:53 -08001078 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1079 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001080 _socket_set_errno( err );
1081 result = -1;
1082 }
1083 return result;
1084}
1085
1086
1087int adb_shutdown(int fd)
1088{
1089 FH f = _fh_from_int(fd, __func__);
1090
1091 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001092 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001093 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001094 return -1;
1095 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001096
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001097 D( "adb_shutdown: %s", f->name);
Spencer Low5200c662015-07-30 23:07:55 -07001098 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1099 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001100 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001101 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001102 _socket_set_errno(err);
1103 return -1;
1104 }
1105 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001106}
1107
1108/**************************************************************************/
1109/**************************************************************************/
1110/***** *****/
1111/***** emulated socketpairs *****/
1112/***** *****/
1113/**************************************************************************/
1114/**************************************************************************/
1115
1116/* we implement socketpairs directly in use space for the following reasons:
1117 * - it avoids copying data from/to the Nt kernel
1118 * - it allows us to implement fdevent hooks easily and cheaply, something
1119 * that is not possible with standard Win32 pipes !!
1120 *
1121 * basically, we use two circular buffers, each one corresponding to a given
1122 * direction.
1123 *
1124 * each buffer is implemented as two regions:
1125 *
1126 * region A which is (a_start,a_end)
1127 * region B which is (0, b_end) with b_end <= a_start
1128 *
1129 * an empty buffer has: a_start = a_end = b_end = 0
1130 *
1131 * a_start is the pointer where we start reading data
1132 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
1133 * then you start writing at b_end
1134 *
1135 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
1136 *
1137 * there is room when b_end < a_start || a_end < BUFER_SIZE
1138 *
1139 * when reading, a_start is incremented, it a_start meets a_end, then
1140 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1141 */
1142
1143#define BIP_BUFFER_SIZE 4096
1144
1145#if 0
1146#include <stdio.h>
1147# define BIPD(x) D x
1148# define BIPDUMP bip_dump_hex
1149
1150static void bip_dump_hex( const unsigned char* ptr, size_t len )
1151{
1152 int nn, len2 = len;
1153
1154 if (len2 > 8) len2 = 8;
1155
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001156 for (nn = 0; nn < len2; nn++)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001157 printf("%02x", ptr[nn]);
1158 printf(" ");
1159
1160 for (nn = 0; nn < len2; nn++) {
1161 int c = ptr[nn];
1162 if (c < 32 || c > 127)
1163 c = '.';
1164 printf("%c", c);
1165 }
1166 printf("\n");
1167 fflush(stdout);
1168}
1169
1170#else
1171# define BIPD(x) do {} while (0)
1172# define BIPDUMP(p,l) BIPD(p)
1173#endif
1174
1175typedef struct BipBufferRec_
1176{
1177 int a_start;
1178 int a_end;
1179 int b_end;
1180 int fdin;
1181 int fdout;
1182 int closed;
1183 int can_write; /* boolean */
1184 HANDLE evt_write; /* event signaled when one can write to a buffer */
1185 int can_read; /* boolean */
1186 HANDLE evt_read; /* event signaled when one can read from a buffer */
1187 CRITICAL_SECTION lock;
1188 unsigned char buff[ BIP_BUFFER_SIZE ];
1189
1190} BipBufferRec, *BipBuffer;
1191
1192static void
1193bip_buffer_init( BipBuffer buffer )
1194{
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001195 D( "bit_buffer_init %p", buffer );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001196 buffer->a_start = 0;
1197 buffer->a_end = 0;
1198 buffer->b_end = 0;
1199 buffer->can_write = 1;
1200 buffer->can_read = 0;
1201 buffer->fdin = 0;
1202 buffer->fdout = 0;
1203 buffer->closed = 0;
1204 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1205 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1206 InitializeCriticalSection( &buffer->lock );
1207}
1208
1209static void
1210bip_buffer_close( BipBuffer bip )
1211{
1212 bip->closed = 1;
1213
1214 if (!bip->can_read) {
1215 SetEvent( bip->evt_read );
1216 }
1217 if (!bip->can_write) {
1218 SetEvent( bip->evt_write );
1219 }
1220}
1221
1222static void
1223bip_buffer_done( BipBuffer bip )
1224{
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001225 BIPD(( "bip_buffer_done: %d->%d", bip->fdin, bip->fdout ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001226 CloseHandle( bip->evt_read );
1227 CloseHandle( bip->evt_write );
1228 DeleteCriticalSection( &bip->lock );
1229}
1230
1231static int
1232bip_buffer_write( BipBuffer bip, const void* src, int len )
1233{
1234 int avail, count = 0;
1235
1236 if (len <= 0)
1237 return 0;
1238
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001239 BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001240 BIPDUMP( src, len );
1241
David Pursellb404dec2015-09-11 16:06:59 -07001242 if (bip->closed) {
1243 errno = EPIPE;
1244 return -1;
1245 }
1246
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001247 EnterCriticalSection( &bip->lock );
1248
1249 while (!bip->can_write) {
1250 int ret;
1251 LeaveCriticalSection( &bip->lock );
1252
1253 if (bip->closed) {
1254 errno = EPIPE;
1255 return -1;
1256 }
1257 /* spinlocking here is probably unfair, but let's live with it */
1258 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1259 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001260 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError() );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001261 return 0;
1262 }
1263 if (bip->closed) {
1264 errno = EPIPE;
1265 return -1;
1266 }
1267 EnterCriticalSection( &bip->lock );
1268 }
1269
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001270 BIPD(( "bip_buffer_write: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001271
1272 avail = BIP_BUFFER_SIZE - bip->a_end;
1273 if (avail > 0)
1274 {
1275 /* we can append to region A */
1276 if (avail > len)
1277 avail = len;
1278
1279 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn60299df2014-04-30 09:10:31 -07001280 src = (const char *)src + avail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001281 count += avail;
1282 len -= avail;
1283
1284 bip->a_end += avail;
1285 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1286 bip->can_write = 0;
1287 ResetEvent( bip->evt_write );
1288 goto Exit;
1289 }
1290 }
1291
1292 if (len == 0)
1293 goto Exit;
1294
1295 avail = bip->a_start - bip->b_end;
1296 assert( avail > 0 ); /* since can_write is TRUE */
1297
1298 if (avail > len)
1299 avail = len;
1300
1301 memcpy( bip->buff + bip->b_end, src, avail );
1302 count += avail;
1303 bip->b_end += avail;
1304
1305 if (bip->b_end == bip->a_start) {
1306 bip->can_write = 0;
1307 ResetEvent( bip->evt_write );
1308 }
1309
1310Exit:
1311 assert( count > 0 );
1312
1313 if ( !bip->can_read ) {
1314 bip->can_read = 1;
1315 SetEvent( bip->evt_read );
1316 }
1317
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001318 BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001319 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1320 LeaveCriticalSection( &bip->lock );
1321
1322 return count;
1323 }
1324
1325static int
1326bip_buffer_read( BipBuffer bip, void* dst, int len )
1327{
1328 int avail, count = 0;
1329
1330 if (len <= 0)
1331 return 0;
1332
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001333 BIPD(( "bip_buffer_read: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001334
1335 EnterCriticalSection( &bip->lock );
1336 while ( !bip->can_read )
1337 {
1338#if 0
1339 LeaveCriticalSection( &bip->lock );
1340 errno = EAGAIN;
1341 return -1;
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001342#else
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001343 int ret;
1344 LeaveCriticalSection( &bip->lock );
1345
1346 if (bip->closed) {
1347 errno = EPIPE;
1348 return -1;
1349 }
1350
1351 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1352 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001353 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001354 return 0;
1355 }
1356 if (bip->closed) {
1357 errno = EPIPE;
1358 return -1;
1359 }
1360 EnterCriticalSection( &bip->lock );
1361#endif
1362 }
1363
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001364 BIPD(( "bip_buffer_read: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001365
1366 avail = bip->a_end - bip->a_start;
1367 assert( avail > 0 ); /* since can_read is TRUE */
1368
1369 if (avail > len)
1370 avail = len;
1371
1372 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn60299df2014-04-30 09:10:31 -07001373 dst = (char *)dst + avail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001374 count += avail;
1375 len -= avail;
1376
1377 bip->a_start += avail;
1378 if (bip->a_start < bip->a_end)
1379 goto Exit;
1380
1381 bip->a_start = 0;
1382 bip->a_end = bip->b_end;
1383 bip->b_end = 0;
1384
1385 avail = bip->a_end;
1386 if (avail > 0) {
1387 if (avail > len)
1388 avail = len;
1389 memcpy( dst, bip->buff, avail );
1390 count += avail;
1391 bip->a_start += avail;
1392
1393 if ( bip->a_start < bip->a_end )
1394 goto Exit;
1395
1396 bip->a_start = bip->a_end = 0;
1397 }
1398
1399 bip->can_read = 0;
1400 ResetEvent( bip->evt_read );
1401
1402Exit:
1403 assert( count > 0 );
1404
1405 if (!bip->can_write ) {
1406 bip->can_write = 1;
1407 SetEvent( bip->evt_write );
1408 }
1409
1410 BIPDUMP( (const unsigned char*)dst - count, count );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001411 BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001412 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1413 LeaveCriticalSection( &bip->lock );
1414
1415 return count;
1416}
1417
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001418typedef struct SocketPairRec_
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001419{
1420 BipBufferRec a2b_bip;
1421 BipBufferRec b2a_bip;
1422 FH a_fd;
1423 int used;
1424
1425} SocketPairRec;
1426
1427void _fh_socketpair_init( FH f )
1428{
1429 f->fh_pair = NULL;
1430}
1431
1432static int
1433_fh_socketpair_close( FH f )
1434{
1435 if ( f->fh_pair ) {
1436 SocketPair pair = f->fh_pair;
1437
1438 if ( f == pair->a_fd ) {
1439 pair->a_fd = NULL;
1440 }
1441
1442 bip_buffer_close( &pair->b2a_bip );
1443 bip_buffer_close( &pair->a2b_bip );
1444
1445 if ( --pair->used == 0 ) {
1446 bip_buffer_done( &pair->b2a_bip );
1447 bip_buffer_done( &pair->a2b_bip );
1448 free( pair );
1449 }
1450 f->fh_pair = NULL;
1451 }
1452 return 0;
1453}
1454
1455static int
1456_fh_socketpair_lseek( FH f, int pos, int origin )
1457{
1458 errno = ESPIPE;
1459 return -1;
1460}
1461
1462static int
1463_fh_socketpair_read( FH f, void* buf, int len )
1464{
1465 SocketPair pair = f->fh_pair;
1466 BipBuffer bip;
1467
1468 if (!pair)
1469 return -1;
1470
1471 if ( f == pair->a_fd )
1472 bip = &pair->b2a_bip;
1473 else
1474 bip = &pair->a2b_bip;
1475
1476 return bip_buffer_read( bip, buf, len );
1477}
1478
1479static int
1480_fh_socketpair_write( FH f, const void* buf, int len )
1481{
1482 SocketPair pair = f->fh_pair;
1483 BipBuffer bip;
1484
1485 if (!pair)
1486 return -1;
1487
1488 if ( f == pair->a_fd )
1489 bip = &pair->a2b_bip;
1490 else
1491 bip = &pair->b2a_bip;
1492
1493 return bip_buffer_write( bip, buf, len );
1494}
1495
1496
1497static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1498
1499static const FHClassRec _fh_socketpair_class =
1500{
1501 _fh_socketpair_init,
1502 _fh_socketpair_close,
1503 _fh_socketpair_lseek,
1504 _fh_socketpair_read,
1505 _fh_socketpair_write,
1506 _fh_socketpair_hook
1507};
1508
1509
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001510int adb_socketpair(int sv[2]) {
1511 SocketPair pair;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001512
Spencer Low5200c662015-07-30 23:07:55 -07001513 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1514 if (!fa) {
1515 return -1;
1516 }
1517 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1518 if (!fb) {
1519 return -1;
1520 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001521
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001522 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001523 if (pair == NULL) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001524 D("adb_socketpair: not enough memory to allocate pipes" );
Spencer Low5200c662015-07-30 23:07:55 -07001525 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001526 }
1527
1528 bip_buffer_init( &pair->a2b_bip );
1529 bip_buffer_init( &pair->b2a_bip );
1530
1531 fa->fh_pair = pair;
1532 fb->fh_pair = pair;
1533 pair->used = 2;
Spencer Low5200c662015-07-30 23:07:55 -07001534 pair->a_fd = fa.get();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001535
Spencer Low5200c662015-07-30 23:07:55 -07001536 sv[0] = _fh_to_int(fa.get());
1537 sv[1] = _fh_to_int(fb.get());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001538
1539 pair->a2b_bip.fdin = sv[0];
1540 pair->a2b_bip.fdout = sv[1];
1541 pair->b2a_bip.fdin = sv[1];
1542 pair->b2a_bip.fdout = sv[0];
1543
1544 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1545 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001546 D( "adb_socketpair: returns (%d, %d)", sv[0], sv[1] );
Spencer Low5200c662015-07-30 23:07:55 -07001547 fa.release();
1548 fb.release();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001549 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001550}
1551
1552/**************************************************************************/
1553/**************************************************************************/
1554/***** *****/
1555/***** fdevents emulation *****/
1556/***** *****/
1557/***** this is a very simple implementation, we rely on the fact *****/
1558/***** that ADB doesn't use FDE_ERROR. *****/
1559/***** *****/
1560/**************************************************************************/
1561/**************************************************************************/
1562
Josh Gao56e9bb92016-01-15 15:17:37 -08001563#define FATAL(fmt, ...) fatal("%s: " fmt, __FUNCTION__, ##__VA_ARGS__)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001564
1565#if DEBUG
1566static void dump_fde(fdevent *fde, const char *info)
1567{
1568 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1569 fde->state & FDE_READ ? 'R' : ' ',
1570 fde->state & FDE_WRITE ? 'W' : ' ',
1571 fde->state & FDE_ERROR ? 'E' : ' ',
1572 info);
1573}
1574#else
1575#define dump_fde(fde, info) do { } while(0)
1576#endif
1577
1578#define FDE_EVENTMASK 0x00ff
1579#define FDE_STATEMASK 0xff00
1580
1581#define FDE_ACTIVE 0x0100
1582#define FDE_PENDING 0x0200
1583#define FDE_CREATED 0x0400
1584
1585static void fdevent_plist_enqueue(fdevent *node);
1586static void fdevent_plist_remove(fdevent *node);
1587static fdevent *fdevent_plist_dequeue(void);
1588
1589static fdevent list_pending = {
1590 .next = &list_pending,
1591 .prev = &list_pending,
1592};
1593
1594static fdevent **fd_table = 0;
1595static int fd_table_max = 0;
1596
1597typedef struct EventLooperRec_* EventLooper;
1598
1599typedef struct EventHookRec_
1600{
1601 EventHook next;
1602 FH fh;
1603 HANDLE h;
1604 int wanted; /* wanted event flags */
1605 int ready; /* ready event flags */
1606 void* aux;
1607 void (*prepare)( EventHook hook );
1608 int (*start) ( EventHook hook );
1609 void (*stop) ( EventHook hook );
1610 int (*check) ( EventHook hook );
1611 int (*peek) ( EventHook hook );
1612} EventHookRec;
1613
1614static EventHook _free_hooks;
1615
1616static EventHook
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001617event_hook_alloc(FH fh) {
1618 EventHook hook = _free_hooks;
1619 if (hook != NULL) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001620 _free_hooks = hook->next;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001621 } else {
1622 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001623 if (hook == NULL)
1624 fatal( "could not allocate event hook\n" );
1625 }
1626 hook->next = NULL;
1627 hook->fh = fh;
1628 hook->wanted = 0;
1629 hook->ready = 0;
1630 hook->h = INVALID_HANDLE_VALUE;
1631 hook->aux = NULL;
1632
1633 hook->prepare = NULL;
1634 hook->start = NULL;
1635 hook->stop = NULL;
1636 hook->check = NULL;
1637 hook->peek = NULL;
1638
1639 return hook;
1640}
1641
1642static void
1643event_hook_free( EventHook hook )
1644{
1645 hook->fh = NULL;
1646 hook->wanted = 0;
1647 hook->ready = 0;
1648 hook->next = _free_hooks;
1649 _free_hooks = hook;
1650}
1651
1652
1653static void
1654event_hook_signal( EventHook hook )
1655{
1656 FH f = hook->fh;
1657 int fd = _fh_to_int(f);
1658 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1659
1660 if (fde != NULL && fde->fd == fd) {
1661 if ((fde->state & FDE_PENDING) == 0) {
1662 fde->state |= FDE_PENDING;
1663 fdevent_plist_enqueue( fde );
1664 }
1665 fde->events |= hook->wanted;
1666 }
1667}
1668
1669
1670#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1671
1672typedef struct EventLooperRec_
1673{
1674 EventHook hooks;
1675 HANDLE htab[ MAX_LOOPER_HANDLES ];
1676 int htab_count;
1677
1678} EventLooperRec;
1679
1680static EventHook*
1681event_looper_find_p( EventLooper looper, FH fh )
1682{
1683 EventHook *pnode = &looper->hooks;
1684 EventHook node = *pnode;
1685 for (;;) {
1686 if ( node == NULL || node->fh == fh )
1687 break;
1688 pnode = &node->next;
1689 node = *pnode;
1690 }
1691 return pnode;
1692}
1693
1694static void
1695event_looper_hook( EventLooper looper, int fd, int events )
1696{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001697 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001698 EventHook *pnode;
1699 EventHook node;
1700
1701 if (f == NULL) /* invalid arg */ {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001702 D("event_looper_hook: invalid fd=%d", fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001703 return;
1704 }
1705
1706 pnode = event_looper_find_p( looper, f );
1707 node = *pnode;
1708 if ( node == NULL ) {
1709 node = event_hook_alloc( f );
1710 node->next = *pnode;
1711 *pnode = node;
1712 }
1713
1714 if ( (node->wanted & events) != events ) {
1715 /* this should update start/stop/check/peek */
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001716 D("event_looper_hook: call hook for %d (new=%x, old=%x)",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001717 fd, node->wanted, events);
1718 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1719 node->wanted |= events;
1720 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001721 D("event_looper_hook: ignoring events %x for %d wanted=%x)",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001722 events, fd, node->wanted);
1723 }
1724}
1725
1726static void
1727event_looper_unhook( EventLooper looper, int fd, int events )
1728{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001729 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001730 EventHook *pnode = event_looper_find_p( looper, fh );
1731 EventHook node = *pnode;
1732
1733 if (node != NULL) {
1734 int events2 = events & node->wanted;
1735 if ( events2 == 0 ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001736 D( "event_looper_unhook: events %x not registered for fd %d", events, fd );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001737 return;
1738 }
1739 node->wanted &= ~events2;
1740 if (!node->wanted) {
1741 *pnode = node->next;
1742 event_hook_free( node );
1743 }
1744 }
1745}
1746
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001747/*
1748 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1749 * handles to wait on.
1750 *
1751 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1752 * instance, this may happen if there are more than 64 processes running on a
1753 * device, or there are multiple devices connected (including the emulator) with
1754 * the combined number of running processes greater than 64. In this case using
1755 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1756 * because of the API limitations (64 handles max). So, we need to provide a way
1757 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1758 * easiest (and "Microsoft recommended") way to do that would be dividing the
1759 * handle array into chunks with the chunk size less than 64, and fire up as many
1760 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1761 * handles, and will report back to the caller which handle has been set.
1762 * Here is the implementation of that algorithm.
1763 */
1764
1765/* Number of handles to wait on in each wating thread. */
1766#define WAIT_ALL_CHUNK_SIZE 63
1767
1768/* Descriptor for a wating thread */
1769typedef struct WaitForAllParam {
1770 /* A handle to an event to signal when waiting is over. This handle is shared
1771 * accross all the waiting threads, so each waiting thread knows when any
1772 * other thread has exited, so it can exit too. */
1773 HANDLE main_event;
1774 /* Upon exit from a waiting thread contains the index of the handle that has
1775 * been signaled. The index is an absolute index of the signaled handle in
1776 * the original array. This pointer is shared accross all the waiting threads
1777 * and it's not guaranteed (due to a race condition) that when all the
1778 * waiting threads exit, the value contained here would indicate the first
1779 * handle that was signaled. This is fine, because the caller cares only
1780 * about any handle being signaled. It doesn't care about the order, nor
1781 * about the whole list of handles that were signaled. */
1782 LONG volatile *signaled_index;
1783 /* Array of handles to wait on in a waiting thread. */
1784 HANDLE* handles;
1785 /* Number of handles in 'handles' array to wait on. */
1786 int handles_count;
1787 /* Index inside the main array of the first handle in the 'handles' array. */
1788 int first_handle_index;
1789 /* Waiting thread handle. */
1790 HANDLE thread;
1791} WaitForAllParam;
1792
1793/* Waiting thread routine. */
1794static unsigned __stdcall
1795_in_waiter_thread(void* arg)
1796{
1797 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1798 int res;
1799 WaitForAllParam* const param = (WaitForAllParam*)arg;
1800
1801 /* We have to wait on the main_event in order to be notified when any of the
1802 * sibling threads is exiting. */
1803 wait_on[0] = param->main_event;
1804 /* The rest of the handles go behind the main event handle. */
1805 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1806
1807 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1808 if (res > 0 && res < (param->handles_count + 1)) {
1809 /* One of the original handles got signaled. Save its absolute index into
1810 * the output variable. */
1811 InterlockedCompareExchange(param->signaled_index,
1812 res - 1L + param->first_handle_index, -1L);
1813 }
1814
1815 /* Notify the caller (and the siblings) that the wait is over. */
1816 SetEvent(param->main_event);
1817
1818 _endthreadex(0);
1819 return 0;
1820}
1821
1822/* WaitForMultipeObjects fixer routine.
1823 * Param:
1824 * handles Array of handles to wait on.
1825 * handles_count Number of handles in the array.
1826 * Return:
1827 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1828 * WAIT_FAILED on an error.
1829 */
1830static int
1831_wait_for_all(HANDLE* handles, int handles_count)
1832{
1833 WaitForAllParam* threads;
1834 HANDLE main_event;
1835 int chunks, chunk, remains;
1836
1837 /* This variable is going to be accessed by several threads at the same time,
1838 * this is bound to fail randomly when the core is run on multi-core machines.
1839 * To solve this, we need to do the following (1 _and_ 2):
1840 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1841 * out the reads/writes in this function unexpectedly.
1842 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1843 * all accesses inside a critical section. But we can also use
1844 * InterlockedCompareExchange() which always provide a full memory barrier
1845 * on Win32.
1846 */
1847 volatile LONG sig_index = -1;
1848
1849 /* Calculate number of chunks, and allocate thread param array. */
1850 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1851 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1852 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1853 sizeof(WaitForAllParam));
1854 if (threads == NULL) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001855 D("Unable to allocate thread array for %d handles.", handles_count);
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001856 return (int)WAIT_FAILED;
1857 }
1858
1859 /* Create main event to wait on for all waiting threads. This is a "manualy
1860 * reset" event that will remain set once it was set. */
1861 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1862 if (main_event == NULL) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001863 D("Unable to create main event. Error: %ld", GetLastError());
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001864 free(threads);
1865 return (int)WAIT_FAILED;
1866 }
1867
1868 /*
1869 * Initialize waiting thread parameters.
1870 */
1871
1872 for (chunk = 0; chunk < chunks; chunk++) {
1873 threads[chunk].main_event = main_event;
1874 threads[chunk].signaled_index = &sig_index;
1875 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1876 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1877 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1878 }
1879 if (remains) {
1880 threads[chunk].main_event = main_event;
1881 threads[chunk].signaled_index = &sig_index;
1882 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1883 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1884 threads[chunk].handles_count = remains;
1885 chunks++;
1886 }
1887
1888 /* Start the waiting threads. */
1889 for (chunk = 0; chunk < chunks; chunk++) {
1890 /* Note that using adb_thread_create is not appropriate here, since we
1891 * need a handle to wait on for thread termination. */
1892 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1893 &threads[chunk], 0, NULL);
1894 if (threads[chunk].thread == NULL) {
1895 /* Unable to create a waiter thread. Collapse. */
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001896 D("Unable to create a waiting thread %d of %d. errno=%d",
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001897 chunk, chunks, errno);
1898 chunks = chunk;
1899 SetEvent(main_event);
1900 break;
1901 }
1902 }
1903
1904 /* Wait on any of the threads to get signaled. */
1905 WaitForSingleObject(main_event, INFINITE);
1906
1907 /* Wait on all the waiting threads to exit. */
1908 for (chunk = 0; chunk < chunks; chunk++) {
1909 WaitForSingleObject(threads[chunk].thread, INFINITE);
1910 CloseHandle(threads[chunk].thread);
1911 }
1912
1913 CloseHandle(main_event);
1914 free(threads);
1915
1916
1917 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1918 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1919}
1920
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001921static EventLooperRec win32_looper;
1922
1923static void fdevent_init(void)
1924{
1925 win32_looper.htab_count = 0;
1926 win32_looper.hooks = NULL;
1927}
1928
1929static void fdevent_connect(fdevent *fde)
1930{
1931 EventLooper looper = &win32_looper;
1932 int events = fde->state & FDE_EVENTMASK;
1933
1934 if (events != 0)
1935 event_looper_hook( looper, fde->fd, events );
1936}
1937
1938static void fdevent_disconnect(fdevent *fde)
1939{
1940 EventLooper looper = &win32_looper;
1941 int events = fde->state & FDE_EVENTMASK;
1942
1943 if (events != 0)
1944 event_looper_unhook( looper, fde->fd, events );
1945}
1946
1947static void fdevent_update(fdevent *fde, unsigned events)
1948{
1949 EventLooper looper = &win32_looper;
1950 unsigned events0 = fde->state & FDE_EVENTMASK;
1951
1952 if (events != events0) {
1953 int removes = events0 & ~events;
1954 int adds = events & ~events0;
1955 if (removes) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001956 D("fdevent_update: remove %x from %d", removes, fde->fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001957 event_looper_unhook( looper, fde->fd, removes );
1958 }
1959 if (adds) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001960 D("fdevent_update: add %x to %d", adds, fde->fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001961 event_looper_hook ( looper, fde->fd, adds );
1962 }
1963 }
1964}
1965
1966static void fdevent_process()
1967{
1968 EventLooper looper = &win32_looper;
1969 EventHook hook;
1970 int gotone = 0;
1971
1972 /* if we have at least one ready hook, execute it/them */
1973 for (hook = looper->hooks; hook; hook = hook->next) {
1974 hook->ready = 0;
1975 if (hook->prepare) {
1976 hook->prepare(hook);
1977 if (hook->ready != 0) {
1978 event_hook_signal( hook );
1979 gotone = 1;
1980 }
1981 }
1982 }
1983
1984 /* nothing's ready yet, so wait for something to happen */
1985 if (!gotone)
1986 {
1987 looper->htab_count = 0;
1988
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001989 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001990 {
1991 if (hook->start && !hook->start(hook)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001992 D( "fdevent_process: error when starting a hook" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001993 return;
1994 }
1995 if (hook->h != INVALID_HANDLE_VALUE) {
1996 int nn;
1997
1998 for (nn = 0; nn < looper->htab_count; nn++)
1999 {
2000 if ( looper->htab[nn] == hook->h )
2001 goto DontAdd;
2002 }
2003 looper->htab[ looper->htab_count++ ] = hook->h;
2004 DontAdd:
2005 ;
2006 }
2007 }
2008
2009 if (looper->htab_count == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002010 D( "fdevent_process: nothing to wait for !!" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002011 return;
2012 }
2013
2014 do
2015 {
2016 int wait_ret;
2017
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002018 D( "adb_win32: waiting for %d events", looper->htab_count );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002019 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002020 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.", looper->htab_count);
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08002021 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
2022 } else {
2023 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002024 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002025 if (wait_ret == (int)WAIT_FAILED) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002026 D( "adb_win32: wait failed, error %ld", GetLastError() );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002027 } else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002028 D( "adb_win32: got one (index %d)", wait_ret );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002029
2030 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
2031 * like mouse movements. we need to filter these with the "check" function
2032 */
2033 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
2034 {
2035 for (hook = looper->hooks; hook; hook = hook->next)
2036 {
2037 if ( looper->htab[wait_ret] == hook->h &&
2038 (!hook->check || hook->check(hook)) )
2039 {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002040 D( "adb_win32: signaling %s for %x", hook->fh->name, hook->ready );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002041 event_hook_signal( hook );
2042 gotone = 1;
2043 break;
2044 }
2045 }
2046 }
2047 }
2048 }
2049 while (!gotone);
2050
2051 for (hook = looper->hooks; hook; hook = hook->next) {
2052 if (hook->stop)
2053 hook->stop( hook );
2054 }
2055 }
2056
2057 for (hook = looper->hooks; hook; hook = hook->next) {
2058 if (hook->peek && hook->peek(hook))
2059 event_hook_signal( hook );
2060 }
2061}
2062
2063
2064static void fdevent_register(fdevent *fde)
2065{
2066 int fd = fde->fd - WIN32_FH_BASE;
2067
2068 if(fd < 0) {
2069 FATAL("bogus negative fd (%d)\n", fde->fd);
2070 }
2071
2072 if(fd >= fd_table_max) {
2073 int oldmax = fd_table_max;
2074 if(fde->fd > 32000) {
2075 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
2076 }
2077 if(fd_table_max == 0) {
2078 fdevent_init();
2079 fd_table_max = 256;
2080 }
2081 while(fd_table_max <= fd) {
2082 fd_table_max *= 2;
2083 }
Elliott Hughesa2f2e562015-04-16 16:47:02 -07002084 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002085 if(fd_table == 0) {
2086 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
2087 }
2088 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
2089 }
2090
2091 fd_table[fd] = fde;
2092}
2093
2094static void fdevent_unregister(fdevent *fde)
2095{
2096 int fd = fde->fd - WIN32_FH_BASE;
2097
2098 if((fd < 0) || (fd >= fd_table_max)) {
2099 FATAL("fd out of range (%d)\n", fde->fd);
2100 }
2101
2102 if(fd_table[fd] != fde) {
2103 FATAL("fd_table out of sync");
2104 }
2105
2106 fd_table[fd] = 0;
2107
2108 if(!(fde->state & FDE_DONT_CLOSE)) {
2109 dump_fde(fde, "close");
2110 adb_close(fde->fd);
2111 }
2112}
2113
2114static void fdevent_plist_enqueue(fdevent *node)
2115{
2116 fdevent *list = &list_pending;
2117
2118 node->next = list;
2119 node->prev = list->prev;
2120 node->prev->next = node;
2121 list->prev = node;
2122}
2123
2124static void fdevent_plist_remove(fdevent *node)
2125{
2126 node->prev->next = node->next;
2127 node->next->prev = node->prev;
2128 node->next = 0;
2129 node->prev = 0;
2130}
2131
2132static fdevent *fdevent_plist_dequeue(void)
2133{
2134 fdevent *list = &list_pending;
2135 fdevent *node = list->next;
2136
2137 if(node == list) return 0;
2138
2139 list->next = node->next;
2140 list->next->prev = list;
2141 node->next = 0;
2142 node->prev = 0;
2143
2144 return node;
2145}
2146
2147fdevent *fdevent_create(int fd, fd_func func, void *arg)
2148{
2149 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2150 if(fde == 0) return 0;
2151 fdevent_install(fde, fd, func, arg);
2152 fde->state |= FDE_CREATED;
2153 return fde;
2154}
2155
2156void fdevent_destroy(fdevent *fde)
2157{
2158 if(fde == 0) return;
2159 if(!(fde->state & FDE_CREATED)) {
2160 FATAL("fde %p not created by fdevent_create()\n", fde);
2161 }
2162 fdevent_remove(fde);
2163}
2164
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08002165void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002166{
2167 memset(fde, 0, sizeof(fdevent));
2168 fde->state = FDE_ACTIVE;
2169 fde->fd = fd;
2170 fde->func = func;
2171 fde->arg = arg;
2172
2173 fdevent_register(fde);
2174 dump_fde(fde, "connect");
2175 fdevent_connect(fde);
2176 fde->state |= FDE_ACTIVE;
2177}
2178
2179void fdevent_remove(fdevent *fde)
2180{
2181 if(fde->state & FDE_PENDING) {
2182 fdevent_plist_remove(fde);
2183 }
2184
2185 if(fde->state & FDE_ACTIVE) {
2186 fdevent_disconnect(fde);
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08002187 dump_fde(fde, "disconnect");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002188 fdevent_unregister(fde);
2189 }
2190
2191 fde->state = 0;
2192 fde->events = 0;
2193}
2194
2195
2196void fdevent_set(fdevent *fde, unsigned events)
2197{
2198 events &= FDE_EVENTMASK;
2199
2200 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2201
2202 if(fde->state & FDE_ACTIVE) {
2203 fdevent_update(fde, events);
2204 dump_fde(fde, "update");
2205 }
2206
2207 fde->state = (fde->state & FDE_STATEMASK) | events;
2208
2209 if(fde->state & FDE_PENDING) {
2210 /* if we're pending, make sure
2211 ** we don't signal an event that
2212 ** is no longer wanted.
2213 */
2214 fde->events &= (~events);
2215 if(fde->events == 0) {
2216 fdevent_plist_remove(fde);
2217 fde->state &= (~FDE_PENDING);
2218 }
2219 }
2220}
2221
2222void fdevent_add(fdevent *fde, unsigned events)
2223{
2224 fdevent_set(
2225 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2226}
2227
2228void fdevent_del(fdevent *fde, unsigned events)
2229{
2230 fdevent_set(
2231 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2232}
2233
2234void fdevent_loop()
2235{
2236 fdevent *fde;
2237
2238 for(;;) {
2239#if DEBUG
2240 fprintf(stderr,"--- ---- waiting for events\n");
2241#endif
2242 fdevent_process();
2243
2244 while((fde = fdevent_plist_dequeue())) {
2245 unsigned events = fde->events;
2246 fde->events = 0;
2247 fde->state &= (~FDE_PENDING);
2248 dump_fde(fde, "callback");
2249 fde->func(fde->fd, events, fde->arg);
2250 }
2251 }
2252}
2253
2254/** FILE EVENT HOOKS
2255 **/
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02002256
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002257static void _event_file_prepare( EventHook hook )
2258{
2259 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2260 /* we can always read/write */
2261 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2262 }
2263}
2264
2265static int _event_file_peek( EventHook hook )
2266{
2267 return (hook->wanted & (FDE_READ|FDE_WRITE));
2268}
2269
2270static void _fh_file_hook( FH f, int events, EventHook hook )
2271{
2272 hook->h = f->fh_handle;
2273 hook->prepare = _event_file_prepare;
2274 hook->peek = _event_file_peek;
2275}
2276
2277/** SOCKET EVENT HOOKS
2278 **/
2279
2280static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2281{
2282 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2283 if (hook->wanted & FDE_READ)
2284 hook->ready |= FDE_READ;
2285 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2286 hook->ready |= FDE_ERROR;
2287 }
2288 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2289 if (hook->wanted & FDE_WRITE)
2290 hook->ready |= FDE_WRITE;
2291 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2292 hook->ready |= FDE_ERROR;
2293 }
2294 if ( evts->lNetworkEvents & FD_OOB ) {
2295 if (hook->wanted & FDE_ERROR)
2296 hook->ready |= FDE_ERROR;
2297 }
2298}
2299
2300static void _event_socket_prepare( EventHook hook )
2301{
2302 WSANETWORKEVENTS evts;
2303
2304 /* look if some of the events we want already happened ? */
2305 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2306 _event_socket_verify( hook, &evts );
2307}
2308
2309static int _socket_wanted_to_flags( int wanted )
2310{
2311 int flags = 0;
2312 if (wanted & FDE_READ)
2313 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2314
2315 if (wanted & FDE_WRITE)
2316 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2317
2318 if (wanted & FDE_ERROR)
2319 flags |= FD_OOB;
2320
2321 return flags;
2322}
2323
2324static int _event_socket_start( EventHook hook )
2325{
2326 /* create an event which we're going to wait for */
2327 FH fh = hook->fh;
2328 long flags = _socket_wanted_to_flags( hook->wanted );
2329
2330 hook->h = fh->event;
2331 if (hook->h == INVALID_HANDLE_VALUE) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002332 D( "_event_socket_start: no event for %s", fh->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002333 return 0;
2334 }
2335
2336 if ( flags != fh->mask ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002337 D( "_event_socket_start: hooking %s for %x (flags %ld)", hook->fh->name, hook->wanted, flags );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002338 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002339 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d", hook->fh->name, WSAGetLastError() );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002340 CloseHandle( hook->h );
2341 hook->h = INVALID_HANDLE_VALUE;
2342 exit(1);
2343 return 0;
2344 }
2345 fh->mask = flags;
2346 }
2347 return 1;
2348}
2349
2350static void _event_socket_stop( EventHook hook )
2351{
2352 hook->h = INVALID_HANDLE_VALUE;
2353}
2354
2355static int _event_socket_check( EventHook hook )
2356{
2357 int result = 0;
2358 FH fh = hook->fh;
2359 WSANETWORKEVENTS evts;
2360
2361 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2362 _event_socket_verify( hook, &evts );
2363 result = (hook->ready != 0);
2364 if (result) {
2365 ResetEvent( hook->h );
2366 }
2367 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002368 D( "_event_socket_check %s returns %d", fh->name, result );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002369 return result;
2370}
2371
2372static int _event_socket_peek( EventHook hook )
2373{
2374 WSANETWORKEVENTS evts;
2375 FH fh = hook->fh;
2376
2377 /* look if some of the events we want already happened ? */
2378 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2379 _event_socket_verify( hook, &evts );
2380 if (hook->ready)
2381 ResetEvent( hook->h );
2382 }
2383
2384 return hook->ready != 0;
2385}
2386
2387
2388
2389static void _fh_socket_hook( FH f, int events, EventHook hook )
2390{
2391 hook->prepare = _event_socket_prepare;
2392 hook->start = _event_socket_start;
2393 hook->stop = _event_socket_stop;
2394 hook->check = _event_socket_check;
2395 hook->peek = _event_socket_peek;
2396
Spencer Low5200c662015-07-30 23:07:55 -07002397 // TODO: check return value?
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002398 _event_socket_start( hook );
2399}
2400
2401/** SOCKETPAIR EVENT HOOKS
2402 **/
2403
2404static void _event_socketpair_prepare( EventHook hook )
2405{
2406 FH fh = hook->fh;
2407 SocketPair pair = fh->fh_pair;
2408 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2409 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2410
2411 if (hook->wanted & FDE_READ && rbip->can_read)
2412 hook->ready |= FDE_READ;
2413
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08002414 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002415 hook->ready |= FDE_WRITE;
2416 }
2417
2418 static int _event_socketpair_start( EventHook hook )
2419 {
2420 FH fh = hook->fh;
2421 SocketPair pair = fh->fh_pair;
2422 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2423 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2424
2425 if (hook->wanted == FDE_READ)
2426 hook->h = rbip->evt_read;
2427
2428 else if (hook->wanted == FDE_WRITE)
2429 hook->h = wbip->evt_write;
2430
2431 else {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002432 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002433 return 0;
2434 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002435 D( "_event_socketpair_start: hook %s for %x wanted=%x",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002436 hook->fh->name, _fh_to_int(fh), hook->wanted);
2437 return 1;
2438}
2439
2440static int _event_socketpair_peek( EventHook hook )
2441{
2442 _event_socketpair_prepare( hook );
2443 return hook->ready != 0;
2444}
2445
2446static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2447{
2448 hook->prepare = _event_socketpair_prepare;
2449 hook->start = _event_socketpair_start;
2450 hook->peek = _event_socketpair_peek;
2451}
2452
2453
2454void
2455adb_sysdeps_init( void )
2456{
2457#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2458#include "mutex_list.h"
2459 InitializeCriticalSection( &_win32_lock );
2460}
2461
Spencer Low50184062015-03-01 15:06:21 -08002462/**************************************************************************/
2463/**************************************************************************/
2464/***** *****/
2465/***** Console Window Terminal Emulation *****/
2466/***** *****/
2467/**************************************************************************/
2468/**************************************************************************/
2469
2470// This reads input from a Win32 console window and translates it into Unix
2471// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2472// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2473// is emulated instead of xterm because it is probably more popular than xterm:
2474// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2475// supports modern fonts, etc. It seems best to emulate the terminal that most
2476// Android developers use because they'll fix apps (the shell, etc.) to keep
2477// working with that terminal's emulation.
2478//
2479// The point of this emulation is not to be perfect or to solve all issues with
2480// console windows on Windows, but to be better than the original code which
2481// just called read() (which called ReadFile(), which called ReadConsoleA())
2482// which did not support Ctrl-C, tab completion, shell input line editing
2483// keys, server echo, and more.
2484//
2485// This implementation reconfigures the console with SetConsoleMode(), then
2486// calls ReadConsoleInput() to get raw input which it remaps to Unix
2487// terminal-style sequences which is returned via unix_read() which is used
2488// by the 'adb shell' command.
2489//
2490// Code organization:
2491//
David Pursellc5b8ad82015-10-28 14:29:51 -07002492// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08002493// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2494// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2495// * _console_read() is the main code of the emulation.
2496
David Pursellc5b8ad82015-10-28 14:29:51 -07002497// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
2498// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
2499// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
2500static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
2501 // First check isatty(); this is very fast and eliminates most non-console
2502 // FDs, but returns 1 for both consoles and character devices like NUL.
2503#pragma push_macro("isatty")
2504#undef isatty
2505 if (!isatty(fd)) {
2506 return nullptr;
2507 }
2508#pragma pop_macro("isatty")
2509
2510 // To differentiate between character devices and consoles we need to get
2511 // the underlying HANDLE and use GetConsoleMode(), which is what requires
2512 // GENERIC_READ permissions.
2513 const intptr_t intptr_handle = _get_osfhandle(fd);
2514 if (intptr_handle == -1) {
2515 return nullptr;
2516 }
2517 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
2518 DWORD temp_mode = 0;
2519 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
2520 return nullptr;
2521 }
2522
2523 return handle;
2524}
2525
2526// Returns a console handle if |stream| is a console, otherwise returns nullptr.
2527static HANDLE _get_console_handle(FILE* const stream) {
2528 const int fd = fileno(stream);
2529 if (fd < 0) {
2530 return nullptr;
2531 }
2532 return _get_console_handle(fd);
2533}
2534
2535int unix_isatty(int fd) {
2536 return _get_console_handle(fd) ? 1 : 0;
2537}
Spencer Low50184062015-03-01 15:06:21 -08002538
Spencer Low32762f42015-11-10 19:17:16 -08002539// Get the next KEY_EVENT_RECORD that should be processed.
2540static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08002541 for (;;) {
2542 DWORD read_count = 0;
2543 memset(input_record, 0, sizeof(*input_record));
2544 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08002545 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08002546 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002547 errno = EIO;
2548 return false;
2549 }
2550
2551 if (read_count == 0) { // should be impossible
2552 fatal("ReadConsoleInputA returned 0");
2553 }
2554
2555 if (read_count != 1) { // should be impossible
2556 fatal("ReadConsoleInputA did not return one input record");
2557 }
2558
Spencer Low2e02dc62015-11-07 17:34:39 -08002559 // If the console window is resized, emulate SIGWINCH by breaking out
2560 // of read() with errno == EINTR. Note that there is no event on
2561 // vertical resize because we don't give the console our own custom
2562 // screen buffer (with CreateConsoleScreenBuffer() +
2563 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
2564 // supports scrollback, but doesn't seem to raise an event for vertical
2565 // window resize.
2566 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
2567 errno = EINTR;
2568 return false;
2569 }
2570
Spencer Low50184062015-03-01 15:06:21 -08002571 if ((input_record->EventType == KEY_EVENT) &&
2572 (input_record->Event.KeyEvent.bKeyDown)) {
2573 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2574 fatal("ReadConsoleInputA returned a key event with zero repeat"
2575 " count");
2576 }
2577
2578 // Got an interesting INPUT_RECORD, so return
2579 return true;
2580 }
2581 }
2582}
2583
Spencer Low50184062015-03-01 15:06:21 -08002584static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2585 return (control_key_state & SHIFT_PRESSED) != 0;
2586}
2587
2588static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2589 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2590}
2591
2592static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2593 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2594}
2595
2596static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2597 return (control_key_state & NUMLOCK_ON) != 0;
2598}
2599
2600static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2601 return (control_key_state & CAPSLOCK_ON) != 0;
2602}
2603
2604static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2605 return (control_key_state & ENHANCED_KEY) != 0;
2606}
2607
2608// Constants from MSDN for ToAscii().
2609static const BYTE TOASCII_KEY_OFF = 0x00;
2610static const BYTE TOASCII_KEY_DOWN = 0x80;
2611static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2612
2613// Given a key event, ignore a modifier key and return the character that was
2614// entered without the modifier. Writes to *ch and returns the number of bytes
2615// written.
2616static size_t _get_char_ignoring_modifier(char* const ch,
2617 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2618 const WORD modifier) {
2619 // If there is no character from Windows, try ignoring the specified
2620 // modifier and look for a character. Note that if AltGr is being used,
2621 // there will be a character from Windows.
2622 if (key_event->uChar.AsciiChar == '\0') {
2623 // Note that we read the control key state from the passed in argument
2624 // instead of from key_event since the argument has been normalized.
2625 if (((modifier == VK_SHIFT) &&
2626 _is_shift_pressed(control_key_state)) ||
2627 ((modifier == VK_CONTROL) &&
2628 _is_ctrl_pressed(control_key_state)) ||
2629 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2630
2631 BYTE key_state[256] = {0};
2632 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2633 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2634 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2635 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2636 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2637 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2638 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2639 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2640
2641 // cause this modifier to be ignored
2642 key_state[modifier] = TOASCII_KEY_OFF;
2643
2644 WORD translated = 0;
2645 if (ToAscii(key_event->wVirtualKeyCode,
2646 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2647 // Ignoring the modifier, we found a character.
2648 *ch = (CHAR)translated;
2649 return 1;
2650 }
2651 }
2652 }
2653
2654 // Just use whatever Windows told us originally.
2655 *ch = key_event->uChar.AsciiChar;
2656
2657 // If the character from Windows is NULL, return a size of zero.
2658 return (*ch == '\0') ? 0 : 1;
2659}
2660
2661// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2662// but taking into account the shift key. This is because for a sequence like
2663// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2664// we want to find the character ')'.
2665//
2666// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2667// because it is the default key-sequence to switch the input language.
2668// This is configurable in the Region and Language control panel.
2669static __inline__ size_t _get_non_control_char(char* const ch,
2670 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2671 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2672 VK_CONTROL);
2673}
2674
2675// Get without Alt.
2676static __inline__ size_t _get_non_alt_char(char* const ch,
2677 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2678 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2679 VK_MENU);
2680}
2681
2682// Ignore the control key, find the character from Windows, and apply any
2683// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2684// *pch and returns number of bytes written.
2685static size_t _get_control_character(char* const pch,
2686 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2687 const size_t len = _get_non_control_char(pch, key_event,
2688 control_key_state);
2689
2690 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2691 char ch = *pch;
2692 switch (ch) {
2693 case '2':
2694 case '@':
2695 case '`':
2696 ch = '\0';
2697 break;
2698 case '3':
2699 case '[':
2700 case '{':
2701 ch = '\x1b';
2702 break;
2703 case '4':
2704 case '\\':
2705 case '|':
2706 ch = '\x1c';
2707 break;
2708 case '5':
2709 case ']':
2710 case '}':
2711 ch = '\x1d';
2712 break;
2713 case '6':
2714 case '^':
2715 case '~':
2716 ch = '\x1e';
2717 break;
2718 case '7':
2719 case '-':
2720 case '_':
2721 ch = '\x1f';
2722 break;
2723 case '8':
2724 ch = '\x7f';
2725 break;
2726 case '/':
2727 if (!_is_alt_pressed(control_key_state)) {
2728 ch = '\x1f';
2729 }
2730 break;
2731 case '?':
2732 if (!_is_alt_pressed(control_key_state)) {
2733 ch = '\x7f';
2734 }
2735 break;
2736 }
2737 *pch = ch;
2738 }
2739
2740 return len;
2741}
2742
2743static DWORD _normalize_altgr_control_key_state(
2744 const KEY_EVENT_RECORD* const key_event) {
2745 DWORD control_key_state = key_event->dwControlKeyState;
2746
2747 // If we're in an AltGr situation where the AltGr key is down (depending on
2748 // the keyboard layout, that might be the physical right alt key which
2749 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2750 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2751 // a character (which indicates that there was an AltGr mapping), then act
2752 // as if alt and control are not really down for the purposes of modifiers.
2753 // This makes it so that if the user with, say, a German keyboard layout
2754 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2755 // output the key and we don't see the Alt and Ctrl keys.
2756 if (_is_ctrl_pressed(control_key_state) &&
2757 _is_alt_pressed(control_key_state)
2758 && (key_event->uChar.AsciiChar != '\0')) {
2759 // Try to remove as few bits as possible to improve our chances of
2760 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2761 // Left-Alt + Right-Ctrl + AltGr.
2762 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2763 // Remove Right-Alt.
2764 control_key_state &= ~RIGHT_ALT_PRESSED;
2765 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2766 // pressed, Left-Ctrl is almost always set, except if the user
2767 // presses Right-Ctrl, then AltGr (in that specific order) for
2768 // whatever reason. At any rate, make sure the bit is not set.
2769 control_key_state &= ~LEFT_CTRL_PRESSED;
2770 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2771 // Remove Left-Alt.
2772 control_key_state &= ~LEFT_ALT_PRESSED;
2773 // Whichever Ctrl key is down, remove it from the state. We only
2774 // remove one key, to improve our chances of detecting the
2775 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2776 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2777 // Remove Left-Ctrl.
2778 control_key_state &= ~LEFT_CTRL_PRESSED;
2779 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2780 // Remove Right-Ctrl.
2781 control_key_state &= ~RIGHT_CTRL_PRESSED;
2782 }
2783 }
2784
2785 // Note that this logic isn't 100% perfect because Windows doesn't
2786 // allow us to detect all combinations because a physical AltGr key
2787 // press shows up as two bits, plus some combinations are ambiguous
2788 // about what is actually physically pressed.
2789 }
2790
2791 return control_key_state;
2792}
2793
2794// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2795// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2796// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2797// appropriately.
2798static DWORD _normalize_keypad_control_key_state(const WORD vk,
2799 const DWORD control_key_state) {
2800 if (!_is_numlock_on(control_key_state)) {
2801 return control_key_state;
2802 }
2803 if (!_is_enhanced_key(control_key_state)) {
2804 switch (vk) {
2805 case VK_INSERT: // 0
2806 case VK_DELETE: // .
2807 case VK_END: // 1
2808 case VK_DOWN: // 2
2809 case VK_NEXT: // 3
2810 case VK_LEFT: // 4
2811 case VK_CLEAR: // 5
2812 case VK_RIGHT: // 6
2813 case VK_HOME: // 7
2814 case VK_UP: // 8
2815 case VK_PRIOR: // 9
2816 return control_key_state | SHIFT_PRESSED;
2817 }
2818 }
2819
2820 return control_key_state;
2821}
2822
2823static const char* _get_keypad_sequence(const DWORD control_key_state,
2824 const char* const normal, const char* const shifted) {
2825 if (_is_shift_pressed(control_key_state)) {
2826 // Shift is pressed and NumLock is off
2827 return shifted;
2828 } else {
2829 // Shift is not pressed and NumLock is off, or,
2830 // Shift is pressed and NumLock is on, in which case we want the
2831 // NumLock and Shift to neutralize each other, thus, we want the normal
2832 // sequence.
2833 return normal;
2834 }
2835 // If Shift is not pressed and NumLock is on, a different virtual key code
2836 // is returned by Windows, which can be taken care of by a different case
2837 // statement in _console_read().
2838}
2839
2840// Write sequence to buf and return the number of bytes written.
2841static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2842 DWORD control_key_state, const char* const normal) {
2843 // Copy the base sequence into buf.
2844 const size_t len = strlen(normal);
2845 memcpy(buf, normal, len);
2846
2847 int code = 0;
2848
2849 control_key_state = _normalize_keypad_control_key_state(vk,
2850 control_key_state);
2851
2852 if (_is_shift_pressed(control_key_state)) {
2853 code |= 0x1;
2854 }
2855 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2856 code |= 0x2;
2857 }
2858 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2859 code |= 0x4;
2860 }
2861 // If some modifier was held down, then we need to insert the modifier code
2862 if (code != 0) {
2863 if (len == 0) {
2864 // Should be impossible because caller should pass a string of
2865 // non-zero length.
2866 return 0;
2867 }
2868 size_t index = len - 1;
2869 const char lastChar = buf[index];
2870 if (lastChar != '~') {
2871 buf[index++] = '1';
2872 }
2873 buf[index++] = ';'; // modifier separator
2874 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2875 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2876 buf[index++] = '1' + code;
2877 buf[index++] = lastChar; // move ~ (or other last char) to the end
2878 return index;
2879 }
2880 return len;
2881}
2882
2883// Write sequence to buf and return the number of bytes written.
2884static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2885 const DWORD control_key_state, const char* const normal,
2886 const char shifted) {
2887 if (_is_shift_pressed(control_key_state)) {
2888 // Shift is pressed and NumLock is off
2889 if (shifted != '\0') {
2890 buf[0] = shifted;
2891 return sizeof(buf[0]);
2892 } else {
2893 return 0;
2894 }
2895 } else {
2896 // Shift is not pressed and NumLock is off, or,
2897 // Shift is pressed and NumLock is on, in which case we want the
2898 // NumLock and Shift to neutralize each other, thus, we want the normal
2899 // sequence.
2900 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2901 }
2902 // If Shift is not pressed and NumLock is on, a different virtual key code
2903 // is returned by Windows, which can be taken care of by a different case
2904 // statement in _console_read().
2905}
2906
2907// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2908// Standard German. Figure this out at runtime so we know what to output for
2909// Shift-VK_DELETE.
2910static char _get_decimal_char() {
2911 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2912}
2913
2914// Prefix the len bytes in buf with the escape character, and then return the
2915// new buffer length.
2916size_t _escape_prefix(char* const buf, const size_t len) {
2917 // If nothing to prefix, don't do anything. We might be called with
2918 // len == 0, if alt was held down with a dead key which produced nothing.
2919 if (len == 0) {
2920 return 0;
2921 }
2922
2923 memmove(&buf[1], buf, len);
2924 buf[0] = '\x1b';
2925 return len + 1;
2926}
2927
Spencer Low32762f42015-11-10 19:17:16 -08002928// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002929static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08002930
2931// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
2932// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08002933static int _console_read(const HANDLE console, void* buf, size_t len) {
2934 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08002935 // Read of zero bytes should not block waiting for something from the console.
2936 if (len == 0) {
2937 return 0;
2938 }
2939
2940 // Flush as much as possible from input buffer.
2941 if (!g_console_input_buffer.empty()) {
2942 const int bytes_read = std::min(len, g_console_input_buffer.size());
2943 memcpy(buf, g_console_input_buffer.data(), bytes_read);
2944 const auto begin = g_console_input_buffer.begin();
2945 g_console_input_buffer.erase(begin, begin + bytes_read);
2946 return bytes_read;
2947 }
2948
2949 // Read from the actual console. This may block until input.
2950 INPUT_RECORD input_record;
2951 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08002952 return -1;
2953 }
2954
Spencer Low32762f42015-11-10 19:17:16 -08002955 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08002956 const WORD vk = key_event->wVirtualKeyCode;
2957 const CHAR ch = key_event->uChar.AsciiChar;
2958 const DWORD control_key_state = _normalize_altgr_control_key_state(
2959 key_event);
2960
2961 // The following emulation code should write the output sequence to
2962 // either seqstr or to seqbuf and seqbuflen.
2963 const char* seqstr = NULL; // NULL terminated C-string
2964 // Enough space for max sequence string below, plus modifiers and/or
2965 // escape prefix.
2966 char seqbuf[16];
2967 size_t seqbuflen = 0; // Space used in seqbuf.
2968
2969#define MATCH(vk, normal) \
2970 case (vk): \
2971 { \
2972 seqstr = (normal); \
2973 } \
2974 break;
2975
2976 // Modifier keys should affect the output sequence.
2977#define MATCH_MODIFIER(vk, normal) \
2978 case (vk): \
2979 { \
2980 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2981 control_key_state, (normal)); \
2982 } \
2983 break;
2984
2985 // The shift key should affect the output sequence.
2986#define MATCH_KEYPAD(vk, normal, shifted) \
2987 case (vk): \
2988 { \
2989 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2990 (shifted)); \
2991 } \
2992 break;
2993
2994 // The shift key and other modifier keys should affect the output
2995 // sequence.
2996#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2997 case (vk): \
2998 { \
2999 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
3000 control_key_state, (normal), (shifted)); \
3001 } \
3002 break;
3003
3004#define ESC "\x1b"
3005#define CSI ESC "["
3006#define SS3 ESC "O"
3007
3008 // Only support normal mode, not application mode.
3009
3010 // Enhanced keys:
3011 // * 6-pack: insert, delete, home, end, page up, page down
3012 // * cursor keys: up, down, right, left
3013 // * keypad: divide, enter
3014 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
3015 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
3016 if (_is_enhanced_key(control_key_state)) {
3017 switch (vk) {
3018 case VK_RETURN: // Enter key on keypad
3019 if (_is_ctrl_pressed(control_key_state)) {
3020 seqstr = "\n";
3021 } else {
3022 seqstr = "\r";
3023 }
3024 break;
3025
3026 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
3027 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
3028
3029 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
3030 // will be fixed soon to match xterm which sends CSI "F" and
3031 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
3032 MATCH(VK_END, CSI "F");
3033 MATCH(VK_HOME, CSI "H");
3034
3035 MATCH_MODIFIER(VK_LEFT, CSI "D");
3036 MATCH_MODIFIER(VK_UP, CSI "A");
3037 MATCH_MODIFIER(VK_RIGHT, CSI "C");
3038 MATCH_MODIFIER(VK_DOWN, CSI "B");
3039
3040 MATCH_MODIFIER(VK_INSERT, CSI "2~");
3041 MATCH_MODIFIER(VK_DELETE, CSI "3~");
3042
3043 MATCH(VK_DIVIDE, "/");
3044 }
3045 } else { // Non-enhanced keys:
3046 switch (vk) {
3047 case VK_BACK: // backspace
3048 if (_is_alt_pressed(control_key_state)) {
3049 seqstr = ESC "\x7f";
3050 } else {
3051 seqstr = "\x7f";
3052 }
3053 break;
3054
3055 case VK_TAB:
3056 if (_is_shift_pressed(control_key_state)) {
3057 seqstr = CSI "Z";
3058 } else {
3059 seqstr = "\t";
3060 }
3061 break;
3062
3063 // Number 5 key in keypad when NumLock is off, or if NumLock is
3064 // on and Shift is down.
3065 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
3066
3067 case VK_RETURN: // Enter key on main keyboard
3068 if (_is_alt_pressed(control_key_state)) {
3069 seqstr = ESC "\n";
3070 } else if (_is_ctrl_pressed(control_key_state)) {
3071 seqstr = "\n";
3072 } else {
3073 seqstr = "\r";
3074 }
3075 break;
3076
3077 // VK_ESCAPE: Don't do any special handling. The OS uses many
3078 // of the sequences with Escape and many of the remaining
3079 // sequences don't produce bKeyDown messages, only !bKeyDown
3080 // for whatever reason.
3081
3082 case VK_SPACE:
3083 if (_is_alt_pressed(control_key_state)) {
3084 seqstr = ESC " ";
3085 } else if (_is_ctrl_pressed(control_key_state)) {
3086 seqbuf[0] = '\0'; // NULL char
3087 seqbuflen = 1;
3088 } else {
3089 seqstr = " ";
3090 }
3091 break;
3092
3093 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
3094 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
3095
3096 MATCH_KEYPAD(VK_END, CSI "4~", "1");
3097 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
3098
3099 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
3100 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
3101 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
3102 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
3103
3104 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
3105 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
3106 _get_decimal_char());
3107
3108 case 0x30: // 0
3109 case 0x31: // 1
3110 case 0x39: // 9
3111 case VK_OEM_1: // ;:
3112 case VK_OEM_PLUS: // =+
3113 case VK_OEM_COMMA: // ,<
3114 case VK_OEM_PERIOD: // .>
3115 case VK_OEM_7: // '"
3116 case VK_OEM_102: // depends on keyboard, could be <> or \|
3117 case VK_OEM_2: // /?
3118 case VK_OEM_3: // `~
3119 case VK_OEM_4: // [{
3120 case VK_OEM_5: // \|
3121 case VK_OEM_6: // ]}
3122 {
3123 seqbuflen = _get_control_character(seqbuf, key_event,
3124 control_key_state);
3125
3126 if (_is_alt_pressed(control_key_state)) {
3127 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3128 }
3129 }
3130 break;
3131
3132 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08003133 case 0x33: // 3
3134 case 0x34: // 4
3135 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08003136 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08003137 case 0x37: // 7
3138 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08003139 case VK_OEM_MINUS: // -_
3140 {
3141 seqbuflen = _get_control_character(seqbuf, key_event,
3142 control_key_state);
3143
3144 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3145 // prefix with escape.
3146 if (_is_alt_pressed(control_key_state) &&
3147 !(_is_ctrl_pressed(control_key_state) &&
3148 !_is_shift_pressed(control_key_state))) {
3149 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3150 }
3151 }
3152 break;
3153
Spencer Low50184062015-03-01 15:06:21 -08003154 case 0x41: // a
3155 case 0x42: // b
3156 case 0x43: // c
3157 case 0x44: // d
3158 case 0x45: // e
3159 case 0x46: // f
3160 case 0x47: // g
3161 case 0x48: // h
3162 case 0x49: // i
3163 case 0x4a: // j
3164 case 0x4b: // k
3165 case 0x4c: // l
3166 case 0x4d: // m
3167 case 0x4e: // n
3168 case 0x4f: // o
3169 case 0x50: // p
3170 case 0x51: // q
3171 case 0x52: // r
3172 case 0x53: // s
3173 case 0x54: // t
3174 case 0x55: // u
3175 case 0x56: // v
3176 case 0x57: // w
3177 case 0x58: // x
3178 case 0x59: // y
3179 case 0x5a: // z
3180 {
3181 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3182 control_key_state);
3183
3184 // If Alt is pressed, then prefix with escape.
3185 if (_is_alt_pressed(control_key_state)) {
3186 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3187 }
3188 }
3189 break;
3190
3191 // These virtual key codes are generated by the keys on the
3192 // keypad *when NumLock is on* and *Shift is up*.
3193 MATCH(VK_NUMPAD0, "0");
3194 MATCH(VK_NUMPAD1, "1");
3195 MATCH(VK_NUMPAD2, "2");
3196 MATCH(VK_NUMPAD3, "3");
3197 MATCH(VK_NUMPAD4, "4");
3198 MATCH(VK_NUMPAD5, "5");
3199 MATCH(VK_NUMPAD6, "6");
3200 MATCH(VK_NUMPAD7, "7");
3201 MATCH(VK_NUMPAD8, "8");
3202 MATCH(VK_NUMPAD9, "9");
3203
3204 MATCH(VK_MULTIPLY, "*");
3205 MATCH(VK_ADD, "+");
3206 MATCH(VK_SUBTRACT, "-");
3207 // VK_DECIMAL is generated by the . key on the keypad *when
3208 // NumLock is on* and *Shift is up* and the sequence is not
3209 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3210 // Windows Security screen to come up).
3211 case VK_DECIMAL:
3212 // U.S. English uses '.', Germany German uses ','.
3213 seqbuflen = _get_non_control_char(seqbuf, key_event,
3214 control_key_state);
3215 break;
3216
3217 MATCH_MODIFIER(VK_F1, SS3 "P");
3218 MATCH_MODIFIER(VK_F2, SS3 "Q");
3219 MATCH_MODIFIER(VK_F3, SS3 "R");
3220 MATCH_MODIFIER(VK_F4, SS3 "S");
3221 MATCH_MODIFIER(VK_F5, CSI "15~");
3222 MATCH_MODIFIER(VK_F6, CSI "17~");
3223 MATCH_MODIFIER(VK_F7, CSI "18~");
3224 MATCH_MODIFIER(VK_F8, CSI "19~");
3225 MATCH_MODIFIER(VK_F9, CSI "20~");
3226 MATCH_MODIFIER(VK_F10, CSI "21~");
3227 MATCH_MODIFIER(VK_F11, CSI "23~");
3228 MATCH_MODIFIER(VK_F12, CSI "24~");
3229
3230 MATCH_MODIFIER(VK_F13, CSI "25~");
3231 MATCH_MODIFIER(VK_F14, CSI "26~");
3232 MATCH_MODIFIER(VK_F15, CSI "28~");
3233 MATCH_MODIFIER(VK_F16, CSI "29~");
3234 MATCH_MODIFIER(VK_F17, CSI "31~");
3235 MATCH_MODIFIER(VK_F18, CSI "32~");
3236 MATCH_MODIFIER(VK_F19, CSI "33~");
3237 MATCH_MODIFIER(VK_F20, CSI "34~");
3238
3239 // MATCH_MODIFIER(VK_F21, ???);
3240 // MATCH_MODIFIER(VK_F22, ???);
3241 // MATCH_MODIFIER(VK_F23, ???);
3242 // MATCH_MODIFIER(VK_F24, ???);
3243 }
3244 }
3245
3246#undef MATCH
3247#undef MATCH_MODIFIER
3248#undef MATCH_KEYPAD
3249#undef MATCH_MODIFIER_KEYPAD
3250#undef ESC
3251#undef CSI
3252#undef SS3
3253
3254 const char* out;
3255 size_t outlen;
3256
3257 // Check for output in any of:
3258 // * seqstr is set (and strlen can be used to determine the length).
3259 // * seqbuf and seqbuflen are set
3260 // Fallback to ch from Windows.
3261 if (seqstr != NULL) {
3262 out = seqstr;
3263 outlen = strlen(seqstr);
3264 } else if (seqbuflen > 0) {
3265 out = seqbuf;
3266 outlen = seqbuflen;
3267 } else if (ch != '\0') {
3268 // Use whatever Windows told us it is.
3269 seqbuf[0] = ch;
3270 seqbuflen = 1;
3271 out = seqbuf;
3272 outlen = seqbuflen;
3273 } else {
3274 // No special handling for the virtual key code and Windows isn't
3275 // telling us a character code, then we don't know how to translate
3276 // the key press.
3277 //
3278 // Consume the input and 'continue' to cause us to get a new key
3279 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07003280 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08003281 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08003282 continue;
3283 }
3284
Spencer Low32762f42015-11-10 19:17:16 -08003285 // put output wRepeatCount times into g_console_input_buffer
3286 while (key_event->wRepeatCount-- > 0) {
3287 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08003288 }
3289
Spencer Low32762f42015-11-10 19:17:16 -08003290 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08003291 }
3292}
3293
3294static DWORD _old_console_mode; // previous GetConsoleMode() result
3295static HANDLE _console_handle; // when set, console mode should be restored
3296
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003297void stdin_raw_init() {
3298 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Low50184062015-03-01 15:06:21 -08003299
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003300 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3301 // calling the process Ctrl-C routine (configured by
3302 // SetConsoleCtrlHandler()).
3303 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3304 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3305 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08003306 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3307 ENABLE_LINE_INPUT |
3308 ENABLE_ECHO_INPUT);
3309 // Enable ENABLE_WINDOW_INPUT to get window resizes.
3310 new_console_mode |= ENABLE_WINDOW_INPUT;
3311
3312 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003313 // This really should not fail.
3314 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08003315 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08003316 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003317
3318 // Once this is set, it means that stdin has been configured for
3319 // reading from and that the old console mode should be restored later.
3320 _console_handle = in;
3321
3322 // Note that we don't need to configure C Runtime line-ending
3323 // translation because _console_read() does not call the C Runtime to
3324 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08003325}
3326
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003327void stdin_raw_restore() {
3328 if (_console_handle != NULL) {
3329 const HANDLE in = _console_handle;
3330 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08003331
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003332 if (!SetConsoleMode(in, _old_console_mode)) {
3333 // This really should not fail.
3334 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08003335 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08003336 }
3337 }
3338}
3339
Spencer Low2e02dc62015-11-07 17:34:39 -08003340// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
3341int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08003342 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3343 // If it is a request to read from stdin, and stdin_raw_init() has been
3344 // called, and it successfully configured the console, then read from
3345 // the console using Win32 console APIs and partially emulate a unix
3346 // terminal.
3347 return _console_read(_console_handle, buf, len);
3348 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07003349 // On older versions of Windows (definitely 7, definitely not 10),
3350 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07003351 // we need to limit the read size.
3352 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07003353 len = 4096;
3354 }
Spencer Low50184062015-03-01 15:06:21 -08003355 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003356 // can do LF/CR translation (which is overridable with _setmode()).
3357 // Undefine the macro that is set in sysdeps.h which bans calls to
3358 // plain read() in favor of unix_read() or adb_read().
3359#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003360#undef read
3361 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003362#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003363 }
3364}
Spencer Lowcf4ff642015-05-11 01:08:48 -07003365
3366/**************************************************************************/
3367/**************************************************************************/
3368/***** *****/
3369/***** Unicode support *****/
3370/***** *****/
3371/**************************************************************************/
3372/**************************************************************************/
3373
3374// This implements support for using files with Unicode filenames and for
3375// outputting Unicode text to a Win32 console window. This is inspired from
3376// http://utf8everywhere.org/.
3377//
3378// Background
3379// ----------
3380//
3381// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3382// filenames to APIs such as open(). This works because filenames are largely
3383// opaque 'cookies' (perhaps excluding path separators).
3384//
3385// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3386// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3387// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3388// CreateFile() API is really just a macro that adds the W/A based on whether
3389// the UNICODE preprocessor symbol is defined).
3390//
3391// Options
3392// -------
3393//
3394// Thus, to write a portable program, there are a few options:
3395//
3396// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3397// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3398// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3399// open() API.
3400//
3401// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3402// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3403// potentially touching a lot of code.
3404//
3405// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3406// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3407// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3408// or C Runtime API.
3409//
3410// The Choice
3411// ----------
3412//
Spencer Lowd21dc822015-11-12 15:20:15 -08003413// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
3414// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07003415// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08003416// args that are passed to main() at the beginning of program startup. We also use
3417// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07003418// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3419//
3420// Unicode console output
3421// ----------------------
3422//
3423// The way to output Unicode to a Win32 console window is to call
3424// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07003425// such as Lucida Console or Consolas, and in the case of East Asian languages
3426// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3427// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3428// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07003429//
3430// The problem is getting the C Runtime to make fprintf and related APIs call
3431// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3432// promising, but the various modes have issues:
3433//
3434// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3435// UTF-16 do not display properly.
3436// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3437// totally wrong.
3438// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3439// handler to be called (upon a later I/O call), aborting the process.
3440// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3441// to output nothing.
3442//
3443// So the only solution is to write our own adb_fprintf() that converts UTF-8
3444// to UTF-16 and then calls WriteConsoleW().
3445
3446
Spencer Lowcf4ff642015-05-11 01:08:48 -07003447// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3448// be passed to main().
3449NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3450 narrow_args = new char*[argc + 1];
3451
3452 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003453 std::string arg_narrow;
3454 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
3455 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
3456 }
3457 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003458 }
3459 narrow_args[argc] = nullptr; // terminate
3460}
3461
3462NarrowArgs::~NarrowArgs() {
3463 if (narrow_args != nullptr) {
3464 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3465 free(*argp);
3466 }
3467 delete[] narrow_args;
3468 narrow_args = nullptr;
3469 }
3470}
3471
3472int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003473 std::wstring path_wide;
3474 if (!android::base::UTF8ToWide(path, &path_wide)) {
3475 return -1;
3476 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003477 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003478 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003479 } else {
3480 int mode;
3481 va_list args;
3482 va_start(args, options);
3483 mode = va_arg(args, int);
3484 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08003485 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003486 }
3487}
3488
3489// Version of stat() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08003490int adb_stat(const char* path, struct adb_stat* s) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07003491#pragma push_macro("wstat")
3492// This definition of wstat seems to be missing from <sys/stat.h>.
3493#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3494#ifdef _USE_32BIT_TIME_T
3495#define wstat _wstat32i64
3496#else
3497#define wstat _wstat64
3498#endif
3499#else
3500// <sys/stat.h> has a function prototype for wstat() that should be available.
3501#endif
3502
Spencer Lowd21dc822015-11-12 15:20:15 -08003503 std::wstring path_wide;
3504 if (!android::base::UTF8ToWide(path, &path_wide)) {
3505 return -1;
3506 }
3507
3508 return wstat(path_wide.c_str(), s);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003509
3510#pragma pop_macro("wstat")
3511}
3512
3513// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08003514DIR* adb_opendir(const char* path) {
3515 std::wstring path_wide;
3516 if (!android::base::UTF8ToWide(path, &path_wide)) {
3517 return nullptr;
3518 }
3519
Spencer Lowcf4ff642015-05-11 01:08:48 -07003520 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3521 // the fields, but right now all the callers treat the structure as
3522 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08003523 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003524}
3525
3526// Version of readdir() that returns UTF-8 paths.
3527struct dirent* adb_readdir(DIR* dir) {
3528 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3529 struct _wdirent* const went = _wreaddir(wdir);
3530 if (went == nullptr) {
3531 return nullptr;
3532 }
Spencer Lowd21dc822015-11-12 15:20:15 -08003533
Spencer Lowcf4ff642015-05-11 01:08:48 -07003534 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08003535 std::string name_utf8;
3536 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
3537 return nullptr;
3538 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003539
3540 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3541 // space for UTF-16 wchar_t's) with UTF-8 char's.
3542 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3543
3544 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3545 // Name too big to fit in existing buffer.
3546 errno = ENOMEM;
3547 return nullptr;
3548 }
3549
3550 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3551 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3552 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3553 // bigger than the caller expects because they expect a dirent structure
3554 // which has a smaller d_name field. Ignore this since the caller should be
3555 // resilient.
3556
3557 // Rewrite the UTF-16 d_name field to UTF-8.
3558 strcpy(ent->d_name, name_utf8.c_str());
3559
3560 return ent;
3561}
3562
3563// Version of closedir() to go with our version of adb_opendir().
3564int adb_closedir(DIR* dir) {
3565 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3566}
3567
3568// Version of unlink() that takes a UTF-8 path.
3569int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003570 std::wstring wpath;
3571 if (!android::base::UTF8ToWide(path, &wpath)) {
3572 return -1;
3573 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003574
3575 int rc = _wunlink(wpath.c_str());
3576
3577 if (rc == -1 && errno == EACCES) {
3578 /* unlink returns EACCES when the file is read-only, so we first */
3579 /* try to make it writable, then unlink again... */
3580 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3581 if (rc == 0)
3582 rc = _wunlink(wpath.c_str());
3583 }
3584 return rc;
3585}
3586
3587// Version of mkdir() that takes a UTF-8 path.
3588int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003589 std::wstring path_wide;
3590 if (!android::base::UTF8ToWide(path, &path_wide)) {
3591 return -1;
3592 }
3593
3594 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003595}
3596
3597// Version of utime() that takes a UTF-8 path.
3598int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003599 std::wstring path_wide;
3600 if (!android::base::UTF8ToWide(path, &path_wide)) {
3601 return -1;
3602 }
3603
Spencer Lowcf4ff642015-05-11 01:08:48 -07003604 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3605 "utimbuf and _utimbuf should be the same size because they both "
3606 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08003607 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003608}
3609
3610// Version of chmod() that takes a UTF-8 path.
3611int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003612 std::wstring path_wide;
3613 if (!android::base::UTF8ToWide(path, &path_wide)) {
3614 return -1;
3615 }
3616
3617 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003618}
3619
Spencer Lowcf4ff642015-05-11 01:08:48 -07003620// Internal helper function to write UTF-8 bytes to a console. Returns -1
3621// on error.
3622static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3623 HANDLE console) {
Elliott Hughesc1fd4922015-11-11 18:02:29 +00003624 std::wstring output;
3625
3626 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors.
3627 // Data might not be UTF-8 if the user cat's random data, runs dmesg, etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07003628 // This could throw std::bad_alloc.
Elliott Hughesc1fd4922015-11-11 18:02:29 +00003629 (void)android::base::UTF8ToWide(buf, size, &output);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003630
3631 // Note that this does not do \n => \r\n translation because that
3632 // doesn't seem necessary for the Windows console. For the Windows
3633 // console \r moves to the beginning of the line and \n moves to a new
3634 // line.
3635
3636 // Flush any stream buffering so that our output is afterwards which
3637 // makes sense because our call is afterwards.
3638 (void)fflush(stream);
3639
3640 // Write UTF-16 to the console.
3641 DWORD written = 0;
3642 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3643 NULL)) {
3644 errno = EIO;
3645 return -1;
3646 }
3647
3648 // This is the number of UTF-16 chars written, which might be different
3649 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3650 // get this count correct.
3651 return written;
3652}
3653
3654// Function prototype because attributes cannot be placed on func definitions.
3655static int _console_vfprintf(const HANDLE console, FILE* stream,
3656 const char *format, va_list ap)
3657 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3658
3659// Internal function to format a UTF-8 string and write it to a Win32 console.
3660// Returns -1 on error.
3661static int _console_vfprintf(const HANDLE console, FILE* stream,
3662 const char *format, va_list ap) {
3663 std::string output_utf8;
3664
3665 // Format the string.
3666 // This could throw std::bad_alloc.
3667 android::base::StringAppendV(&output_utf8, format, ap);
3668
3669 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3670 stream, console);
3671}
3672
3673// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3674// Windows console.
3675int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3676 const HANDLE console = _get_console_handle(stream);
3677
3678 // If there is an associated Win32 console, write to it specially,
3679 // otherwise defer to the regular C Runtime, passing it UTF-8.
3680 if (console != NULL) {
3681 return _console_vfprintf(console, stream, format, ap);
3682 } else {
3683 // If vfprintf is a macro, undefine it, so we can call the real
3684 // C Runtime API.
3685#pragma push_macro("vfprintf")
3686#undef vfprintf
3687 return vfprintf(stream, format, ap);
3688#pragma pop_macro("vfprintf")
3689 }
3690}
3691
3692// Version of fprintf() that takes UTF-8 and can write Unicode to a
3693// Windows console.
3694int adb_fprintf(FILE *stream, const char *format, ...) {
3695 va_list ap;
3696 va_start(ap, format);
3697 const int result = adb_vfprintf(stream, format, ap);
3698 va_end(ap);
3699
3700 return result;
3701}
3702
3703// Version of printf() that takes UTF-8 and can write Unicode to a
3704// Windows console.
3705int adb_printf(const char *format, ...) {
3706 va_list ap;
3707 va_start(ap, format);
3708 const int result = adb_vfprintf(stdout, format, ap);
3709 va_end(ap);
3710
3711 return result;
3712}
3713
3714// Version of fputs() that takes UTF-8 and can write Unicode to a
3715// Windows console.
3716int adb_fputs(const char* buf, FILE* stream) {
3717 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3718 // which fputs (and hence adb_fputs) should return on error.
3719 return adb_fprintf(stream, "%s", buf);
3720}
3721
3722// Version of fputc() that takes UTF-8 and can write Unicode to a
3723// Windows console.
3724int adb_fputc(int ch, FILE* stream) {
3725 const int result = adb_fprintf(stream, "%c", ch);
3726 if (result <= 0) {
3727 // If there was an error, or if nothing was printed (which should be an
3728 // error), return an error, which fprintf signifies with EOF.
3729 return EOF;
3730 }
3731 // For success, fputc returns the char, cast to unsigned char, then to int.
3732 return static_cast<unsigned char>(ch);
3733}
3734
3735// Internal function to write UTF-8 to a Win32 console. Returns the number of
3736// items (of length size) written. On error, returns a short item count or 0.
3737static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3738 FILE* stream, HANDLE console) {
3739 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3740 // if we're passed only some of the bytes of a character (for example, from
3741 // the network socket for adb shell), we won't be able to convert the char
3742 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3743 // right.
3744 //
3745 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3746 //
3747 // For now we ignore this problem because the alternative is that we'd have
3748 // to parse UTF-8 and buffer things up (doable). At least this is better
3749 // than what we had before -- always incorrect multi-byte UTF-8 output.
3750 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3751 size * nmemb, stream, console);
3752 if (result == -1) {
3753 return 0;
3754 }
3755 return result / size;
3756}
3757
3758// Version of fwrite() that takes UTF-8 and can write Unicode to a
3759// Windows console.
3760size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3761 const HANDLE console = _get_console_handle(stream);
3762
3763 // If there is an associated Win32 console, write to it specially,
3764 // otherwise defer to the regular C Runtime, passing it UTF-8.
3765 if (console != NULL) {
3766 return _console_fwrite(ptr, size, nmemb, stream, console);
3767 } else {
3768 // If fwrite is a macro, undefine it, so we can call the real
3769 // C Runtime API.
3770#pragma push_macro("fwrite")
3771#undef fwrite
3772 return fwrite(ptr, size, nmemb, stream);
3773#pragma pop_macro("fwrite")
3774 }
3775}
3776
3777// Version of fopen() that takes a UTF-8 filename and can access a file with
3778// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08003779FILE* adb_fopen(const char* path, const char* mode) {
3780 std::wstring path_wide;
3781 if (!android::base::UTF8ToWide(path, &path_wide)) {
3782 return nullptr;
3783 }
3784
3785 std::wstring mode_wide;
3786 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
3787 return nullptr;
3788 }
3789
3790 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003791}
3792
Spencer Lowe6ae5732015-09-08 17:13:04 -07003793// Return a lowercase version of the argument. Uses C Runtime tolower() on
3794// each byte which is not UTF-8 aware, and theoretically uses the current C
3795// Runtime locale (which in practice is not changed, so this becomes a ASCII
3796// conversion).
3797static std::string ToLower(const std::string& anycase) {
3798 // copy string
3799 std::string str(anycase);
3800 // transform the copy
3801 std::transform(str.begin(), str.end(), str.begin(), tolower);
3802 return str;
3803}
3804
3805extern "C" int main(int argc, char** argv);
3806
3807// Link with -municode to cause this wmain() to be used as the program
3808// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3809// regular main() with UTF-8 args.
3810extern "C" int wmain(int argc, wchar_t **argv) {
3811 // Convert args from UTF-16 to UTF-8 and pass that to main().
3812 NarrowArgs narrow_args(argc, argv);
3813 return main(argc, narrow_args.data());
3814}
3815
Spencer Lowcf4ff642015-05-11 01:08:48 -07003816// Shadow UTF-8 environment variable name/value pairs that are created from
3817// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07003818// currently updated if putenv, setenv, unsetenv are called. Note that no
3819// thread synchronization is done, but we're called early enough in
3820// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08003821static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07003822
3823// Make sure that shadow UTF-8 environment variables are setup.
3824static void _ensure_env_setup() {
3825 // If some name/value pairs exist, then we've already done the setup below.
3826 if (g_environ_utf8.size() != 0) {
3827 return;
3828 }
3829
Spencer Lowe6ae5732015-09-08 17:13:04 -07003830 if (_wenviron == nullptr) {
3831 // If _wenviron is null, then -municode probably wasn't used. That
3832 // linker flag will cause the entry point to setup _wenviron. It will
3833 // also require an implementation of wmain() (which we provide above).
3834 fatal("_wenviron is not set, did you link with -municode?");
3835 }
3836
Spencer Lowcf4ff642015-05-11 01:08:48 -07003837 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3838 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3839 // to use the D() macro here because that tracing only works if the
3840 // ADB_TRACE environment variable is setup, but that env var can't be read
3841 // until this code completes.
3842 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3843 wchar_t* const equal = wcschr(*env, L'=');
3844 if (equal == nullptr) {
3845 // Malformed environment variable with no equal sign. Shouldn't
3846 // really happen, but we should be resilient to this.
3847 continue;
3848 }
3849
Spencer Lowd21dc822015-11-12 15:20:15 -08003850 // If we encounter an error converting UTF-16, don't error-out on account of a single env
3851 // var because the program might never even read this particular variable.
3852 std::string name_utf8;
3853 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
3854 continue;
3855 }
3856
Spencer Lowe6ae5732015-09-08 17:13:04 -07003857 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08003858 name_utf8 = ToLower(name_utf8);
3859
3860 std::string value_utf8;
3861 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
3862 continue;
3863 }
3864
3865 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003866
Spencer Lowe6ae5732015-09-08 17:13:04 -07003867 // Don't overwrite a previus env var with the same name. In reality,
3868 // the system probably won't let two env vars with the same name exist
3869 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08003870 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07003871 }
3872}
3873
3874// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07003875// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07003876char* adb_getenv(const char* name) {
3877 _ensure_env_setup();
3878
Spencer Lowe6ae5732015-09-08 17:13:04 -07003879 // Case-insensitive search by searching for lowercase name in a map of
3880 // lowercase names.
3881 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003882 if (it == g_environ_utf8.end()) {
3883 return nullptr;
3884 }
3885
3886 return it->second;
3887}
3888
3889// Version of getcwd() that returns the current working directory in UTF-8.
3890char* adb_getcwd(char* buf, int size) {
3891 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3892 if (wbuf == nullptr) {
3893 return nullptr;
3894 }
3895
Spencer Lowd21dc822015-11-12 15:20:15 -08003896 std::string buf_utf8;
3897 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003898 free(wbuf);
3899 wbuf = nullptr;
3900
Spencer Lowd21dc822015-11-12 15:20:15 -08003901 if (!narrow_result) {
3902 return nullptr;
3903 }
3904
Spencer Lowcf4ff642015-05-11 01:08:48 -07003905 // If size was specified, make sure all the chars will fit.
3906 if (size != 0) {
3907 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3908 errno = ERANGE;
3909 return nullptr;
3910 }
3911 }
3912
3913 // If buf was not specified, allocate storage.
3914 if (buf == nullptr) {
3915 if (size == 0) {
3916 size = buf_utf8.length() + 1;
3917 }
3918 buf = reinterpret_cast<char*>(malloc(size));
3919 if (buf == nullptr) {
3920 return nullptr;
3921 }
3922 }
3923
3924 // Destination buffer was allocated with enough space, or we've already
3925 // checked an existing buffer size for enough space.
3926 strcpy(buf, buf_utf8.c_str());
3927
3928 return buf;
3929}