blob: 0b0898186fb51e99d9f7e8e0b1f8cff5c736afc8 [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
Spencer Lowa30b79a2015-11-15 16:29:36 -08002454static adb_mutex_t g_console_output_buffer_lock;
2455
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002456void
2457adb_sysdeps_init( void )
2458{
2459#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2460#include "mutex_list.h"
2461 InitializeCriticalSection( &_win32_lock );
Spencer Lowa30b79a2015-11-15 16:29:36 -08002462 InitializeCriticalSection( &g_console_output_buffer_lock );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002463}
2464
Spencer Low50184062015-03-01 15:06:21 -08002465/**************************************************************************/
2466/**************************************************************************/
2467/***** *****/
2468/***** Console Window Terminal Emulation *****/
2469/***** *****/
2470/**************************************************************************/
2471/**************************************************************************/
2472
2473// This reads input from a Win32 console window and translates it into Unix
2474// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2475// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2476// is emulated instead of xterm because it is probably more popular than xterm:
2477// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2478// supports modern fonts, etc. It seems best to emulate the terminal that most
2479// Android developers use because they'll fix apps (the shell, etc.) to keep
2480// working with that terminal's emulation.
2481//
2482// The point of this emulation is not to be perfect or to solve all issues with
2483// console windows on Windows, but to be better than the original code which
2484// just called read() (which called ReadFile(), which called ReadConsoleA())
2485// which did not support Ctrl-C, tab completion, shell input line editing
2486// keys, server echo, and more.
2487//
2488// This implementation reconfigures the console with SetConsoleMode(), then
2489// calls ReadConsoleInput() to get raw input which it remaps to Unix
2490// terminal-style sequences which is returned via unix_read() which is used
2491// by the 'adb shell' command.
2492//
2493// Code organization:
2494//
David Pursellc5b8ad82015-10-28 14:29:51 -07002495// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08002496// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2497// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2498// * _console_read() is the main code of the emulation.
2499
David Pursellc5b8ad82015-10-28 14:29:51 -07002500// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
2501// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
2502// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
2503static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
2504 // First check isatty(); this is very fast and eliminates most non-console
2505 // FDs, but returns 1 for both consoles and character devices like NUL.
2506#pragma push_macro("isatty")
2507#undef isatty
2508 if (!isatty(fd)) {
2509 return nullptr;
2510 }
2511#pragma pop_macro("isatty")
2512
2513 // To differentiate between character devices and consoles we need to get
2514 // the underlying HANDLE and use GetConsoleMode(), which is what requires
2515 // GENERIC_READ permissions.
2516 const intptr_t intptr_handle = _get_osfhandle(fd);
2517 if (intptr_handle == -1) {
2518 return nullptr;
2519 }
2520 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
2521 DWORD temp_mode = 0;
2522 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
2523 return nullptr;
2524 }
2525
2526 return handle;
2527}
2528
2529// Returns a console handle if |stream| is a console, otherwise returns nullptr.
2530static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002531 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
2532 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07002533 const int fd = fileno(stream);
2534 if (fd < 0) {
2535 return nullptr;
2536 }
2537 return _get_console_handle(fd);
2538}
2539
2540int unix_isatty(int fd) {
2541 return _get_console_handle(fd) ? 1 : 0;
2542}
Spencer Low50184062015-03-01 15:06:21 -08002543
Spencer Low32762f42015-11-10 19:17:16 -08002544// Get the next KEY_EVENT_RECORD that should be processed.
2545static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08002546 for (;;) {
2547 DWORD read_count = 0;
2548 memset(input_record, 0, sizeof(*input_record));
2549 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08002550 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08002551 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002552 errno = EIO;
2553 return false;
2554 }
2555
2556 if (read_count == 0) { // should be impossible
2557 fatal("ReadConsoleInputA returned 0");
2558 }
2559
2560 if (read_count != 1) { // should be impossible
2561 fatal("ReadConsoleInputA did not return one input record");
2562 }
2563
Spencer Low2e02dc62015-11-07 17:34:39 -08002564 // If the console window is resized, emulate SIGWINCH by breaking out
2565 // of read() with errno == EINTR. Note that there is no event on
2566 // vertical resize because we don't give the console our own custom
2567 // screen buffer (with CreateConsoleScreenBuffer() +
2568 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
2569 // supports scrollback, but doesn't seem to raise an event for vertical
2570 // window resize.
2571 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
2572 errno = EINTR;
2573 return false;
2574 }
2575
Spencer Low50184062015-03-01 15:06:21 -08002576 if ((input_record->EventType == KEY_EVENT) &&
2577 (input_record->Event.KeyEvent.bKeyDown)) {
2578 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2579 fatal("ReadConsoleInputA returned a key event with zero repeat"
2580 " count");
2581 }
2582
2583 // Got an interesting INPUT_RECORD, so return
2584 return true;
2585 }
2586 }
2587}
2588
Spencer Low50184062015-03-01 15:06:21 -08002589static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2590 return (control_key_state & SHIFT_PRESSED) != 0;
2591}
2592
2593static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2594 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2595}
2596
2597static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2598 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2599}
2600
2601static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2602 return (control_key_state & NUMLOCK_ON) != 0;
2603}
2604
2605static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2606 return (control_key_state & CAPSLOCK_ON) != 0;
2607}
2608
2609static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2610 return (control_key_state & ENHANCED_KEY) != 0;
2611}
2612
2613// Constants from MSDN for ToAscii().
2614static const BYTE TOASCII_KEY_OFF = 0x00;
2615static const BYTE TOASCII_KEY_DOWN = 0x80;
2616static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2617
2618// Given a key event, ignore a modifier key and return the character that was
2619// entered without the modifier. Writes to *ch and returns the number of bytes
2620// written.
2621static size_t _get_char_ignoring_modifier(char* const ch,
2622 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2623 const WORD modifier) {
2624 // If there is no character from Windows, try ignoring the specified
2625 // modifier and look for a character. Note that if AltGr is being used,
2626 // there will be a character from Windows.
2627 if (key_event->uChar.AsciiChar == '\0') {
2628 // Note that we read the control key state from the passed in argument
2629 // instead of from key_event since the argument has been normalized.
2630 if (((modifier == VK_SHIFT) &&
2631 _is_shift_pressed(control_key_state)) ||
2632 ((modifier == VK_CONTROL) &&
2633 _is_ctrl_pressed(control_key_state)) ||
2634 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2635
2636 BYTE key_state[256] = {0};
2637 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2638 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2639 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2640 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2641 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2642 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2643 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2644 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2645
2646 // cause this modifier to be ignored
2647 key_state[modifier] = TOASCII_KEY_OFF;
2648
2649 WORD translated = 0;
2650 if (ToAscii(key_event->wVirtualKeyCode,
2651 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2652 // Ignoring the modifier, we found a character.
2653 *ch = (CHAR)translated;
2654 return 1;
2655 }
2656 }
2657 }
2658
2659 // Just use whatever Windows told us originally.
2660 *ch = key_event->uChar.AsciiChar;
2661
2662 // If the character from Windows is NULL, return a size of zero.
2663 return (*ch == '\0') ? 0 : 1;
2664}
2665
2666// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2667// but taking into account the shift key. This is because for a sequence like
2668// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2669// we want to find the character ')'.
2670//
2671// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2672// because it is the default key-sequence to switch the input language.
2673// This is configurable in the Region and Language control panel.
2674static __inline__ size_t _get_non_control_char(char* const ch,
2675 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2676 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2677 VK_CONTROL);
2678}
2679
2680// Get without Alt.
2681static __inline__ size_t _get_non_alt_char(char* const ch,
2682 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2683 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2684 VK_MENU);
2685}
2686
2687// Ignore the control key, find the character from Windows, and apply any
2688// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2689// *pch and returns number of bytes written.
2690static size_t _get_control_character(char* const pch,
2691 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2692 const size_t len = _get_non_control_char(pch, key_event,
2693 control_key_state);
2694
2695 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2696 char ch = *pch;
2697 switch (ch) {
2698 case '2':
2699 case '@':
2700 case '`':
2701 ch = '\0';
2702 break;
2703 case '3':
2704 case '[':
2705 case '{':
2706 ch = '\x1b';
2707 break;
2708 case '4':
2709 case '\\':
2710 case '|':
2711 ch = '\x1c';
2712 break;
2713 case '5':
2714 case ']':
2715 case '}':
2716 ch = '\x1d';
2717 break;
2718 case '6':
2719 case '^':
2720 case '~':
2721 ch = '\x1e';
2722 break;
2723 case '7':
2724 case '-':
2725 case '_':
2726 ch = '\x1f';
2727 break;
2728 case '8':
2729 ch = '\x7f';
2730 break;
2731 case '/':
2732 if (!_is_alt_pressed(control_key_state)) {
2733 ch = '\x1f';
2734 }
2735 break;
2736 case '?':
2737 if (!_is_alt_pressed(control_key_state)) {
2738 ch = '\x7f';
2739 }
2740 break;
2741 }
2742 *pch = ch;
2743 }
2744
2745 return len;
2746}
2747
2748static DWORD _normalize_altgr_control_key_state(
2749 const KEY_EVENT_RECORD* const key_event) {
2750 DWORD control_key_state = key_event->dwControlKeyState;
2751
2752 // If we're in an AltGr situation where the AltGr key is down (depending on
2753 // the keyboard layout, that might be the physical right alt key which
2754 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2755 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2756 // a character (which indicates that there was an AltGr mapping), then act
2757 // as if alt and control are not really down for the purposes of modifiers.
2758 // This makes it so that if the user with, say, a German keyboard layout
2759 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2760 // output the key and we don't see the Alt and Ctrl keys.
2761 if (_is_ctrl_pressed(control_key_state) &&
2762 _is_alt_pressed(control_key_state)
2763 && (key_event->uChar.AsciiChar != '\0')) {
2764 // Try to remove as few bits as possible to improve our chances of
2765 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2766 // Left-Alt + Right-Ctrl + AltGr.
2767 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2768 // Remove Right-Alt.
2769 control_key_state &= ~RIGHT_ALT_PRESSED;
2770 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2771 // pressed, Left-Ctrl is almost always set, except if the user
2772 // presses Right-Ctrl, then AltGr (in that specific order) for
2773 // whatever reason. At any rate, make sure the bit is not set.
2774 control_key_state &= ~LEFT_CTRL_PRESSED;
2775 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2776 // Remove Left-Alt.
2777 control_key_state &= ~LEFT_ALT_PRESSED;
2778 // Whichever Ctrl key is down, remove it from the state. We only
2779 // remove one key, to improve our chances of detecting the
2780 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2781 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2782 // Remove Left-Ctrl.
2783 control_key_state &= ~LEFT_CTRL_PRESSED;
2784 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2785 // Remove Right-Ctrl.
2786 control_key_state &= ~RIGHT_CTRL_PRESSED;
2787 }
2788 }
2789
2790 // Note that this logic isn't 100% perfect because Windows doesn't
2791 // allow us to detect all combinations because a physical AltGr key
2792 // press shows up as two bits, plus some combinations are ambiguous
2793 // about what is actually physically pressed.
2794 }
2795
2796 return control_key_state;
2797}
2798
2799// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2800// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2801// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2802// appropriately.
2803static DWORD _normalize_keypad_control_key_state(const WORD vk,
2804 const DWORD control_key_state) {
2805 if (!_is_numlock_on(control_key_state)) {
2806 return control_key_state;
2807 }
2808 if (!_is_enhanced_key(control_key_state)) {
2809 switch (vk) {
2810 case VK_INSERT: // 0
2811 case VK_DELETE: // .
2812 case VK_END: // 1
2813 case VK_DOWN: // 2
2814 case VK_NEXT: // 3
2815 case VK_LEFT: // 4
2816 case VK_CLEAR: // 5
2817 case VK_RIGHT: // 6
2818 case VK_HOME: // 7
2819 case VK_UP: // 8
2820 case VK_PRIOR: // 9
2821 return control_key_state | SHIFT_PRESSED;
2822 }
2823 }
2824
2825 return control_key_state;
2826}
2827
2828static const char* _get_keypad_sequence(const DWORD control_key_state,
2829 const char* const normal, const char* const shifted) {
2830 if (_is_shift_pressed(control_key_state)) {
2831 // Shift is pressed and NumLock is off
2832 return shifted;
2833 } else {
2834 // Shift is not pressed and NumLock is off, or,
2835 // Shift is pressed and NumLock is on, in which case we want the
2836 // NumLock and Shift to neutralize each other, thus, we want the normal
2837 // sequence.
2838 return normal;
2839 }
2840 // If Shift is not pressed and NumLock is on, a different virtual key code
2841 // is returned by Windows, which can be taken care of by a different case
2842 // statement in _console_read().
2843}
2844
2845// Write sequence to buf and return the number of bytes written.
2846static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2847 DWORD control_key_state, const char* const normal) {
2848 // Copy the base sequence into buf.
2849 const size_t len = strlen(normal);
2850 memcpy(buf, normal, len);
2851
2852 int code = 0;
2853
2854 control_key_state = _normalize_keypad_control_key_state(vk,
2855 control_key_state);
2856
2857 if (_is_shift_pressed(control_key_state)) {
2858 code |= 0x1;
2859 }
2860 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2861 code |= 0x2;
2862 }
2863 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2864 code |= 0x4;
2865 }
2866 // If some modifier was held down, then we need to insert the modifier code
2867 if (code != 0) {
2868 if (len == 0) {
2869 // Should be impossible because caller should pass a string of
2870 // non-zero length.
2871 return 0;
2872 }
2873 size_t index = len - 1;
2874 const char lastChar = buf[index];
2875 if (lastChar != '~') {
2876 buf[index++] = '1';
2877 }
2878 buf[index++] = ';'; // modifier separator
2879 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2880 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2881 buf[index++] = '1' + code;
2882 buf[index++] = lastChar; // move ~ (or other last char) to the end
2883 return index;
2884 }
2885 return len;
2886}
2887
2888// Write sequence to buf and return the number of bytes written.
2889static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2890 const DWORD control_key_state, const char* const normal,
2891 const char shifted) {
2892 if (_is_shift_pressed(control_key_state)) {
2893 // Shift is pressed and NumLock is off
2894 if (shifted != '\0') {
2895 buf[0] = shifted;
2896 return sizeof(buf[0]);
2897 } else {
2898 return 0;
2899 }
2900 } else {
2901 // Shift is not pressed and NumLock is off, or,
2902 // Shift is pressed and NumLock is on, in which case we want the
2903 // NumLock and Shift to neutralize each other, thus, we want the normal
2904 // sequence.
2905 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2906 }
2907 // If Shift is not pressed and NumLock is on, a different virtual key code
2908 // is returned by Windows, which can be taken care of by a different case
2909 // statement in _console_read().
2910}
2911
2912// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2913// Standard German. Figure this out at runtime so we know what to output for
2914// Shift-VK_DELETE.
2915static char _get_decimal_char() {
2916 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2917}
2918
2919// Prefix the len bytes in buf with the escape character, and then return the
2920// new buffer length.
2921size_t _escape_prefix(char* const buf, const size_t len) {
2922 // If nothing to prefix, don't do anything. We might be called with
2923 // len == 0, if alt was held down with a dead key which produced nothing.
2924 if (len == 0) {
2925 return 0;
2926 }
2927
2928 memmove(&buf[1], buf, len);
2929 buf[0] = '\x1b';
2930 return len + 1;
2931}
2932
Spencer Low32762f42015-11-10 19:17:16 -08002933// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002934static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08002935
2936// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
2937// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08002938static int _console_read(const HANDLE console, void* buf, size_t len) {
2939 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08002940 // Read of zero bytes should not block waiting for something from the console.
2941 if (len == 0) {
2942 return 0;
2943 }
2944
2945 // Flush as much as possible from input buffer.
2946 if (!g_console_input_buffer.empty()) {
2947 const int bytes_read = std::min(len, g_console_input_buffer.size());
2948 memcpy(buf, g_console_input_buffer.data(), bytes_read);
2949 const auto begin = g_console_input_buffer.begin();
2950 g_console_input_buffer.erase(begin, begin + bytes_read);
2951 return bytes_read;
2952 }
2953
2954 // Read from the actual console. This may block until input.
2955 INPUT_RECORD input_record;
2956 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08002957 return -1;
2958 }
2959
Spencer Low32762f42015-11-10 19:17:16 -08002960 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08002961 const WORD vk = key_event->wVirtualKeyCode;
2962 const CHAR ch = key_event->uChar.AsciiChar;
2963 const DWORD control_key_state = _normalize_altgr_control_key_state(
2964 key_event);
2965
2966 // The following emulation code should write the output sequence to
2967 // either seqstr or to seqbuf and seqbuflen.
2968 const char* seqstr = NULL; // NULL terminated C-string
2969 // Enough space for max sequence string below, plus modifiers and/or
2970 // escape prefix.
2971 char seqbuf[16];
2972 size_t seqbuflen = 0; // Space used in seqbuf.
2973
2974#define MATCH(vk, normal) \
2975 case (vk): \
2976 { \
2977 seqstr = (normal); \
2978 } \
2979 break;
2980
2981 // Modifier keys should affect the output sequence.
2982#define MATCH_MODIFIER(vk, normal) \
2983 case (vk): \
2984 { \
2985 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2986 control_key_state, (normal)); \
2987 } \
2988 break;
2989
2990 // The shift key should affect the output sequence.
2991#define MATCH_KEYPAD(vk, normal, shifted) \
2992 case (vk): \
2993 { \
2994 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2995 (shifted)); \
2996 } \
2997 break;
2998
2999 // The shift key and other modifier keys should affect the output
3000 // sequence.
3001#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
3002 case (vk): \
3003 { \
3004 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
3005 control_key_state, (normal), (shifted)); \
3006 } \
3007 break;
3008
3009#define ESC "\x1b"
3010#define CSI ESC "["
3011#define SS3 ESC "O"
3012
3013 // Only support normal mode, not application mode.
3014
3015 // Enhanced keys:
3016 // * 6-pack: insert, delete, home, end, page up, page down
3017 // * cursor keys: up, down, right, left
3018 // * keypad: divide, enter
3019 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
3020 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
3021 if (_is_enhanced_key(control_key_state)) {
3022 switch (vk) {
3023 case VK_RETURN: // Enter key on keypad
3024 if (_is_ctrl_pressed(control_key_state)) {
3025 seqstr = "\n";
3026 } else {
3027 seqstr = "\r";
3028 }
3029 break;
3030
3031 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
3032 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
3033
3034 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
3035 // will be fixed soon to match xterm which sends CSI "F" and
3036 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
3037 MATCH(VK_END, CSI "F");
3038 MATCH(VK_HOME, CSI "H");
3039
3040 MATCH_MODIFIER(VK_LEFT, CSI "D");
3041 MATCH_MODIFIER(VK_UP, CSI "A");
3042 MATCH_MODIFIER(VK_RIGHT, CSI "C");
3043 MATCH_MODIFIER(VK_DOWN, CSI "B");
3044
3045 MATCH_MODIFIER(VK_INSERT, CSI "2~");
3046 MATCH_MODIFIER(VK_DELETE, CSI "3~");
3047
3048 MATCH(VK_DIVIDE, "/");
3049 }
3050 } else { // Non-enhanced keys:
3051 switch (vk) {
3052 case VK_BACK: // backspace
3053 if (_is_alt_pressed(control_key_state)) {
3054 seqstr = ESC "\x7f";
3055 } else {
3056 seqstr = "\x7f";
3057 }
3058 break;
3059
3060 case VK_TAB:
3061 if (_is_shift_pressed(control_key_state)) {
3062 seqstr = CSI "Z";
3063 } else {
3064 seqstr = "\t";
3065 }
3066 break;
3067
3068 // Number 5 key in keypad when NumLock is off, or if NumLock is
3069 // on and Shift is down.
3070 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
3071
3072 case VK_RETURN: // Enter key on main keyboard
3073 if (_is_alt_pressed(control_key_state)) {
3074 seqstr = ESC "\n";
3075 } else if (_is_ctrl_pressed(control_key_state)) {
3076 seqstr = "\n";
3077 } else {
3078 seqstr = "\r";
3079 }
3080 break;
3081
3082 // VK_ESCAPE: Don't do any special handling. The OS uses many
3083 // of the sequences with Escape and many of the remaining
3084 // sequences don't produce bKeyDown messages, only !bKeyDown
3085 // for whatever reason.
3086
3087 case VK_SPACE:
3088 if (_is_alt_pressed(control_key_state)) {
3089 seqstr = ESC " ";
3090 } else if (_is_ctrl_pressed(control_key_state)) {
3091 seqbuf[0] = '\0'; // NULL char
3092 seqbuflen = 1;
3093 } else {
3094 seqstr = " ";
3095 }
3096 break;
3097
3098 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
3099 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
3100
3101 MATCH_KEYPAD(VK_END, CSI "4~", "1");
3102 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
3103
3104 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
3105 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
3106 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
3107 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
3108
3109 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
3110 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
3111 _get_decimal_char());
3112
3113 case 0x30: // 0
3114 case 0x31: // 1
3115 case 0x39: // 9
3116 case VK_OEM_1: // ;:
3117 case VK_OEM_PLUS: // =+
3118 case VK_OEM_COMMA: // ,<
3119 case VK_OEM_PERIOD: // .>
3120 case VK_OEM_7: // '"
3121 case VK_OEM_102: // depends on keyboard, could be <> or \|
3122 case VK_OEM_2: // /?
3123 case VK_OEM_3: // `~
3124 case VK_OEM_4: // [{
3125 case VK_OEM_5: // \|
3126 case VK_OEM_6: // ]}
3127 {
3128 seqbuflen = _get_control_character(seqbuf, key_event,
3129 control_key_state);
3130
3131 if (_is_alt_pressed(control_key_state)) {
3132 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3133 }
3134 }
3135 break;
3136
3137 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08003138 case 0x33: // 3
3139 case 0x34: // 4
3140 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08003141 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08003142 case 0x37: // 7
3143 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08003144 case VK_OEM_MINUS: // -_
3145 {
3146 seqbuflen = _get_control_character(seqbuf, key_event,
3147 control_key_state);
3148
3149 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3150 // prefix with escape.
3151 if (_is_alt_pressed(control_key_state) &&
3152 !(_is_ctrl_pressed(control_key_state) &&
3153 !_is_shift_pressed(control_key_state))) {
3154 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3155 }
3156 }
3157 break;
3158
Spencer Low50184062015-03-01 15:06:21 -08003159 case 0x41: // a
3160 case 0x42: // b
3161 case 0x43: // c
3162 case 0x44: // d
3163 case 0x45: // e
3164 case 0x46: // f
3165 case 0x47: // g
3166 case 0x48: // h
3167 case 0x49: // i
3168 case 0x4a: // j
3169 case 0x4b: // k
3170 case 0x4c: // l
3171 case 0x4d: // m
3172 case 0x4e: // n
3173 case 0x4f: // o
3174 case 0x50: // p
3175 case 0x51: // q
3176 case 0x52: // r
3177 case 0x53: // s
3178 case 0x54: // t
3179 case 0x55: // u
3180 case 0x56: // v
3181 case 0x57: // w
3182 case 0x58: // x
3183 case 0x59: // y
3184 case 0x5a: // z
3185 {
3186 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3187 control_key_state);
3188
3189 // If Alt is pressed, then prefix with escape.
3190 if (_is_alt_pressed(control_key_state)) {
3191 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3192 }
3193 }
3194 break;
3195
3196 // These virtual key codes are generated by the keys on the
3197 // keypad *when NumLock is on* and *Shift is up*.
3198 MATCH(VK_NUMPAD0, "0");
3199 MATCH(VK_NUMPAD1, "1");
3200 MATCH(VK_NUMPAD2, "2");
3201 MATCH(VK_NUMPAD3, "3");
3202 MATCH(VK_NUMPAD4, "4");
3203 MATCH(VK_NUMPAD5, "5");
3204 MATCH(VK_NUMPAD6, "6");
3205 MATCH(VK_NUMPAD7, "7");
3206 MATCH(VK_NUMPAD8, "8");
3207 MATCH(VK_NUMPAD9, "9");
3208
3209 MATCH(VK_MULTIPLY, "*");
3210 MATCH(VK_ADD, "+");
3211 MATCH(VK_SUBTRACT, "-");
3212 // VK_DECIMAL is generated by the . key on the keypad *when
3213 // NumLock is on* and *Shift is up* and the sequence is not
3214 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3215 // Windows Security screen to come up).
3216 case VK_DECIMAL:
3217 // U.S. English uses '.', Germany German uses ','.
3218 seqbuflen = _get_non_control_char(seqbuf, key_event,
3219 control_key_state);
3220 break;
3221
3222 MATCH_MODIFIER(VK_F1, SS3 "P");
3223 MATCH_MODIFIER(VK_F2, SS3 "Q");
3224 MATCH_MODIFIER(VK_F3, SS3 "R");
3225 MATCH_MODIFIER(VK_F4, SS3 "S");
3226 MATCH_MODIFIER(VK_F5, CSI "15~");
3227 MATCH_MODIFIER(VK_F6, CSI "17~");
3228 MATCH_MODIFIER(VK_F7, CSI "18~");
3229 MATCH_MODIFIER(VK_F8, CSI "19~");
3230 MATCH_MODIFIER(VK_F9, CSI "20~");
3231 MATCH_MODIFIER(VK_F10, CSI "21~");
3232 MATCH_MODIFIER(VK_F11, CSI "23~");
3233 MATCH_MODIFIER(VK_F12, CSI "24~");
3234
3235 MATCH_MODIFIER(VK_F13, CSI "25~");
3236 MATCH_MODIFIER(VK_F14, CSI "26~");
3237 MATCH_MODIFIER(VK_F15, CSI "28~");
3238 MATCH_MODIFIER(VK_F16, CSI "29~");
3239 MATCH_MODIFIER(VK_F17, CSI "31~");
3240 MATCH_MODIFIER(VK_F18, CSI "32~");
3241 MATCH_MODIFIER(VK_F19, CSI "33~");
3242 MATCH_MODIFIER(VK_F20, CSI "34~");
3243
3244 // MATCH_MODIFIER(VK_F21, ???);
3245 // MATCH_MODIFIER(VK_F22, ???);
3246 // MATCH_MODIFIER(VK_F23, ???);
3247 // MATCH_MODIFIER(VK_F24, ???);
3248 }
3249 }
3250
3251#undef MATCH
3252#undef MATCH_MODIFIER
3253#undef MATCH_KEYPAD
3254#undef MATCH_MODIFIER_KEYPAD
3255#undef ESC
3256#undef CSI
3257#undef SS3
3258
3259 const char* out;
3260 size_t outlen;
3261
3262 // Check for output in any of:
3263 // * seqstr is set (and strlen can be used to determine the length).
3264 // * seqbuf and seqbuflen are set
3265 // Fallback to ch from Windows.
3266 if (seqstr != NULL) {
3267 out = seqstr;
3268 outlen = strlen(seqstr);
3269 } else if (seqbuflen > 0) {
3270 out = seqbuf;
3271 outlen = seqbuflen;
3272 } else if (ch != '\0') {
3273 // Use whatever Windows told us it is.
3274 seqbuf[0] = ch;
3275 seqbuflen = 1;
3276 out = seqbuf;
3277 outlen = seqbuflen;
3278 } else {
3279 // No special handling for the virtual key code and Windows isn't
3280 // telling us a character code, then we don't know how to translate
3281 // the key press.
3282 //
3283 // Consume the input and 'continue' to cause us to get a new key
3284 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07003285 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08003286 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08003287 continue;
3288 }
3289
Spencer Low32762f42015-11-10 19:17:16 -08003290 // put output wRepeatCount times into g_console_input_buffer
3291 while (key_event->wRepeatCount-- > 0) {
3292 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08003293 }
3294
Spencer Low32762f42015-11-10 19:17:16 -08003295 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08003296 }
3297}
3298
3299static DWORD _old_console_mode; // previous GetConsoleMode() result
3300static HANDLE _console_handle; // when set, console mode should be restored
3301
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003302void stdin_raw_init() {
3303 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08003304 if (in == nullptr) {
3305 return;
3306 }
Spencer Low50184062015-03-01 15:06:21 -08003307
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003308 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3309 // calling the process Ctrl-C routine (configured by
3310 // SetConsoleCtrlHandler()).
3311 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3312 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3313 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08003314 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3315 ENABLE_LINE_INPUT |
3316 ENABLE_ECHO_INPUT);
3317 // Enable ENABLE_WINDOW_INPUT to get window resizes.
3318 new_console_mode |= ENABLE_WINDOW_INPUT;
3319
3320 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003321 // This really should not fail.
3322 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08003323 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08003324 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003325
3326 // Once this is set, it means that stdin has been configured for
3327 // reading from and that the old console mode should be restored later.
3328 _console_handle = in;
3329
3330 // Note that we don't need to configure C Runtime line-ending
3331 // translation because _console_read() does not call the C Runtime to
3332 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08003333}
3334
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003335void stdin_raw_restore() {
3336 if (_console_handle != NULL) {
3337 const HANDLE in = _console_handle;
3338 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08003339
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003340 if (!SetConsoleMode(in, _old_console_mode)) {
3341 // This really should not fail.
3342 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08003343 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08003344 }
3345 }
3346}
3347
Spencer Low2e02dc62015-11-07 17:34:39 -08003348// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
3349int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08003350 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3351 // If it is a request to read from stdin, and stdin_raw_init() has been
3352 // called, and it successfully configured the console, then read from
3353 // the console using Win32 console APIs and partially emulate a unix
3354 // terminal.
3355 return _console_read(_console_handle, buf, len);
3356 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07003357 // On older versions of Windows (definitely 7, definitely not 10),
3358 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07003359 // we need to limit the read size.
3360 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07003361 len = 4096;
3362 }
Spencer Low50184062015-03-01 15:06:21 -08003363 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003364 // can do LF/CR translation (which is overridable with _setmode()).
3365 // Undefine the macro that is set in sysdeps.h which bans calls to
3366 // plain read() in favor of unix_read() or adb_read().
3367#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003368#undef read
3369 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003370#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003371 }
3372}
Spencer Lowcf4ff642015-05-11 01:08:48 -07003373
3374/**************************************************************************/
3375/**************************************************************************/
3376/***** *****/
3377/***** Unicode support *****/
3378/***** *****/
3379/**************************************************************************/
3380/**************************************************************************/
3381
3382// This implements support for using files with Unicode filenames and for
3383// outputting Unicode text to a Win32 console window. This is inspired from
3384// http://utf8everywhere.org/.
3385//
3386// Background
3387// ----------
3388//
3389// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3390// filenames to APIs such as open(). This works because filenames are largely
3391// opaque 'cookies' (perhaps excluding path separators).
3392//
3393// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3394// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3395// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3396// CreateFile() API is really just a macro that adds the W/A based on whether
3397// the UNICODE preprocessor symbol is defined).
3398//
3399// Options
3400// -------
3401//
3402// Thus, to write a portable program, there are a few options:
3403//
3404// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3405// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3406// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3407// open() API.
3408//
3409// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3410// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3411// potentially touching a lot of code.
3412//
3413// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3414// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3415// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3416// or C Runtime API.
3417//
3418// The Choice
3419// ----------
3420//
Spencer Lowd21dc822015-11-12 15:20:15 -08003421// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
3422// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07003423// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08003424// args that are passed to main() at the beginning of program startup. We also use
3425// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07003426// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3427//
3428// Unicode console output
3429// ----------------------
3430//
3431// The way to output Unicode to a Win32 console window is to call
3432// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07003433// such as Lucida Console or Consolas, and in the case of East Asian languages
3434// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3435// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3436// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07003437//
3438// The problem is getting the C Runtime to make fprintf and related APIs call
3439// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3440// promising, but the various modes have issues:
3441//
3442// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3443// UTF-16 do not display properly.
3444// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3445// totally wrong.
3446// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3447// handler to be called (upon a later I/O call), aborting the process.
3448// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3449// to output nothing.
3450//
3451// So the only solution is to write our own adb_fprintf() that converts UTF-8
3452// to UTF-16 and then calls WriteConsoleW().
3453
3454
Spencer Lowcf4ff642015-05-11 01:08:48 -07003455// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3456// be passed to main().
3457NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3458 narrow_args = new char*[argc + 1];
3459
3460 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003461 std::string arg_narrow;
3462 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
3463 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
3464 }
3465 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003466 }
3467 narrow_args[argc] = nullptr; // terminate
3468}
3469
3470NarrowArgs::~NarrowArgs() {
3471 if (narrow_args != nullptr) {
3472 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3473 free(*argp);
3474 }
3475 delete[] narrow_args;
3476 narrow_args = nullptr;
3477 }
3478}
3479
3480int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003481 std::wstring path_wide;
3482 if (!android::base::UTF8ToWide(path, &path_wide)) {
3483 return -1;
3484 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003485 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003486 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003487 } else {
3488 int mode;
3489 va_list args;
3490 va_start(args, options);
3491 mode = va_arg(args, int);
3492 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08003493 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003494 }
3495}
3496
3497// Version of stat() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08003498int adb_stat(const char* path, struct adb_stat* s) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07003499#pragma push_macro("wstat")
3500// This definition of wstat seems to be missing from <sys/stat.h>.
3501#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3502#ifdef _USE_32BIT_TIME_T
3503#define wstat _wstat32i64
3504#else
3505#define wstat _wstat64
3506#endif
3507#else
3508// <sys/stat.h> has a function prototype for wstat() that should be available.
3509#endif
3510
Spencer Lowd21dc822015-11-12 15:20:15 -08003511 std::wstring path_wide;
3512 if (!android::base::UTF8ToWide(path, &path_wide)) {
3513 return -1;
3514 }
3515
3516 return wstat(path_wide.c_str(), s);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003517
3518#pragma pop_macro("wstat")
3519}
3520
3521// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08003522DIR* adb_opendir(const char* path) {
3523 std::wstring path_wide;
3524 if (!android::base::UTF8ToWide(path, &path_wide)) {
3525 return nullptr;
3526 }
3527
Spencer Lowcf4ff642015-05-11 01:08:48 -07003528 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3529 // the fields, but right now all the callers treat the structure as
3530 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08003531 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003532}
3533
3534// Version of readdir() that returns UTF-8 paths.
3535struct dirent* adb_readdir(DIR* dir) {
3536 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3537 struct _wdirent* const went = _wreaddir(wdir);
3538 if (went == nullptr) {
3539 return nullptr;
3540 }
Spencer Lowd21dc822015-11-12 15:20:15 -08003541
Spencer Lowcf4ff642015-05-11 01:08:48 -07003542 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08003543 std::string name_utf8;
3544 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
3545 return nullptr;
3546 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003547
3548 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3549 // space for UTF-16 wchar_t's) with UTF-8 char's.
3550 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3551
3552 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3553 // Name too big to fit in existing buffer.
3554 errno = ENOMEM;
3555 return nullptr;
3556 }
3557
3558 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3559 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3560 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3561 // bigger than the caller expects because they expect a dirent structure
3562 // which has a smaller d_name field. Ignore this since the caller should be
3563 // resilient.
3564
3565 // Rewrite the UTF-16 d_name field to UTF-8.
3566 strcpy(ent->d_name, name_utf8.c_str());
3567
3568 return ent;
3569}
3570
3571// Version of closedir() to go with our version of adb_opendir().
3572int adb_closedir(DIR* dir) {
3573 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3574}
3575
3576// Version of unlink() that takes a UTF-8 path.
3577int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003578 std::wstring wpath;
3579 if (!android::base::UTF8ToWide(path, &wpath)) {
3580 return -1;
3581 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003582
3583 int rc = _wunlink(wpath.c_str());
3584
3585 if (rc == -1 && errno == EACCES) {
3586 /* unlink returns EACCES when the file is read-only, so we first */
3587 /* try to make it writable, then unlink again... */
3588 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3589 if (rc == 0)
3590 rc = _wunlink(wpath.c_str());
3591 }
3592 return rc;
3593}
3594
3595// Version of mkdir() that takes a UTF-8 path.
3596int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003597 std::wstring path_wide;
3598 if (!android::base::UTF8ToWide(path, &path_wide)) {
3599 return -1;
3600 }
3601
3602 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003603}
3604
3605// Version of utime() that takes a UTF-8 path.
3606int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003607 std::wstring path_wide;
3608 if (!android::base::UTF8ToWide(path, &path_wide)) {
3609 return -1;
3610 }
3611
Spencer Lowcf4ff642015-05-11 01:08:48 -07003612 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3613 "utimbuf and _utimbuf should be the same size because they both "
3614 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08003615 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003616}
3617
3618// Version of chmod() that takes a UTF-8 path.
3619int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003620 std::wstring path_wide;
3621 if (!android::base::UTF8ToWide(path, &path_wide)) {
3622 return -1;
3623 }
3624
3625 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003626}
3627
Spencer Lowa30b79a2015-11-15 16:29:36 -08003628// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
3629static inline size_t utf8_codepoint_len(uint8_t ch) {
3630 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
3631}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00003632
Spencer Lowa30b79a2015-11-15 16:29:36 -08003633namespace internal {
3634
3635// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
3636// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
3637// remaining_bytes.
3638size_t ParseCompleteUTF8(const char* const first, const char* const last,
3639 std::vector<char>* const remaining_bytes) {
3640 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
3641 // Current_after points one byte past the current byte to be examined.
3642 for (const char* current_after = last; current_after != first; --current_after) {
3643 const char* const current = current_after - 1;
3644 const char ch = *current;
3645 const char kHighBit = 0x80u;
3646 const char kTwoHighestBits = 0xC0u;
3647 if ((ch & kHighBit) == 0) { // high bit not set
3648 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
3649 // bytes with no leading byte, so return the entire buffer.
3650 break;
3651 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
3652 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
3653 const size_t bytes_available = last - current;
3654 if (bytes_available < utf8_codepoint_len(ch)) {
3655 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
3656 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
3657 // to remaining_bytes.
3658 remaining_bytes->insert(remaining_bytes->end(), current, last);
3659 return current - first;
3660 } else {
3661 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
3662 // trailing bytes with no lead byte, so return the entire buffer.
3663 break;
3664 }
3665 } else {
3666 // Trailing byte, so keep going backwards looking for the lead byte.
3667 }
3668 }
3669
3670 // Return the size of the entire buffer. It is possible that we walked backward past invalid
3671 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
3672 // so that they can be processed.
3673 return last - first;
3674}
3675
3676}
3677
3678// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
3679// Note that we use only one buffer even though stderr and stdout are logically separate streams.
3680// This matches the behavior of Linux.
3681// Protected by g_console_output_buffer_lock.
3682static auto& g_console_output_buffer = *new std::vector<char>();
3683
3684// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
3685static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
3686 HANDLE console) {
3687 const int saved_errno = errno;
3688 std::vector<char> combined_buffer;
3689
3690 // Complete UTF-8 sequences that should be immediately written to the console.
3691 const char* utf8;
3692 size_t utf8_size;
3693
3694 adb_mutex_lock(&g_console_output_buffer_lock);
3695 if (g_console_output_buffer.empty()) {
3696 // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
3697 // common case with plain ASCII), parse buf directly.
3698 utf8 = buf;
3699 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
3700 } else {
3701 // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
3702 // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
3703 // combined_buffer, then parse it all together.
3704 combined_buffer.swap(g_console_output_buffer);
3705 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
3706
3707 utf8 = combined_buffer.data();
3708 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
3709 &g_console_output_buffer);
3710 }
3711 adb_mutex_unlock(&g_console_output_buffer_lock);
3712
3713 std::wstring utf16;
3714
3715 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
3716 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
3717 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07003718 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08003719 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003720
3721 // Note that this does not do \n => \r\n translation because that
3722 // doesn't seem necessary for the Windows console. For the Windows
3723 // console \r moves to the beginning of the line and \n moves to a new
3724 // line.
3725
3726 // Flush any stream buffering so that our output is afterwards which
3727 // makes sense because our call is afterwards.
3728 (void)fflush(stream);
3729
3730 // Write UTF-16 to the console.
3731 DWORD written = 0;
Spencer Lowa30b79a2015-11-15 16:29:36 -08003732 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07003733 errno = EIO;
3734 return -1;
3735 }
3736
Spencer Lowa30b79a2015-11-15 16:29:36 -08003737 // Return the size of the original buffer passed in, signifying that we consumed it all, even
3738 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
3739 // matches the Linux behavior.
3740 errno = saved_errno;
3741 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07003742}
3743
3744// Function prototype because attributes cannot be placed on func definitions.
3745static int _console_vfprintf(const HANDLE console, FILE* stream,
3746 const char *format, va_list ap)
3747 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3748
3749// Internal function to format a UTF-8 string and write it to a Win32 console.
3750// Returns -1 on error.
3751static int _console_vfprintf(const HANDLE console, FILE* stream,
3752 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08003753 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07003754 std::string output_utf8;
3755
3756 // Format the string.
3757 // This could throw std::bad_alloc.
3758 android::base::StringAppendV(&output_utf8, format, ap);
3759
Spencer Lowa30b79a2015-11-15 16:29:36 -08003760 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
3761 console);
3762 if (result != -1) {
3763 errno = saved_errno;
3764 } else {
3765 // If -1 was returned, errno has been set.
3766 }
3767 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07003768}
3769
3770// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3771// Windows console.
3772int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3773 const HANDLE console = _get_console_handle(stream);
3774
3775 // If there is an associated Win32 console, write to it specially,
3776 // otherwise defer to the regular C Runtime, passing it UTF-8.
3777 if (console != NULL) {
3778 return _console_vfprintf(console, stream, format, ap);
3779 } else {
3780 // If vfprintf is a macro, undefine it, so we can call the real
3781 // C Runtime API.
3782#pragma push_macro("vfprintf")
3783#undef vfprintf
3784 return vfprintf(stream, format, ap);
3785#pragma pop_macro("vfprintf")
3786 }
3787}
3788
Spencer Lowa30b79a2015-11-15 16:29:36 -08003789// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
3790int adb_vprintf(const char *format, va_list ap) {
3791 return adb_vfprintf(stdout, format, ap);
3792}
3793
Spencer Lowcf4ff642015-05-11 01:08:48 -07003794// Version of fprintf() that takes UTF-8 and can write Unicode to a
3795// Windows console.
3796int adb_fprintf(FILE *stream, const char *format, ...) {
3797 va_list ap;
3798 va_start(ap, format);
3799 const int result = adb_vfprintf(stream, format, ap);
3800 va_end(ap);
3801
3802 return result;
3803}
3804
3805// Version of printf() that takes UTF-8 and can write Unicode to a
3806// Windows console.
3807int adb_printf(const char *format, ...) {
3808 va_list ap;
3809 va_start(ap, format);
3810 const int result = adb_vfprintf(stdout, format, ap);
3811 va_end(ap);
3812
3813 return result;
3814}
3815
3816// Version of fputs() that takes UTF-8 and can write Unicode to a
3817// Windows console.
3818int adb_fputs(const char* buf, FILE* stream) {
3819 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3820 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08003821 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07003822 return adb_fprintf(stream, "%s", buf);
3823}
3824
3825// Version of fputc() that takes UTF-8 and can write Unicode to a
3826// Windows console.
3827int adb_fputc(int ch, FILE* stream) {
3828 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08003829 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07003830 return EOF;
3831 }
3832 // For success, fputc returns the char, cast to unsigned char, then to int.
3833 return static_cast<unsigned char>(ch);
3834}
3835
Spencer Lowa30b79a2015-11-15 16:29:36 -08003836// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
3837int adb_putchar(int ch) {
3838 return adb_fputc(ch, stdout);
3839}
3840
3841// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
3842int adb_puts(const char* buf) {
3843 // adb_printf returns -1 on error, which is conveniently the same as EOF
3844 // which puts (and hence adb_puts) should return on error.
3845 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
3846 return adb_printf("%s\n", buf);
3847}
3848
Spencer Lowcf4ff642015-05-11 01:08:48 -07003849// Internal function to write UTF-8 to a Win32 console. Returns the number of
3850// items (of length size) written. On error, returns a short item count or 0.
3851static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3852 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08003853 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
3854 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003855 if (result == -1) {
3856 return 0;
3857 }
3858 return result / size;
3859}
3860
3861// Version of fwrite() that takes UTF-8 and can write Unicode to a
3862// Windows console.
3863size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3864 const HANDLE console = _get_console_handle(stream);
3865
3866 // If there is an associated Win32 console, write to it specially,
3867 // otherwise defer to the regular C Runtime, passing it UTF-8.
3868 if (console != NULL) {
3869 return _console_fwrite(ptr, size, nmemb, stream, console);
3870 } else {
3871 // If fwrite is a macro, undefine it, so we can call the real
3872 // C Runtime API.
3873#pragma push_macro("fwrite")
3874#undef fwrite
3875 return fwrite(ptr, size, nmemb, stream);
3876#pragma pop_macro("fwrite")
3877 }
3878}
3879
3880// Version of fopen() that takes a UTF-8 filename and can access a file with
3881// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08003882FILE* adb_fopen(const char* path, const char* mode) {
3883 std::wstring path_wide;
3884 if (!android::base::UTF8ToWide(path, &path_wide)) {
3885 return nullptr;
3886 }
3887
3888 std::wstring mode_wide;
3889 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
3890 return nullptr;
3891 }
3892
3893 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003894}
3895
Spencer Lowe6ae5732015-09-08 17:13:04 -07003896// Return a lowercase version of the argument. Uses C Runtime tolower() on
3897// each byte which is not UTF-8 aware, and theoretically uses the current C
3898// Runtime locale (which in practice is not changed, so this becomes a ASCII
3899// conversion).
3900static std::string ToLower(const std::string& anycase) {
3901 // copy string
3902 std::string str(anycase);
3903 // transform the copy
3904 std::transform(str.begin(), str.end(), str.begin(), tolower);
3905 return str;
3906}
3907
3908extern "C" int main(int argc, char** argv);
3909
3910// Link with -municode to cause this wmain() to be used as the program
3911// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3912// regular main() with UTF-8 args.
3913extern "C" int wmain(int argc, wchar_t **argv) {
3914 // Convert args from UTF-16 to UTF-8 and pass that to main().
3915 NarrowArgs narrow_args(argc, argv);
3916 return main(argc, narrow_args.data());
3917}
3918
Spencer Lowcf4ff642015-05-11 01:08:48 -07003919// Shadow UTF-8 environment variable name/value pairs that are created from
3920// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07003921// currently updated if putenv, setenv, unsetenv are called. Note that no
3922// thread synchronization is done, but we're called early enough in
3923// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08003924static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07003925
3926// Make sure that shadow UTF-8 environment variables are setup.
3927static void _ensure_env_setup() {
3928 // If some name/value pairs exist, then we've already done the setup below.
3929 if (g_environ_utf8.size() != 0) {
3930 return;
3931 }
3932
Spencer Lowe6ae5732015-09-08 17:13:04 -07003933 if (_wenviron == nullptr) {
3934 // If _wenviron is null, then -municode probably wasn't used. That
3935 // linker flag will cause the entry point to setup _wenviron. It will
3936 // also require an implementation of wmain() (which we provide above).
3937 fatal("_wenviron is not set, did you link with -municode?");
3938 }
3939
Spencer Lowcf4ff642015-05-11 01:08:48 -07003940 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3941 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3942 // to use the D() macro here because that tracing only works if the
3943 // ADB_TRACE environment variable is setup, but that env var can't be read
3944 // until this code completes.
3945 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3946 wchar_t* const equal = wcschr(*env, L'=');
3947 if (equal == nullptr) {
3948 // Malformed environment variable with no equal sign. Shouldn't
3949 // really happen, but we should be resilient to this.
3950 continue;
3951 }
3952
Spencer Lowd21dc822015-11-12 15:20:15 -08003953 // If we encounter an error converting UTF-16, don't error-out on account of a single env
3954 // var because the program might never even read this particular variable.
3955 std::string name_utf8;
3956 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
3957 continue;
3958 }
3959
Spencer Lowe6ae5732015-09-08 17:13:04 -07003960 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08003961 name_utf8 = ToLower(name_utf8);
3962
3963 std::string value_utf8;
3964 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
3965 continue;
3966 }
3967
3968 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003969
Spencer Lowe6ae5732015-09-08 17:13:04 -07003970 // Don't overwrite a previus env var with the same name. In reality,
3971 // the system probably won't let two env vars with the same name exist
3972 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08003973 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07003974 }
3975}
3976
3977// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07003978// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07003979char* adb_getenv(const char* name) {
3980 _ensure_env_setup();
3981
Spencer Lowe6ae5732015-09-08 17:13:04 -07003982 // Case-insensitive search by searching for lowercase name in a map of
3983 // lowercase names.
3984 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003985 if (it == g_environ_utf8.end()) {
3986 return nullptr;
3987 }
3988
3989 return it->second;
3990}
3991
3992// Version of getcwd() that returns the current working directory in UTF-8.
3993char* adb_getcwd(char* buf, int size) {
3994 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3995 if (wbuf == nullptr) {
3996 return nullptr;
3997 }
3998
Spencer Lowd21dc822015-11-12 15:20:15 -08003999 std::string buf_utf8;
4000 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07004001 free(wbuf);
4002 wbuf = nullptr;
4003
Spencer Lowd21dc822015-11-12 15:20:15 -08004004 if (!narrow_result) {
4005 return nullptr;
4006 }
4007
Spencer Lowcf4ff642015-05-11 01:08:48 -07004008 // If size was specified, make sure all the chars will fit.
4009 if (size != 0) {
4010 if (size < static_cast<int>(buf_utf8.length() + 1)) {
4011 errno = ERANGE;
4012 return nullptr;
4013 }
4014 }
4015
4016 // If buf was not specified, allocate storage.
4017 if (buf == nullptr) {
4018 if (size == 0) {
4019 size = buf_utf8.length() + 1;
4020 }
4021 buf = reinterpret_cast<char*>(malloc(size));
4022 if (buf == nullptr) {
4023 return nullptr;
4024 }
4025 }
4026
4027 // Destination buffer was allocated with enough space, or we've already
4028 // checked an existing buffer size for enough space.
4029 strcpy(buf, buf_utf8.c_str());
4030
4031 return buf;
4032}