blob: 0dbfb984765fadab1757504ab830490a86066488 [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albertdb6fe642015-03-19 15:21:08 -070018
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
Spencer Low50740f52015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low753d4852015-07-30 23:07:55 -070029#include <memory>
30#include <string>
Spencer Low6815c072015-05-11 01:08:48 -070031#include <unordered_map>
Josh Gaoe7388122016-02-16 17:34:53 -080032#include <vector>
Spencer Low753d4852015-07-30 23:07:55 -070033
Elliott Hughesfe447512015-07-24 11:35:40 -070034#include <cutils/sockets.h>
35
David Pursellc573d522016-01-27 08:52:53 -080036#include <android-base/errors.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080037#include <android-base/logging.h>
38#include <android-base/stringprintf.h>
39#include <android-base/strings.h>
40#include <android-base/utf8.h>
Spencer Low753d4852015-07-30 23:07:55 -070041
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080042#include "adb.h"
Josh Gaoe7388122016-02-16 17:34:53 -080043#include "adb_utils.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080044
45extern void fatal(const char *fmt, ...);
46
Elliott Hughes6a096932015-04-16 16:47:02 -070047/* forward declarations */
48
49typedef const struct FHClassRec_* FHClass;
50typedef struct FHRec_* FH;
51typedef struct EventHookRec_* EventHook;
52
53typedef struct FHClassRec_ {
54 void (*_fh_init)(FH);
55 int (*_fh_close)(FH);
56 int (*_fh_lseek)(FH, int, int);
57 int (*_fh_read)(FH, void*, int);
58 int (*_fh_write)(FH, const void*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070059} FHClassRec;
60
61static void _fh_file_init(FH);
62static int _fh_file_close(FH);
63static int _fh_file_lseek(FH, int, int);
64static int _fh_file_read(FH, void*, int);
65static int _fh_file_write(FH, const void*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070066
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,
Elliott Hughes6a096932015-04-16 16:47:02 -070073};
74
75static void _fh_socket_init(FH);
76static int _fh_socket_close(FH);
77static int _fh_socket_lseek(FH, int, int);
78static int _fh_socket_read(FH, void*, int);
79static int _fh_socket_write(FH, const void*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070080
81static const FHClassRec _fh_socket_class = {
82 _fh_socket_init,
83 _fh_socket_close,
84 _fh_socket_lseek,
85 _fh_socket_read,
86 _fh_socket_write,
Elliott Hughes6a096932015-04-16 16:47:02 -070087};
88
Josh Gao2930cdc2016-01-15 15:17:37 -080089#define assert(cond) \
90 do { \
91 if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \
92 } while (0)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080093
Spencer Low2bbb3a92015-08-26 18:46:09 -070094void handle_deleter::operator()(HANDLE h) {
95 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
96 // implying that NULL is a valid handle, but this is probably impossible.
97 // Other APIs like CreateEvent() are documented to return NULL on error,
98 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
99 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
100 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
101 // only need to check for INVALID_HANDLE_VALUE.
102 if (h != INVALID_HANDLE_VALUE) {
103 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700104 D("CloseHandle(%p) failed: %s", h,
David Pursellc573d522016-01-27 08:52:53 -0800105 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2bbb3a92015-08-26 18:46:09 -0700106 }
107 }
108}
109
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800110/**************************************************************************/
111/**************************************************************************/
112/***** *****/
113/***** replaces libs/cutils/load_file.c *****/
114/***** *****/
115/**************************************************************************/
116/**************************************************************************/
117
118void *load_file(const char *fn, unsigned *_sz)
119{
120 HANDLE file;
121 char *data;
122 DWORD file_size;
123
Spencer Low50f5bf12015-11-12 15:20:15 -0800124 std::wstring fn_wide;
125 if (!android::base::UTF8ToWide(fn, &fn_wide))
126 return NULL;
127
128 file = CreateFileW( fn_wide.c_str(),
Spencer Low6815c072015-05-11 01:08:48 -0700129 GENERIC_READ,
130 FILE_SHARE_READ,
131 NULL,
132 OPEN_EXISTING,
133 0,
134 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800135
136 if (file == INVALID_HANDLE_VALUE)
137 return NULL;
138
139 file_size = GetFileSize( file, NULL );
140 data = NULL;
141
142 if (file_size > 0) {
143 data = (char*) malloc( file_size + 1 );
144 if (data == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -0700145 D("load_file: could not allocate %ld bytes", file_size );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800146 file_size = 0;
147 } else {
148 DWORD out_bytes;
149
150 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
151 out_bytes != file_size )
152 {
Yabin Cui815ad882015-09-02 17:44:28 -0700153 D("load_file: could not read %ld bytes from '%s'", file_size, fn);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800154 free(data);
155 data = NULL;
156 file_size = 0;
157 }
158 }
159 }
160 CloseHandle( file );
161
162 *_sz = (unsigned) file_size;
163 return data;
164}
165
166/**************************************************************************/
167/**************************************************************************/
168/***** *****/
169/***** common file descriptor handling *****/
170/***** *****/
171/**************************************************************************/
172/**************************************************************************/
173
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800174typedef struct FHRec_
175{
176 FHClass clazz;
177 int used;
178 int eof;
179 union {
180 HANDLE handle;
181 SOCKET socket;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800182 } u;
183
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800184 int mask;
185
186 char name[32];
187
188} FHRec;
189
190#define fh_handle u.handle
191#define fh_socket u.socket
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800192
193#define WIN32_FH_BASE 100
194
195#define WIN32_MAX_FHS 128
196
197static adb_mutex_t _win32_lock;
198static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700199static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800200
201static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700202_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800203{
204 FH f;
205
206 fd -= WIN32_FH_BASE;
207
Spencer Lowb732a372015-07-24 15:38:19 -0700208 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui815ad882015-09-02 17:44:28 -0700209 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700210 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800211 errno = EBADF;
212 return NULL;
213 }
214
215 f = &_win32_fhs[fd];
216
217 if (f->used == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700218 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700219 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800220 errno = EBADF;
221 return NULL;
222 }
223
224 return f;
225}
226
227
228static int
229_fh_to_int( FH f )
230{
231 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
232 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
233
234 return -1;
235}
236
237static FH
238_fh_alloc( FHClass clazz )
239{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800240 FH f = NULL;
241
242 adb_mutex_lock( &_win32_lock );
243
Spencer Lowb732a372015-07-24 15:38:19 -0700244 // Search entire array, starting from _win32_fh_next.
245 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
246 // Keep incrementing _win32_fh_next to avoid giving out an index that
247 // was recently closed, to try to avoid use-after-free.
248 const int index = _win32_fh_next++;
249 // Handle wrap-around of _win32_fh_next.
250 if (_win32_fh_next == WIN32_MAX_FHS) {
251 _win32_fh_next = 0;
252 }
253 if (_win32_fhs[index].clazz == NULL) {
254 f = &_win32_fhs[index];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800255 goto Exit;
256 }
257 }
Yabin Cui815ad882015-09-02 17:44:28 -0700258 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowb732a372015-07-24 15:38:19 -0700259 errno = EMFILE; // Too many open files
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800260Exit:
261 if (f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700262 f->clazz = clazz;
263 f->used = 1;
264 f->eof = 0;
265 f->name[0] = '\0';
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800266 clazz->_fh_init(f);
267 }
268 adb_mutex_unlock( &_win32_lock );
269 return f;
270}
271
272
273static int
274_fh_close( FH f )
275{
Spencer Lowb732a372015-07-24 15:38:19 -0700276 // Use lock so that closing only happens once and so that _fh_alloc can't
277 // allocate a FH that we're in the middle of closing.
278 adb_mutex_lock(&_win32_lock);
279 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800280 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700281 f->name[0] = '\0';
282 f->eof = 0;
283 f->used = 0;
284 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800285 }
Spencer Lowb732a372015-07-24 15:38:19 -0700286 adb_mutex_unlock(&_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800287 return 0;
288}
289
Spencer Low753d4852015-07-30 23:07:55 -0700290// Deleter for unique_fh.
291class fh_deleter {
292 public:
293 void operator()(struct FHRec_* fh) {
294 // We're called from a destructor and destructors should not overwrite
295 // errno because callers may do:
296 // errno = EBLAH;
297 // return -1; // calls destructor, which should not overwrite errno
298 const int saved_errno = errno;
299 _fh_close(fh);
300 errno = saved_errno;
301 }
302};
303
304// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
305typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
306
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800307/**************************************************************************/
308/**************************************************************************/
309/***** *****/
310/***** file-based descriptor handling *****/
311/***** *****/
312/**************************************************************************/
313/**************************************************************************/
314
Elliott Hughes6a096932015-04-16 16:47:02 -0700315static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800316 f->fh_handle = INVALID_HANDLE_VALUE;
317}
318
Elliott Hughes6a096932015-04-16 16:47:02 -0700319static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800320 CloseHandle( f->fh_handle );
321 f->fh_handle = INVALID_HANDLE_VALUE;
322 return 0;
323}
324
Elliott Hughes6a096932015-04-16 16:47:02 -0700325static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800326 DWORD read_bytes;
327
328 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700329 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800330 errno = EIO;
331 return -1;
332 } else if (read_bytes < (DWORD)len) {
333 f->eof = 1;
334 }
335 return (int)read_bytes;
336}
337
Elliott Hughes6a096932015-04-16 16:47:02 -0700338static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800339 DWORD wrote_bytes;
340
341 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700342 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800343 errno = EIO;
344 return -1;
345 } else if (wrote_bytes < (DWORD)len) {
346 f->eof = 1;
347 }
348 return (int)wrote_bytes;
349}
350
Elliott Hughes6a096932015-04-16 16:47:02 -0700351static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800352 DWORD method;
353 DWORD result;
354
355 switch (origin)
356 {
357 case SEEK_SET: method = FILE_BEGIN; break;
358 case SEEK_CUR: method = FILE_CURRENT; break;
359 case SEEK_END: method = FILE_END; break;
360 default:
361 errno = EINVAL;
362 return -1;
363 }
364
365 result = SetFilePointer( f->fh_handle, pos, NULL, method );
366 if (result == INVALID_SET_FILE_POINTER) {
367 errno = EIO;
368 return -1;
369 } else {
370 f->eof = 0;
371 }
372 return (int)result;
373}
374
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800375
376/**************************************************************************/
377/**************************************************************************/
378/***** *****/
379/***** file-based descriptor handling *****/
380/***** *****/
381/**************************************************************************/
382/**************************************************************************/
383
384int adb_open(const char* path, int options)
385{
386 FH f;
387
388 DWORD desiredAccess = 0;
389 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
390
391 switch (options) {
392 case O_RDONLY:
393 desiredAccess = GENERIC_READ;
394 break;
395 case O_WRONLY:
396 desiredAccess = GENERIC_WRITE;
397 break;
398 case O_RDWR:
399 desiredAccess = GENERIC_READ | GENERIC_WRITE;
400 break;
401 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700402 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800403 errno = EINVAL;
404 return -1;
405 }
406
407 f = _fh_alloc( &_fh_file_class );
408 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800409 return -1;
410 }
411
Spencer Low50f5bf12015-11-12 15:20:15 -0800412 std::wstring path_wide;
413 if (!android::base::UTF8ToWide(path, &path_wide)) {
414 return -1;
415 }
416 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Low6815c072015-05-11 01:08:48 -0700417 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800418
419 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700420 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800421 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700422 D( "adb_open: could not open '%s': ", path );
423 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800424 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700425 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800426 errno = ENOENT;
427 return -1;
428
429 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700430 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800431 errno = ENOTDIR;
432 return -1;
433
434 default:
David Pursellc573d522016-01-27 08:52:53 -0800435 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800436 errno = ENOENT;
437 return -1;
438 }
439 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800440
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800441 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700442 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800443 return _fh_to_int(f);
444}
445
446/* ignore mode on Win32 */
447int adb_creat(const char* path, int mode)
448{
449 FH f;
450
451 f = _fh_alloc( &_fh_file_class );
452 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800453 return -1;
454 }
455
Spencer Low50f5bf12015-11-12 15:20:15 -0800456 std::wstring path_wide;
457 if (!android::base::UTF8ToWide(path, &path_wide)) {
458 return -1;
459 }
460 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Low6815c072015-05-11 01:08:48 -0700461 FILE_SHARE_READ | FILE_SHARE_WRITE,
462 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
463 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800464
465 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700466 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800467 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700468 D( "adb_creat: could not open '%s': ", path );
469 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800470 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700471 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800472 errno = ENOENT;
473 return -1;
474
475 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700476 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800477 errno = ENOTDIR;
478 return -1;
479
480 default:
David Pursellc573d522016-01-27 08:52:53 -0800481 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800482 errno = ENOENT;
483 return -1;
484 }
485 }
486 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700487 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800488 return _fh_to_int(f);
489}
490
491
492int adb_read(int fd, void* buf, int len)
493{
Spencer Low3a2421b2015-05-22 20:09:06 -0700494 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800495
496 if (f == NULL) {
497 return -1;
498 }
499
500 return f->clazz->_fh_read( f, buf, len );
501}
502
503
504int adb_write(int fd, const void* buf, int len)
505{
Spencer Low3a2421b2015-05-22 20:09:06 -0700506 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800507
508 if (f == NULL) {
509 return -1;
510 }
511
512 return f->clazz->_fh_write(f, buf, len);
513}
514
515
516int adb_lseek(int fd, int pos, int where)
517{
Spencer Low3a2421b2015-05-22 20:09:06 -0700518 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800519
520 if (!f) {
521 return -1;
522 }
523
524 return f->clazz->_fh_lseek(f, pos, where);
525}
526
527
528int adb_close(int fd)
529{
Spencer Low3a2421b2015-05-22 20:09:06 -0700530 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800531
532 if (!f) {
533 return -1;
534 }
535
Yabin Cui815ad882015-09-02 17:44:28 -0700536 D( "adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800537 _fh_close(f);
538 return 0;
539}
540
Spencer Low028e1592015-10-18 16:45:09 -0700541// Overrides strerror() to handle error codes not supported by the Windows C
542// Runtime (MSVCRT.DLL).
543char* adb_strerror(int err) {
544 // sysdeps.h defines strerror to adb_strerror, but in this function, we
545 // want to call the real C Runtime strerror().
546#pragma push_macro("strerror")
547#undef strerror
548 const int saved_err = errno; // Save because we overwrite it later.
549
550 // Lookup the string for an unknown error.
551 char* errmsg = strerror(-1);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700552 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low028e1592015-10-18 16:45:09 -0700553
554 // Lookup the string for this error to see if the C Runtime has it.
555 errmsg = strerror(err);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700556 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low028e1592015-10-18 16:45:09 -0700557 // The CRT returned an error message and it is different than the error
558 // message for an unknown error, so it is probably valid, so use it.
559 } else {
560 // Check if we have a string for this error code.
561 const char* custom_msg = nullptr;
562 switch (err) {
563#pragma push_macro("ERR")
564#undef ERR
565#define ERR(errnum, desc) case errnum: custom_msg = desc; break
566 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
567 // Note that these cannot be longer than 94 characters because we
568 // pass this to _strerror() which has that requirement.
569 ERR(ECONNRESET, "Connection reset by peer");
570 ERR(EHOSTUNREACH, "No route to host");
571 ERR(ENETDOWN, "Network is down");
572 ERR(ENETRESET, "Network dropped connection because of reset");
573 ERR(ENOBUFS, "No buffer space available");
574 ERR(ENOPROTOOPT, "Protocol not available");
575 ERR(ENOTCONN, "Transport endpoint is not connected");
576 ERR(ENOTSOCK, "Socket operation on non-socket");
577 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
578#pragma pop_macro("ERR")
579 }
580
581 if (custom_msg != nullptr) {
582 // Use _strerror() to write our string into the writable per-thread
583 // buffer used by strerror()/_strerror(). _strerror() appends the
584 // msg for the current value of errno, so set errno to a consistent
585 // value for every call so that our code-path is always the same.
586 errno = 0;
587 errmsg = _strerror(custom_msg);
588 const size_t custom_msg_len = strlen(custom_msg);
589 // Just in case _strerror() returned a read-only string, check if
590 // the returned string starts with our custom message because that
591 // implies that the string is not read-only.
592 if ((errmsg != nullptr) &&
593 !strncmp(custom_msg, errmsg, custom_msg_len)) {
594 // _strerror() puts other text after our custom message, so
595 // remove that by terminating after our message.
596 errmsg[custom_msg_len] = '\0';
597 } else {
598 // For some reason nullptr was returned or a pointer to a
599 // read-only string was returned, so fallback to whatever
600 // strerror() can muster (probably "Unknown error" or some
601 // generic CRT error string).
602 errmsg = strerror(err);
603 }
604 } else {
605 // We don't have a custom message, so use whatever strerror(err)
606 // returned earlier.
607 }
608 }
609
610 errno = saved_err; // restore
611
612 return errmsg;
613#pragma pop_macro("strerror")
614}
615
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800616/**************************************************************************/
617/**************************************************************************/
618/***** *****/
619/***** socket-based file descriptors *****/
620/***** *****/
621/**************************************************************************/
622/**************************************************************************/
623
Spencer Low31aafa62015-01-25 14:40:16 -0800624#undef setsockopt
625
Spencer Low753d4852015-07-30 23:07:55 -0700626static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700627 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
628 // lot of POSIX and socket error codes, some of the resulting error codes
629 // are mapped to strings by adb_strerror() above.
Spencer Low753d4852015-07-30 23:07:55 -0700630 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800631 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700632 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
633 // case WSAEINTR: errno = EINTR; break;
634 case WSAEFAULT: errno = EFAULT; break;
635 case WSAEINVAL: errno = EINVAL; break;
636 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700637 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
638 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
639 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800640 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700641 case WSAENOTSOCK: errno = ENOTSOCK; break;
642 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
643 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
644 case WSAENETDOWN: errno = ENETDOWN; break;
645 case WSAENETRESET: errno = ENETRESET; break;
646 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
647 // to use EPIPE for these situations and there are some callers that look
648 // for EPIPE.
649 case WSAECONNABORTED: errno = EPIPE; break;
650 case WSAECONNRESET: errno = ECONNRESET; break;
651 case WSAENOBUFS: errno = ENOBUFS; break;
652 case WSAENOTCONN: errno = ENOTCONN; break;
653 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
654 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
655 // considerations: Reportedly send() can return zero on timeout, and POSIX
656 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
657 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
658 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800659 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800660 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700661 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700662 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800663 }
664}
665
Josh Gaoe7388122016-02-16 17:34:53 -0800666extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
667 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
668 int skipped = 0;
669 std::vector<WSAPOLLFD> sockets;
670 std::vector<adb_pollfd*> original;
671 for (size_t i = 0; i < nfds; ++i) {
672 FH fh = _fh_from_int(fds[i].fd, __func__);
673 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
674 D("adb_poll received bad FD %d", fds[i].fd);
675 fds[i].revents = POLLNVAL;
676 ++skipped;
677 } else {
678 WSAPOLLFD wsapollfd = {
679 .fd = fh->u.socket,
680 .events = static_cast<short>(fds[i].events)
681 };
682 sockets.push_back(wsapollfd);
683 original.push_back(&fds[i]);
684 }
Spencer Low753d4852015-07-30 23:07:55 -0700685 }
Josh Gaoe7388122016-02-16 17:34:53 -0800686
687 if (sockets.empty()) {
688 return skipped;
689 }
690
691 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
692 if (result == SOCKET_ERROR) {
693 _socket_set_errno(WSAGetLastError());
694 return -1;
695 }
696
697 // Map the results back onto the original set.
698 for (size_t i = 0; i < sockets.size(); ++i) {
699 original[i]->revents = sockets[i].revents;
700 }
701
702 // WSAPoll appears to return the number of unique FDs with avaiable events, instead of how many
703 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
704 // to do. Ignore its result and calculate the proper return value.
705 result = 0;
706 for (size_t i = 0; i < nfds; ++i) {
707 if (fds[i].revents != 0) {
708 ++result;
709 }
710 }
711 return result;
712}
713
714static void _fh_socket_init(FH f) {
715 f->fh_socket = INVALID_SOCKET;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800716 f->mask = 0;
717}
718
Elliott Hughes6a096932015-04-16 16:47:02 -0700719static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700720 if (f->fh_socket != INVALID_SOCKET) {
721 /* gently tell any peer that we're closing the socket */
722 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
723 // If the socket is not connected, this returns an error. We want to
724 // minimize logging spam, so don't log these errors for now.
725#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700726 D("socket shutdown failed: %s",
David Pursellc573d522016-01-27 08:52:53 -0800727 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700728#endif
729 }
730 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Yabin Cui815ad882015-09-02 17:44:28 -0700731 D("closesocket failed: %s",
David Pursellc573d522016-01-27 08:52:53 -0800732 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700733 }
734 f->fh_socket = INVALID_SOCKET;
735 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800736 f->mask = 0;
737 return 0;
738}
739
Elliott Hughes6a096932015-04-16 16:47:02 -0700740static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800741 errno = EPIPE;
742 return -1;
743}
744
Elliott Hughes6a096932015-04-16 16:47:02 -0700745static int _fh_socket_read(FH f, void* buf, int len) {
746 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800747 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700748 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700749 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
750 // that to reduce spam and confusion.
751 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700752 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800753 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low32625852015-08-11 16:45:32 -0700754 }
Spencer Low753d4852015-07-30 23:07:55 -0700755 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800756 result = -1;
757 }
758 return result;
759}
760
Elliott Hughes6a096932015-04-16 16:47:02 -0700761static int _fh_socket_write(FH f, const void* buf, int len) {
762 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800763 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700764 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700765 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
766 // that to reduce spam and confusion.
767 if (err != WSAEWOULDBLOCK) {
768 D("send fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800769 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low028e1592015-10-18 16:45:09 -0700770 }
Spencer Low753d4852015-07-30 23:07:55 -0700771 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800772 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700773 } else {
774 // According to https://code.google.com/p/chromium/issues/detail?id=27870
775 // Winsock Layered Service Providers may cause this.
776 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
777 << f->name << ", but " << result
778 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800779 }
780 return result;
781}
782
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800783/**************************************************************************/
784/**************************************************************************/
785/***** *****/
786/***** replacement for libs/cutils/socket_xxxx.c *****/
787/***** *****/
788/**************************************************************************/
789/**************************************************************************/
790
791#include <winsock2.h>
792
793static int _winsock_init;
794
795static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800796_init_winsock( void )
797{
Spencer Low753d4852015-07-30 23:07:55 -0700798 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700799 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800800 if (!_winsock_init) {
801 WSADATA wsaData;
802 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
803 if (rc != 0) {
David Pursellc573d522016-01-27 08:52:53 -0800804 fatal("adb: could not initialize Winsock: %s",
805 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800806 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800807 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700808
809 // Note that we do not call atexit() to register WSACleanup to be called
810 // at normal process termination because:
811 // 1) When exit() is called, there are still threads actively using
812 // Winsock because we don't cleanly shutdown all threads, so it
813 // doesn't make sense to call WSACleanup() and may cause problems
814 // with those threads.
815 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
816 // calls WSACleanup() which tries to unload a DLL, which tries to
817 // grab the LoaderLock. This conflicts with the device_poll_thread
818 // which holds the LoaderLock because AdbWinApi.dll calls
819 // setupapi.dll which tries to load wintrust.dll which tries to load
820 // crypt32.dll which calls atexit() which tries to acquire the C
821 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800822 }
823}
824
Spencer Lowc7c45612015-09-29 15:05:29 -0700825// Map a socket type to an explicit socket protocol instead of using the socket
826// protocol of 0. Explicit socket protocols are used by most apps and we should
827// do the same to reduce the chance of exercising uncommon code-paths that might
828// have problems or that might load different Winsock service providers that
829// have problems.
830static int GetSocketProtocolFromSocketType(int type) {
831 switch (type) {
832 case SOCK_STREAM:
833 return IPPROTO_TCP;
834 case SOCK_DGRAM:
835 return IPPROTO_UDP;
836 default:
837 LOG(FATAL) << "Unknown socket type: " << type;
838 return 0;
839 }
840}
841
Spencer Low753d4852015-07-30 23:07:55 -0700842int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800843 struct sockaddr_in addr;
844 SOCKET s;
845
Spencer Low753d4852015-07-30 23:07:55 -0700846 unique_fh f(_fh_alloc(&_fh_socket_class));
847 if (!f) {
848 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800849 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700850 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800851
852 if (!_winsock_init)
853 _init_winsock();
854
855 memset(&addr, 0, sizeof(addr));
856 addr.sin_family = AF_INET;
857 addr.sin_port = htons(port);
858 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
859
Spencer Lowc7c45612015-09-29 15:05:29 -0700860 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800861 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700862 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursellc573d522016-01-27 08:52:53 -0800863 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700864 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700865 return -1;
866 }
867 f->fh_socket = s;
868
869 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700870 // Save err just in case inet_ntoa() or ntohs() changes the last error.
871 const DWORD err = WSAGetLastError();
872 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
873 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
David Pursellc573d522016-01-27 08:52:53 -0800874 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700875 D("could not connect to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700876 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800877 return -1;
878 }
879
Spencer Low753d4852015-07-30 23:07:55 -0700880 const int fd = _fh_to_int(f.get());
881 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
882 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700883 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700884 fd );
885 f.release();
886 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800887}
888
889#define LISTEN_BACKLOG 4
890
Spencer Low753d4852015-07-30 23:07:55 -0700891// interface_address is INADDR_LOOPBACK or INADDR_ANY.
892static int _network_server(int port, int type, u_long interface_address,
893 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800894 struct sockaddr_in addr;
895 SOCKET s;
896 int n;
897
Spencer Low753d4852015-07-30 23:07:55 -0700898 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800899 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700900 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800901 return -1;
902 }
903
904 if (!_winsock_init)
905 _init_winsock();
906
907 memset(&addr, 0, sizeof(addr));
908 addr.sin_family = AF_INET;
909 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700910 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800911
Spencer Low753d4852015-07-30 23:07:55 -0700912 // TODO: Consider using dual-stack socket that can simultaneously listen on
913 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700914 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700915 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700916 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursellc573d522016-01-27 08:52:53 -0800917 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700918 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700919 return -1;
920 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800921
922 f->fh_socket = s;
923
Spencer Low32625852015-08-11 16:45:32 -0700924 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
925 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800926 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700927 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
928 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700929 *error = android::base::StringPrintf(
930 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
David Pursellc573d522016-01-27 08:52:53 -0800931 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700932 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700933 return -1;
934 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800935
Spencer Low32625852015-08-11 16:45:32 -0700936 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
937 // Save err just in case inet_ntoa() or ntohs() changes the last error.
938 const DWORD err = WSAGetLastError();
939 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
940 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
David Pursellc573d522016-01-27 08:52:53 -0800941 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700942 D("could not bind to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700943 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800944 return -1;
945 }
946 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700947 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700948 *error = android::base::StringPrintf("cannot listen on socket: %s",
David Pursellc573d522016-01-27 08:52:53 -0800949 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700950 D("could not listen on %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700951 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800952 return -1;
953 }
954 }
Spencer Low753d4852015-07-30 23:07:55 -0700955 const int fd = _fh_to_int(f.get());
956 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
957 interface_address == INADDR_LOOPBACK ? "lo" : "any",
958 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700959 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700960 fd );
961 f.release();
962 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800963}
964
Spencer Low753d4852015-07-30 23:07:55 -0700965int network_loopback_server(int port, int type, std::string* error) {
966 return _network_server(port, type, INADDR_LOOPBACK, error);
967}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800968
Spencer Low753d4852015-07-30 23:07:55 -0700969int network_inaddr_any_server(int port, int type, std::string* error) {
970 return _network_server(port, type, INADDR_ANY, error);
971}
972
973int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
974 unique_fh f(_fh_alloc(&_fh_socket_class));
975 if (!f) {
976 *error = strerror(errno);
977 return -1;
978 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800979
Elliott Hughes43df1092015-07-23 17:12:58 -0700980 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800981
Spencer Low753d4852015-07-30 23:07:55 -0700982 struct addrinfo hints;
983 memset(&hints, 0, sizeof(hints));
984 hints.ai_family = AF_UNSPEC;
985 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700986 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700987
988 char port_str[16];
989 snprintf(port_str, sizeof(port_str), "%d", port);
990
991 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700992
993#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
994 // TODO: When the Android SDK tools increases the Windows system
Spencer Low50f5bf12015-11-12 15:20:15 -0800995 // requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700996#else
997 // Otherwise, keep using getaddrinfo(), or do runtime API detection
998 // with GetProcAddress("GetAddrInfoW").
999#endif
Spencer Low753d4852015-07-30 23:07:55 -07001000 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -07001001 *error = android::base::StringPrintf(
1002 "cannot resolve host '%s' and port %s: %s", host.c_str(),
David Pursellc573d522016-01-27 08:52:53 -08001003 port_str, android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001004 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001005 return -1;
1006 }
Spencer Low753d4852015-07-30 23:07:55 -07001007 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
1008 addrinfo(addrinfo_ptr, freeaddrinfo);
1009 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001010
Spencer Low753d4852015-07-30 23:07:55 -07001011 // TODO: Try all the addresses if there's more than one? This just uses
1012 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
1013 // which tries all addresses, takes a timeout and more.
1014 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
1015 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001016 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -07001017 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursellc573d522016-01-27 08:52:53 -08001018 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001019 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001020 return -1;
1021 }
1022 f->fh_socket = s;
1023
Spencer Low753d4852015-07-30 23:07:55 -07001024 // TODO: Implement timeouts for Windows. Seems like the default in theory
1025 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
1026 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -07001027 // TODO: Use WSAAddressToString or inet_ntop on address.
1028 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
1029 host.c_str(), port_str,
David Pursellc573d522016-01-27 08:52:53 -08001030 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001031 D("could not connect to %s:%s:%s: %s",
Spencer Low753d4852015-07-30 23:07:55 -07001032 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
1033 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001034 return -1;
1035 }
1036
Spencer Low753d4852015-07-30 23:07:55 -07001037 const int fd = _fh_to_int(f.get());
1038 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
1039 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -07001040 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low753d4852015-07-30 23:07:55 -07001041 type != SOCK_STREAM ? "udp" : "tcp", fd );
1042 f.release();
1043 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001044}
1045
1046#undef accept
1047int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
1048{
Spencer Low3a2421b2015-05-22 20:09:06 -07001049 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001050
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001051 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001052 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -07001053 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001054 return -1;
1055 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001056
Spencer Low753d4852015-07-30 23:07:55 -07001057 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001058 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -07001059 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1060 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001061 return -1;
1062 }
1063
1064 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1065 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001066 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -07001067 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursellc573d522016-01-27 08:52:53 -08001068 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low753d4852015-07-30 23:07:55 -07001069 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001070 return -1;
1071 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001072
Spencer Low753d4852015-07-30 23:07:55 -07001073 const int fd = _fh_to_int(fh.get());
1074 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -07001075 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -07001076 fh.release();
1077 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001078}
1079
1080
Spencer Low31aafa62015-01-25 14:40:16 -08001081int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001082{
Spencer Low3a2421b2015-05-22 20:09:06 -07001083 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001084
Spencer Low31aafa62015-01-25 14:40:16 -08001085 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001086 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001087 errno = EBADF;
1088 return -1;
1089 }
Spencer Lowc7c45612015-09-29 15:05:29 -07001090
1091 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1092 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1093 // auto-tuning.
1094
Spencer Low753d4852015-07-30 23:07:55 -07001095 int result = setsockopt( fh->fh_socket, level, optname,
1096 reinterpret_cast<const char*>(optval), optlen );
1097 if ( result == SOCKET_ERROR ) {
1098 const DWORD err = WSAGetLastError();
David Pursellc573d522016-01-27 08:52:53 -08001099 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1100 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001101 _socket_set_errno( err );
1102 result = -1;
1103 }
1104 return result;
1105}
1106
Josh Gaoe7388122016-02-16 17:34:53 -08001107int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1108 FH fh = _fh_from_int(fd, __func__);
1109
1110 if (!fh || fh->clazz != &_fh_socket_class) {
1111 D("adb_getsockname: invalid fd %d", fd);
1112 errno = EBADF;
1113 return -1;
1114 }
1115
1116 int result = getsockname(fh->fh_socket, sockaddr, optlen);
1117 if (result == SOCKET_ERROR) {
1118 const DWORD err = WSAGetLastError();
1119 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1120 android::base::SystemErrorCodeToString(err).c_str());
1121 _socket_set_errno(err);
1122 result = -1;
1123 }
1124 return result;
1125}
Spencer Low753d4852015-07-30 23:07:55 -07001126
1127int adb_shutdown(int fd)
1128{
1129 FH f = _fh_from_int(fd, __func__);
1130
1131 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001132 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001133 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001134 return -1;
1135 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001136
Yabin Cui815ad882015-09-02 17:44:28 -07001137 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001138 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1139 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001140 D("socket shutdown fd %d failed: %s", fd,
David Pursellc573d522016-01-27 08:52:53 -08001141 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001142 _socket_set_errno(err);
1143 return -1;
1144 }
1145 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001146}
1147
Josh Gaoe7388122016-02-16 17:34:53 -08001148// Emulate socketpair(2) by binding and connecting to a socket.
1149int adb_socketpair(int sv[2]) {
1150 int server = -1;
1151 int client = -1;
1152 int accepted = -1;
1153 sockaddr_storage addr_storage;
1154 socklen_t addr_len = sizeof(addr_storage);
1155 sockaddr_in* addr = nullptr;
1156 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001157
Josh Gaoe7388122016-02-16 17:34:53 -08001158 server = network_loopback_server(0, SOCK_STREAM, &error);
1159 if (server < 0) {
1160 D("adb_socketpair: failed to create server: %s", error.c_str());
1161 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001162 }
1163
Josh Gaoe7388122016-02-16 17:34:53 -08001164 if (adb_getsockname(server, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1165 D("adb_socketpair: adb_getsockname failed: %s", strerror(errno));
1166 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001167 }
1168
Josh Gaoe7388122016-02-16 17:34:53 -08001169 if (addr_storage.ss_family != AF_INET) {
1170 D("adb_socketpair: unknown address family received: %d", addr_storage.ss_family);
1171 errno = ECONNABORTED;
1172 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001173 }
1174
Josh Gaoe7388122016-02-16 17:34:53 -08001175 addr = reinterpret_cast<sockaddr_in*>(&addr_storage);
1176 D("adb_socketpair: bound on port %d", ntohs(addr->sin_port));
1177 client = network_loopback_client(ntohs(addr->sin_port), SOCK_STREAM, &error);
1178 if (client < 0) {
1179 D("adb_socketpair: failed to connect client: %s", error.c_str());
1180 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001181 }
1182
Josh Gaoe7388122016-02-16 17:34:53 -08001183 accepted = adb_socket_accept(server, nullptr, nullptr);
1184 if (accepted < 0) {
1185 const DWORD err = WSAGetLastError();
1186 D("adb_socketpair: failed to accept: %s",
1187 android::base::SystemErrorCodeToString(err).c_str());
1188 _socket_set_errno(err);
1189 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001190 }
Josh Gaoe7388122016-02-16 17:34:53 -08001191 adb_close(server);
1192 sv[0] = client;
1193 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001194 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001195
Josh Gaoe7388122016-02-16 17:34:53 -08001196fail:
1197 if (server >= 0) {
1198 adb_close(server);
1199 }
1200 if (client >= 0) {
1201 adb_close(client);
1202 }
1203 if (accepted >= 0) {
1204 adb_close(accepted);
1205 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001206 return -1;
1207}
1208
Josh Gaoe7388122016-02-16 17:34:53 -08001209bool set_file_block_mode(int fd, bool block) {
1210 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001211
Josh Gaoe7388122016-02-16 17:34:53 -08001212 if (!fh || !fh->used) {
1213 errno = EBADF;
1214 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001215 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001216
Josh Gaoe7388122016-02-16 17:34:53 -08001217 if (fh->clazz == &_fh_socket_class) {
1218 u_long x = !block;
1219 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
1220 _socket_set_errno(WSAGetLastError());
1221 return false;
1222 }
1223 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001224 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001225 errno = ENOTSOCK;
1226 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001227 }
1228}
1229
Spencer Lowf373c352015-11-15 16:29:36 -08001230static adb_mutex_t g_console_output_buffer_lock;
1231
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001232void
1233adb_sysdeps_init( void )
1234{
1235#define ADB_MUTEX(x) InitializeCriticalSection( & x );
1236#include "mutex_list.h"
1237 InitializeCriticalSection( &_win32_lock );
Spencer Lowf373c352015-11-15 16:29:36 -08001238 InitializeCriticalSection( &g_console_output_buffer_lock );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001239}
1240
Spencer Lowbeb61982015-03-01 15:06:21 -08001241/**************************************************************************/
1242/**************************************************************************/
1243/***** *****/
1244/***** Console Window Terminal Emulation *****/
1245/***** *****/
1246/**************************************************************************/
1247/**************************************************************************/
1248
1249// This reads input from a Win32 console window and translates it into Unix
1250// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1251// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1252// is emulated instead of xterm because it is probably more popular than xterm:
1253// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1254// supports modern fonts, etc. It seems best to emulate the terminal that most
1255// Android developers use because they'll fix apps (the shell, etc.) to keep
1256// working with that terminal's emulation.
1257//
1258// The point of this emulation is not to be perfect or to solve all issues with
1259// console windows on Windows, but to be better than the original code which
1260// just called read() (which called ReadFile(), which called ReadConsoleA())
1261// which did not support Ctrl-C, tab completion, shell input line editing
1262// keys, server echo, and more.
1263//
1264// This implementation reconfigures the console with SetConsoleMode(), then
1265// calls ReadConsoleInput() to get raw input which it remaps to Unix
1266// terminal-style sequences which is returned via unix_read() which is used
1267// by the 'adb shell' command.
1268//
1269// Code organization:
1270//
David Pursell58805362015-10-28 14:29:51 -07001271// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001272// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1273// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1274// * _console_read() is the main code of the emulation.
1275
David Pursell58805362015-10-28 14:29:51 -07001276// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1277// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1278// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1279static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1280 // First check isatty(); this is very fast and eliminates most non-console
1281 // FDs, but returns 1 for both consoles and character devices like NUL.
1282#pragma push_macro("isatty")
1283#undef isatty
1284 if (!isatty(fd)) {
1285 return nullptr;
1286 }
1287#pragma pop_macro("isatty")
1288
1289 // To differentiate between character devices and consoles we need to get
1290 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1291 // GENERIC_READ permissions.
1292 const intptr_t intptr_handle = _get_osfhandle(fd);
1293 if (intptr_handle == -1) {
1294 return nullptr;
1295 }
1296 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1297 DWORD temp_mode = 0;
1298 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1299 return nullptr;
1300 }
1301
1302 return handle;
1303}
1304
1305// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1306static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001307 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1308 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001309 const int fd = fileno(stream);
1310 if (fd < 0) {
1311 return nullptr;
1312 }
1313 return _get_console_handle(fd);
1314}
1315
1316int unix_isatty(int fd) {
1317 return _get_console_handle(fd) ? 1 : 0;
1318}
Spencer Lowbeb61982015-03-01 15:06:21 -08001319
Spencer Low9c8f7462015-11-10 19:17:16 -08001320// Get the next KEY_EVENT_RECORD that should be processed.
1321static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001322 for (;;) {
1323 DWORD read_count = 0;
1324 memset(input_record, 0, sizeof(*input_record));
1325 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001326 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001327 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001328 errno = EIO;
1329 return false;
1330 }
1331
1332 if (read_count == 0) { // should be impossible
1333 fatal("ReadConsoleInputA returned 0");
1334 }
1335
1336 if (read_count != 1) { // should be impossible
1337 fatal("ReadConsoleInputA did not return one input record");
1338 }
1339
Spencer Low55441402015-11-07 17:34:39 -08001340 // If the console window is resized, emulate SIGWINCH by breaking out
1341 // of read() with errno == EINTR. Note that there is no event on
1342 // vertical resize because we don't give the console our own custom
1343 // screen buffer (with CreateConsoleScreenBuffer() +
1344 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1345 // supports scrollback, but doesn't seem to raise an event for vertical
1346 // window resize.
1347 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1348 errno = EINTR;
1349 return false;
1350 }
1351
Spencer Lowbeb61982015-03-01 15:06:21 -08001352 if ((input_record->EventType == KEY_EVENT) &&
1353 (input_record->Event.KeyEvent.bKeyDown)) {
1354 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1355 fatal("ReadConsoleInputA returned a key event with zero repeat"
1356 " count");
1357 }
1358
1359 // Got an interesting INPUT_RECORD, so return
1360 return true;
1361 }
1362 }
1363}
1364
Spencer Lowbeb61982015-03-01 15:06:21 -08001365static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1366 return (control_key_state & SHIFT_PRESSED) != 0;
1367}
1368
1369static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1370 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1371}
1372
1373static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1374 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1375}
1376
1377static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1378 return (control_key_state & NUMLOCK_ON) != 0;
1379}
1380
1381static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1382 return (control_key_state & CAPSLOCK_ON) != 0;
1383}
1384
1385static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1386 return (control_key_state & ENHANCED_KEY) != 0;
1387}
1388
1389// Constants from MSDN for ToAscii().
1390static const BYTE TOASCII_KEY_OFF = 0x00;
1391static const BYTE TOASCII_KEY_DOWN = 0x80;
1392static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1393
1394// Given a key event, ignore a modifier key and return the character that was
1395// entered without the modifier. Writes to *ch and returns the number of bytes
1396// written.
1397static size_t _get_char_ignoring_modifier(char* const ch,
1398 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1399 const WORD modifier) {
1400 // If there is no character from Windows, try ignoring the specified
1401 // modifier and look for a character. Note that if AltGr is being used,
1402 // there will be a character from Windows.
1403 if (key_event->uChar.AsciiChar == '\0') {
1404 // Note that we read the control key state from the passed in argument
1405 // instead of from key_event since the argument has been normalized.
1406 if (((modifier == VK_SHIFT) &&
1407 _is_shift_pressed(control_key_state)) ||
1408 ((modifier == VK_CONTROL) &&
1409 _is_ctrl_pressed(control_key_state)) ||
1410 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1411
1412 BYTE key_state[256] = {0};
1413 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1414 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1415 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1416 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1417 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1418 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1419 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1420 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1421
1422 // cause this modifier to be ignored
1423 key_state[modifier] = TOASCII_KEY_OFF;
1424
1425 WORD translated = 0;
1426 if (ToAscii(key_event->wVirtualKeyCode,
1427 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1428 // Ignoring the modifier, we found a character.
1429 *ch = (CHAR)translated;
1430 return 1;
1431 }
1432 }
1433 }
1434
1435 // Just use whatever Windows told us originally.
1436 *ch = key_event->uChar.AsciiChar;
1437
1438 // If the character from Windows is NULL, return a size of zero.
1439 return (*ch == '\0') ? 0 : 1;
1440}
1441
1442// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1443// but taking into account the shift key. This is because for a sequence like
1444// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1445// we want to find the character ')'.
1446//
1447// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1448// because it is the default key-sequence to switch the input language.
1449// This is configurable in the Region and Language control panel.
1450static __inline__ size_t _get_non_control_char(char* const ch,
1451 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1452 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1453 VK_CONTROL);
1454}
1455
1456// Get without Alt.
1457static __inline__ size_t _get_non_alt_char(char* const ch,
1458 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1459 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1460 VK_MENU);
1461}
1462
1463// Ignore the control key, find the character from Windows, and apply any
1464// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1465// *pch and returns number of bytes written.
1466static size_t _get_control_character(char* const pch,
1467 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1468 const size_t len = _get_non_control_char(pch, key_event,
1469 control_key_state);
1470
1471 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1472 char ch = *pch;
1473 switch (ch) {
1474 case '2':
1475 case '@':
1476 case '`':
1477 ch = '\0';
1478 break;
1479 case '3':
1480 case '[':
1481 case '{':
1482 ch = '\x1b';
1483 break;
1484 case '4':
1485 case '\\':
1486 case '|':
1487 ch = '\x1c';
1488 break;
1489 case '5':
1490 case ']':
1491 case '}':
1492 ch = '\x1d';
1493 break;
1494 case '6':
1495 case '^':
1496 case '~':
1497 ch = '\x1e';
1498 break;
1499 case '7':
1500 case '-':
1501 case '_':
1502 ch = '\x1f';
1503 break;
1504 case '8':
1505 ch = '\x7f';
1506 break;
1507 case '/':
1508 if (!_is_alt_pressed(control_key_state)) {
1509 ch = '\x1f';
1510 }
1511 break;
1512 case '?':
1513 if (!_is_alt_pressed(control_key_state)) {
1514 ch = '\x7f';
1515 }
1516 break;
1517 }
1518 *pch = ch;
1519 }
1520
1521 return len;
1522}
1523
1524static DWORD _normalize_altgr_control_key_state(
1525 const KEY_EVENT_RECORD* const key_event) {
1526 DWORD control_key_state = key_event->dwControlKeyState;
1527
1528 // If we're in an AltGr situation where the AltGr key is down (depending on
1529 // the keyboard layout, that might be the physical right alt key which
1530 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1531 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1532 // a character (which indicates that there was an AltGr mapping), then act
1533 // as if alt and control are not really down for the purposes of modifiers.
1534 // This makes it so that if the user with, say, a German keyboard layout
1535 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1536 // output the key and we don't see the Alt and Ctrl keys.
1537 if (_is_ctrl_pressed(control_key_state) &&
1538 _is_alt_pressed(control_key_state)
1539 && (key_event->uChar.AsciiChar != '\0')) {
1540 // Try to remove as few bits as possible to improve our chances of
1541 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1542 // Left-Alt + Right-Ctrl + AltGr.
1543 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1544 // Remove Right-Alt.
1545 control_key_state &= ~RIGHT_ALT_PRESSED;
1546 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1547 // pressed, Left-Ctrl is almost always set, except if the user
1548 // presses Right-Ctrl, then AltGr (in that specific order) for
1549 // whatever reason. At any rate, make sure the bit is not set.
1550 control_key_state &= ~LEFT_CTRL_PRESSED;
1551 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1552 // Remove Left-Alt.
1553 control_key_state &= ~LEFT_ALT_PRESSED;
1554 // Whichever Ctrl key is down, remove it from the state. We only
1555 // remove one key, to improve our chances of detecting the
1556 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1557 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1558 // Remove Left-Ctrl.
1559 control_key_state &= ~LEFT_CTRL_PRESSED;
1560 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1561 // Remove Right-Ctrl.
1562 control_key_state &= ~RIGHT_CTRL_PRESSED;
1563 }
1564 }
1565
1566 // Note that this logic isn't 100% perfect because Windows doesn't
1567 // allow us to detect all combinations because a physical AltGr key
1568 // press shows up as two bits, plus some combinations are ambiguous
1569 // about what is actually physically pressed.
1570 }
1571
1572 return control_key_state;
1573}
1574
1575// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1576// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1577// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1578// appropriately.
1579static DWORD _normalize_keypad_control_key_state(const WORD vk,
1580 const DWORD control_key_state) {
1581 if (!_is_numlock_on(control_key_state)) {
1582 return control_key_state;
1583 }
1584 if (!_is_enhanced_key(control_key_state)) {
1585 switch (vk) {
1586 case VK_INSERT: // 0
1587 case VK_DELETE: // .
1588 case VK_END: // 1
1589 case VK_DOWN: // 2
1590 case VK_NEXT: // 3
1591 case VK_LEFT: // 4
1592 case VK_CLEAR: // 5
1593 case VK_RIGHT: // 6
1594 case VK_HOME: // 7
1595 case VK_UP: // 8
1596 case VK_PRIOR: // 9
1597 return control_key_state | SHIFT_PRESSED;
1598 }
1599 }
1600
1601 return control_key_state;
1602}
1603
1604static const char* _get_keypad_sequence(const DWORD control_key_state,
1605 const char* const normal, const char* const shifted) {
1606 if (_is_shift_pressed(control_key_state)) {
1607 // Shift is pressed and NumLock is off
1608 return shifted;
1609 } else {
1610 // Shift is not pressed and NumLock is off, or,
1611 // Shift is pressed and NumLock is on, in which case we want the
1612 // NumLock and Shift to neutralize each other, thus, we want the normal
1613 // sequence.
1614 return normal;
1615 }
1616 // If Shift is not pressed and NumLock is on, a different virtual key code
1617 // is returned by Windows, which can be taken care of by a different case
1618 // statement in _console_read().
1619}
1620
1621// Write sequence to buf and return the number of bytes written.
1622static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1623 DWORD control_key_state, const char* const normal) {
1624 // Copy the base sequence into buf.
1625 const size_t len = strlen(normal);
1626 memcpy(buf, normal, len);
1627
1628 int code = 0;
1629
1630 control_key_state = _normalize_keypad_control_key_state(vk,
1631 control_key_state);
1632
1633 if (_is_shift_pressed(control_key_state)) {
1634 code |= 0x1;
1635 }
1636 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1637 code |= 0x2;
1638 }
1639 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1640 code |= 0x4;
1641 }
1642 // If some modifier was held down, then we need to insert the modifier code
1643 if (code != 0) {
1644 if (len == 0) {
1645 // Should be impossible because caller should pass a string of
1646 // non-zero length.
1647 return 0;
1648 }
1649 size_t index = len - 1;
1650 const char lastChar = buf[index];
1651 if (lastChar != '~') {
1652 buf[index++] = '1';
1653 }
1654 buf[index++] = ';'; // modifier separator
1655 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1656 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1657 buf[index++] = '1' + code;
1658 buf[index++] = lastChar; // move ~ (or other last char) to the end
1659 return index;
1660 }
1661 return len;
1662}
1663
1664// Write sequence to buf and return the number of bytes written.
1665static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1666 const DWORD control_key_state, const char* const normal,
1667 const char shifted) {
1668 if (_is_shift_pressed(control_key_state)) {
1669 // Shift is pressed and NumLock is off
1670 if (shifted != '\0') {
1671 buf[0] = shifted;
1672 return sizeof(buf[0]);
1673 } else {
1674 return 0;
1675 }
1676 } else {
1677 // Shift is not pressed and NumLock is off, or,
1678 // Shift is pressed and NumLock is on, in which case we want the
1679 // NumLock and Shift to neutralize each other, thus, we want the normal
1680 // sequence.
1681 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1682 }
1683 // If Shift is not pressed and NumLock is on, a different virtual key code
1684 // is returned by Windows, which can be taken care of by a different case
1685 // statement in _console_read().
1686}
1687
1688// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1689// Standard German. Figure this out at runtime so we know what to output for
1690// Shift-VK_DELETE.
1691static char _get_decimal_char() {
1692 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1693}
1694
1695// Prefix the len bytes in buf with the escape character, and then return the
1696// new buffer length.
1697size_t _escape_prefix(char* const buf, const size_t len) {
1698 // If nothing to prefix, don't do anything. We might be called with
1699 // len == 0, if alt was held down with a dead key which produced nothing.
1700 if (len == 0) {
1701 return 0;
1702 }
1703
1704 memmove(&buf[1], buf, len);
1705 buf[0] = '\x1b';
1706 return len + 1;
1707}
1708
Spencer Low9c8f7462015-11-10 19:17:16 -08001709// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001710static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001711
1712// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1713// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001714static int _console_read(const HANDLE console, void* buf, size_t len) {
1715 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001716 // Read of zero bytes should not block waiting for something from the console.
1717 if (len == 0) {
1718 return 0;
1719 }
1720
1721 // Flush as much as possible from input buffer.
1722 if (!g_console_input_buffer.empty()) {
1723 const int bytes_read = std::min(len, g_console_input_buffer.size());
1724 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1725 const auto begin = g_console_input_buffer.begin();
1726 g_console_input_buffer.erase(begin, begin + bytes_read);
1727 return bytes_read;
1728 }
1729
1730 // Read from the actual console. This may block until input.
1731 INPUT_RECORD input_record;
1732 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001733 return -1;
1734 }
1735
Spencer Low9c8f7462015-11-10 19:17:16 -08001736 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001737 const WORD vk = key_event->wVirtualKeyCode;
1738 const CHAR ch = key_event->uChar.AsciiChar;
1739 const DWORD control_key_state = _normalize_altgr_control_key_state(
1740 key_event);
1741
1742 // The following emulation code should write the output sequence to
1743 // either seqstr or to seqbuf and seqbuflen.
1744 const char* seqstr = NULL; // NULL terminated C-string
1745 // Enough space for max sequence string below, plus modifiers and/or
1746 // escape prefix.
1747 char seqbuf[16];
1748 size_t seqbuflen = 0; // Space used in seqbuf.
1749
1750#define MATCH(vk, normal) \
1751 case (vk): \
1752 { \
1753 seqstr = (normal); \
1754 } \
1755 break;
1756
1757 // Modifier keys should affect the output sequence.
1758#define MATCH_MODIFIER(vk, normal) \
1759 case (vk): \
1760 { \
1761 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1762 control_key_state, (normal)); \
1763 } \
1764 break;
1765
1766 // The shift key should affect the output sequence.
1767#define MATCH_KEYPAD(vk, normal, shifted) \
1768 case (vk): \
1769 { \
1770 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1771 (shifted)); \
1772 } \
1773 break;
1774
1775 // The shift key and other modifier keys should affect the output
1776 // sequence.
1777#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1778 case (vk): \
1779 { \
1780 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1781 control_key_state, (normal), (shifted)); \
1782 } \
1783 break;
1784
1785#define ESC "\x1b"
1786#define CSI ESC "["
1787#define SS3 ESC "O"
1788
1789 // Only support normal mode, not application mode.
1790
1791 // Enhanced keys:
1792 // * 6-pack: insert, delete, home, end, page up, page down
1793 // * cursor keys: up, down, right, left
1794 // * keypad: divide, enter
1795 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1796 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1797 if (_is_enhanced_key(control_key_state)) {
1798 switch (vk) {
1799 case VK_RETURN: // Enter key on keypad
1800 if (_is_ctrl_pressed(control_key_state)) {
1801 seqstr = "\n";
1802 } else {
1803 seqstr = "\r";
1804 }
1805 break;
1806
1807 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1808 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1809
1810 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1811 // will be fixed soon to match xterm which sends CSI "F" and
1812 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1813 MATCH(VK_END, CSI "F");
1814 MATCH(VK_HOME, CSI "H");
1815
1816 MATCH_MODIFIER(VK_LEFT, CSI "D");
1817 MATCH_MODIFIER(VK_UP, CSI "A");
1818 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1819 MATCH_MODIFIER(VK_DOWN, CSI "B");
1820
1821 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1822 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1823
1824 MATCH(VK_DIVIDE, "/");
1825 }
1826 } else { // Non-enhanced keys:
1827 switch (vk) {
1828 case VK_BACK: // backspace
1829 if (_is_alt_pressed(control_key_state)) {
1830 seqstr = ESC "\x7f";
1831 } else {
1832 seqstr = "\x7f";
1833 }
1834 break;
1835
1836 case VK_TAB:
1837 if (_is_shift_pressed(control_key_state)) {
1838 seqstr = CSI "Z";
1839 } else {
1840 seqstr = "\t";
1841 }
1842 break;
1843
1844 // Number 5 key in keypad when NumLock is off, or if NumLock is
1845 // on and Shift is down.
1846 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1847
1848 case VK_RETURN: // Enter key on main keyboard
1849 if (_is_alt_pressed(control_key_state)) {
1850 seqstr = ESC "\n";
1851 } else if (_is_ctrl_pressed(control_key_state)) {
1852 seqstr = "\n";
1853 } else {
1854 seqstr = "\r";
1855 }
1856 break;
1857
1858 // VK_ESCAPE: Don't do any special handling. The OS uses many
1859 // of the sequences with Escape and many of the remaining
1860 // sequences don't produce bKeyDown messages, only !bKeyDown
1861 // for whatever reason.
1862
1863 case VK_SPACE:
1864 if (_is_alt_pressed(control_key_state)) {
1865 seqstr = ESC " ";
1866 } else if (_is_ctrl_pressed(control_key_state)) {
1867 seqbuf[0] = '\0'; // NULL char
1868 seqbuflen = 1;
1869 } else {
1870 seqstr = " ";
1871 }
1872 break;
1873
1874 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1875 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1876
1877 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1878 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1879
1880 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1881 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1882 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1883 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1884
1885 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1886 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1887 _get_decimal_char());
1888
1889 case 0x30: // 0
1890 case 0x31: // 1
1891 case 0x39: // 9
1892 case VK_OEM_1: // ;:
1893 case VK_OEM_PLUS: // =+
1894 case VK_OEM_COMMA: // ,<
1895 case VK_OEM_PERIOD: // .>
1896 case VK_OEM_7: // '"
1897 case VK_OEM_102: // depends on keyboard, could be <> or \|
1898 case VK_OEM_2: // /?
1899 case VK_OEM_3: // `~
1900 case VK_OEM_4: // [{
1901 case VK_OEM_5: // \|
1902 case VK_OEM_6: // ]}
1903 {
1904 seqbuflen = _get_control_character(seqbuf, key_event,
1905 control_key_state);
1906
1907 if (_is_alt_pressed(control_key_state)) {
1908 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1909 }
1910 }
1911 break;
1912
1913 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001914 case 0x33: // 3
1915 case 0x34: // 4
1916 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001917 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001918 case 0x37: // 7
1919 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001920 case VK_OEM_MINUS: // -_
1921 {
1922 seqbuflen = _get_control_character(seqbuf, key_event,
1923 control_key_state);
1924
1925 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1926 // prefix with escape.
1927 if (_is_alt_pressed(control_key_state) &&
1928 !(_is_ctrl_pressed(control_key_state) &&
1929 !_is_shift_pressed(control_key_state))) {
1930 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1931 }
1932 }
1933 break;
1934
Spencer Lowbeb61982015-03-01 15:06:21 -08001935 case 0x41: // a
1936 case 0x42: // b
1937 case 0x43: // c
1938 case 0x44: // d
1939 case 0x45: // e
1940 case 0x46: // f
1941 case 0x47: // g
1942 case 0x48: // h
1943 case 0x49: // i
1944 case 0x4a: // j
1945 case 0x4b: // k
1946 case 0x4c: // l
1947 case 0x4d: // m
1948 case 0x4e: // n
1949 case 0x4f: // o
1950 case 0x50: // p
1951 case 0x51: // q
1952 case 0x52: // r
1953 case 0x53: // s
1954 case 0x54: // t
1955 case 0x55: // u
1956 case 0x56: // v
1957 case 0x57: // w
1958 case 0x58: // x
1959 case 0x59: // y
1960 case 0x5a: // z
1961 {
1962 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1963 control_key_state);
1964
1965 // If Alt is pressed, then prefix with escape.
1966 if (_is_alt_pressed(control_key_state)) {
1967 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1968 }
1969 }
1970 break;
1971
1972 // These virtual key codes are generated by the keys on the
1973 // keypad *when NumLock is on* and *Shift is up*.
1974 MATCH(VK_NUMPAD0, "0");
1975 MATCH(VK_NUMPAD1, "1");
1976 MATCH(VK_NUMPAD2, "2");
1977 MATCH(VK_NUMPAD3, "3");
1978 MATCH(VK_NUMPAD4, "4");
1979 MATCH(VK_NUMPAD5, "5");
1980 MATCH(VK_NUMPAD6, "6");
1981 MATCH(VK_NUMPAD7, "7");
1982 MATCH(VK_NUMPAD8, "8");
1983 MATCH(VK_NUMPAD9, "9");
1984
1985 MATCH(VK_MULTIPLY, "*");
1986 MATCH(VK_ADD, "+");
1987 MATCH(VK_SUBTRACT, "-");
1988 // VK_DECIMAL is generated by the . key on the keypad *when
1989 // NumLock is on* and *Shift is up* and the sequence is not
1990 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1991 // Windows Security screen to come up).
1992 case VK_DECIMAL:
1993 // U.S. English uses '.', Germany German uses ','.
1994 seqbuflen = _get_non_control_char(seqbuf, key_event,
1995 control_key_state);
1996 break;
1997
1998 MATCH_MODIFIER(VK_F1, SS3 "P");
1999 MATCH_MODIFIER(VK_F2, SS3 "Q");
2000 MATCH_MODIFIER(VK_F3, SS3 "R");
2001 MATCH_MODIFIER(VK_F4, SS3 "S");
2002 MATCH_MODIFIER(VK_F5, CSI "15~");
2003 MATCH_MODIFIER(VK_F6, CSI "17~");
2004 MATCH_MODIFIER(VK_F7, CSI "18~");
2005 MATCH_MODIFIER(VK_F8, CSI "19~");
2006 MATCH_MODIFIER(VK_F9, CSI "20~");
2007 MATCH_MODIFIER(VK_F10, CSI "21~");
2008 MATCH_MODIFIER(VK_F11, CSI "23~");
2009 MATCH_MODIFIER(VK_F12, CSI "24~");
2010
2011 MATCH_MODIFIER(VK_F13, CSI "25~");
2012 MATCH_MODIFIER(VK_F14, CSI "26~");
2013 MATCH_MODIFIER(VK_F15, CSI "28~");
2014 MATCH_MODIFIER(VK_F16, CSI "29~");
2015 MATCH_MODIFIER(VK_F17, CSI "31~");
2016 MATCH_MODIFIER(VK_F18, CSI "32~");
2017 MATCH_MODIFIER(VK_F19, CSI "33~");
2018 MATCH_MODIFIER(VK_F20, CSI "34~");
2019
2020 // MATCH_MODIFIER(VK_F21, ???);
2021 // MATCH_MODIFIER(VK_F22, ???);
2022 // MATCH_MODIFIER(VK_F23, ???);
2023 // MATCH_MODIFIER(VK_F24, ???);
2024 }
2025 }
2026
2027#undef MATCH
2028#undef MATCH_MODIFIER
2029#undef MATCH_KEYPAD
2030#undef MATCH_MODIFIER_KEYPAD
2031#undef ESC
2032#undef CSI
2033#undef SS3
2034
2035 const char* out;
2036 size_t outlen;
2037
2038 // Check for output in any of:
2039 // * seqstr is set (and strlen can be used to determine the length).
2040 // * seqbuf and seqbuflen are set
2041 // Fallback to ch from Windows.
2042 if (seqstr != NULL) {
2043 out = seqstr;
2044 outlen = strlen(seqstr);
2045 } else if (seqbuflen > 0) {
2046 out = seqbuf;
2047 outlen = seqbuflen;
2048 } else if (ch != '\0') {
2049 // Use whatever Windows told us it is.
2050 seqbuf[0] = ch;
2051 seqbuflen = 1;
2052 out = seqbuf;
2053 outlen = seqbuflen;
2054 } else {
2055 // No special handling for the virtual key code and Windows isn't
2056 // telling us a character code, then we don't know how to translate
2057 // the key press.
2058 //
2059 // Consume the input and 'continue' to cause us to get a new key
2060 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07002061 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08002062 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08002063 continue;
2064 }
2065
Spencer Low9c8f7462015-11-10 19:17:16 -08002066 // put output wRepeatCount times into g_console_input_buffer
2067 while (key_event->wRepeatCount-- > 0) {
2068 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08002069 }
2070
Spencer Low9c8f7462015-11-10 19:17:16 -08002071 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08002072 }
2073}
2074
2075static DWORD _old_console_mode; // previous GetConsoleMode() result
2076static HANDLE _console_handle; // when set, console mode should be restored
2077
Elliott Hughesa8265792015-11-03 11:18:40 -08002078void stdin_raw_init() {
2079 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08002080 if (in == nullptr) {
2081 return;
2082 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002083
Elliott Hughesa8265792015-11-03 11:18:40 -08002084 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2085 // calling the process Ctrl-C routine (configured by
2086 // SetConsoleCtrlHandler()).
2087 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2088 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2089 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08002090 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2091 ENABLE_LINE_INPUT |
2092 ENABLE_ECHO_INPUT);
2093 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2094 new_console_mode |= ENABLE_WINDOW_INPUT;
2095
2096 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002097 // This really should not fail.
2098 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002099 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002100 }
Elliott Hughesa8265792015-11-03 11:18:40 -08002101
2102 // Once this is set, it means that stdin has been configured for
2103 // reading from and that the old console mode should be restored later.
2104 _console_handle = in;
2105
2106 // Note that we don't need to configure C Runtime line-ending
2107 // translation because _console_read() does not call the C Runtime to
2108 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002109}
2110
Elliott Hughesa8265792015-11-03 11:18:40 -08002111void stdin_raw_restore() {
2112 if (_console_handle != NULL) {
2113 const HANDLE in = _console_handle;
2114 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002115
Elliott Hughesa8265792015-11-03 11:18:40 -08002116 if (!SetConsoleMode(in, _old_console_mode)) {
2117 // This really should not fail.
2118 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002119 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002120 }
2121 }
2122}
2123
Spencer Low55441402015-11-07 17:34:39 -08002124// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2125int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002126 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2127 // If it is a request to read from stdin, and stdin_raw_init() has been
2128 // called, and it successfully configured the console, then read from
2129 // the console using Win32 console APIs and partially emulate a unix
2130 // terminal.
2131 return _console_read(_console_handle, buf, len);
2132 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002133 // On older versions of Windows (definitely 7, definitely not 10),
2134 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002135 // we need to limit the read size.
2136 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002137 len = 4096;
2138 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002139 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002140 // can do LF/CR translation (which is overridable with _setmode()).
2141 // Undefine the macro that is set in sysdeps.h which bans calls to
2142 // plain read() in favor of unix_read() or adb_read().
2143#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002144#undef read
2145 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002146#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002147 }
2148}
Spencer Low6815c072015-05-11 01:08:48 -07002149
2150/**************************************************************************/
2151/**************************************************************************/
2152/***** *****/
2153/***** Unicode support *****/
2154/***** *****/
2155/**************************************************************************/
2156/**************************************************************************/
2157
2158// This implements support for using files with Unicode filenames and for
2159// outputting Unicode text to a Win32 console window. This is inspired from
2160// http://utf8everywhere.org/.
2161//
2162// Background
2163// ----------
2164//
2165// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2166// filenames to APIs such as open(). This works because filenames are largely
2167// opaque 'cookies' (perhaps excluding path separators).
2168//
2169// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2170// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2171// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2172// CreateFile() API is really just a macro that adds the W/A based on whether
2173// the UNICODE preprocessor symbol is defined).
2174//
2175// Options
2176// -------
2177//
2178// Thus, to write a portable program, there are a few options:
2179//
2180// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2181// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2182// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2183// open() API.
2184//
2185// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2186// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2187// potentially touching a lot of code.
2188//
2189// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2190// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2191// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2192// or C Runtime API.
2193//
2194// The Choice
2195// ----------
2196//
Spencer Low50f5bf12015-11-12 15:20:15 -08002197// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2198// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002199// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002200// args that are passed to main() at the beginning of program startup. We also use
2201// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002202// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2203//
2204// Unicode console output
2205// ----------------------
2206//
2207// The way to output Unicode to a Win32 console window is to call
2208// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002209// such as Lucida Console or Consolas, and in the case of East Asian languages
2210// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2211// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2212// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002213//
2214// The problem is getting the C Runtime to make fprintf and related APIs call
2215// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2216// promising, but the various modes have issues:
2217//
2218// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2219// UTF-16 do not display properly.
2220// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2221// totally wrong.
2222// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2223// handler to be called (upon a later I/O call), aborting the process.
2224// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2225// to output nothing.
2226//
2227// So the only solution is to write our own adb_fprintf() that converts UTF-8
2228// to UTF-16 and then calls WriteConsoleW().
2229
2230
Spencer Low6815c072015-05-11 01:08:48 -07002231// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2232// be passed to main().
2233NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2234 narrow_args = new char*[argc + 1];
2235
2236 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002237 std::string arg_narrow;
2238 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2239 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2240 }
2241 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002242 }
2243 narrow_args[argc] = nullptr; // terminate
2244}
2245
2246NarrowArgs::~NarrowArgs() {
2247 if (narrow_args != nullptr) {
2248 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2249 free(*argp);
2250 }
2251 delete[] narrow_args;
2252 narrow_args = nullptr;
2253 }
2254}
2255
2256int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002257 std::wstring path_wide;
2258 if (!android::base::UTF8ToWide(path, &path_wide)) {
2259 return -1;
2260 }
Spencer Low6815c072015-05-11 01:08:48 -07002261 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002262 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002263 } else {
2264 int mode;
2265 va_list args;
2266 va_start(args, options);
2267 mode = va_arg(args, int);
2268 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002269 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002270 }
2271}
2272
2273// Version of stat() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002274int adb_stat(const char* path, struct adb_stat* s) {
Spencer Low6815c072015-05-11 01:08:48 -07002275#pragma push_macro("wstat")
2276// This definition of wstat seems to be missing from <sys/stat.h>.
2277#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
2278#ifdef _USE_32BIT_TIME_T
2279#define wstat _wstat32i64
2280#else
2281#define wstat _wstat64
2282#endif
2283#else
2284// <sys/stat.h> has a function prototype for wstat() that should be available.
2285#endif
2286
Spencer Low50f5bf12015-11-12 15:20:15 -08002287 std::wstring path_wide;
2288 if (!android::base::UTF8ToWide(path, &path_wide)) {
2289 return -1;
2290 }
2291
2292 return wstat(path_wide.c_str(), s);
Spencer Low6815c072015-05-11 01:08:48 -07002293
2294#pragma pop_macro("wstat")
2295}
2296
2297// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002298DIR* adb_opendir(const char* path) {
2299 std::wstring path_wide;
2300 if (!android::base::UTF8ToWide(path, &path_wide)) {
2301 return nullptr;
2302 }
2303
Spencer Low6815c072015-05-11 01:08:48 -07002304 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2305 // the fields, but right now all the callers treat the structure as
2306 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002307 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002308}
2309
2310// Version of readdir() that returns UTF-8 paths.
2311struct dirent* adb_readdir(DIR* dir) {
2312 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2313 struct _wdirent* const went = _wreaddir(wdir);
2314 if (went == nullptr) {
2315 return nullptr;
2316 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002317
Spencer Low6815c072015-05-11 01:08:48 -07002318 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002319 std::string name_utf8;
2320 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2321 return nullptr;
2322 }
Spencer Low6815c072015-05-11 01:08:48 -07002323
2324 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2325 // space for UTF-16 wchar_t's) with UTF-8 char's.
2326 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2327
2328 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2329 // Name too big to fit in existing buffer.
2330 errno = ENOMEM;
2331 return nullptr;
2332 }
2333
2334 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2335 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2336 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2337 // bigger than the caller expects because they expect a dirent structure
2338 // which has a smaller d_name field. Ignore this since the caller should be
2339 // resilient.
2340
2341 // Rewrite the UTF-16 d_name field to UTF-8.
2342 strcpy(ent->d_name, name_utf8.c_str());
2343
2344 return ent;
2345}
2346
2347// Version of closedir() to go with our version of adb_opendir().
2348int adb_closedir(DIR* dir) {
2349 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2350}
2351
2352// Version of unlink() that takes a UTF-8 path.
2353int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002354 std::wstring wpath;
2355 if (!android::base::UTF8ToWide(path, &wpath)) {
2356 return -1;
2357 }
Spencer Low6815c072015-05-11 01:08:48 -07002358
2359 int rc = _wunlink(wpath.c_str());
2360
2361 if (rc == -1 && errno == EACCES) {
2362 /* unlink returns EACCES when the file is read-only, so we first */
2363 /* try to make it writable, then unlink again... */
2364 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2365 if (rc == 0)
2366 rc = _wunlink(wpath.c_str());
2367 }
2368 return rc;
2369}
2370
2371// Version of mkdir() that takes a UTF-8 path.
2372int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002373 std::wstring path_wide;
2374 if (!android::base::UTF8ToWide(path, &path_wide)) {
2375 return -1;
2376 }
2377
2378 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002379}
2380
2381// Version of utime() that takes a UTF-8 path.
2382int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002383 std::wstring path_wide;
2384 if (!android::base::UTF8ToWide(path, &path_wide)) {
2385 return -1;
2386 }
2387
Spencer Low6815c072015-05-11 01:08:48 -07002388 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2389 "utimbuf and _utimbuf should be the same size because they both "
2390 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002391 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002392}
2393
2394// Version of chmod() that takes a UTF-8 path.
2395int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002396 std::wstring path_wide;
2397 if (!android::base::UTF8ToWide(path, &path_wide)) {
2398 return -1;
2399 }
2400
2401 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002402}
2403
Spencer Lowf373c352015-11-15 16:29:36 -08002404// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2405static inline size_t utf8_codepoint_len(uint8_t ch) {
2406 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2407}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002408
Spencer Lowf373c352015-11-15 16:29:36 -08002409namespace internal {
2410
2411// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2412// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2413// remaining_bytes.
2414size_t ParseCompleteUTF8(const char* const first, const char* const last,
2415 std::vector<char>* const remaining_bytes) {
2416 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2417 // Current_after points one byte past the current byte to be examined.
2418 for (const char* current_after = last; current_after != first; --current_after) {
2419 const char* const current = current_after - 1;
2420 const char ch = *current;
2421 const char kHighBit = 0x80u;
2422 const char kTwoHighestBits = 0xC0u;
2423 if ((ch & kHighBit) == 0) { // high bit not set
2424 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2425 // bytes with no leading byte, so return the entire buffer.
2426 break;
2427 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2428 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2429 const size_t bytes_available = last - current;
2430 if (bytes_available < utf8_codepoint_len(ch)) {
2431 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2432 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2433 // to remaining_bytes.
2434 remaining_bytes->insert(remaining_bytes->end(), current, last);
2435 return current - first;
2436 } else {
2437 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2438 // trailing bytes with no lead byte, so return the entire buffer.
2439 break;
2440 }
2441 } else {
2442 // Trailing byte, so keep going backwards looking for the lead byte.
2443 }
2444 }
2445
2446 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2447 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2448 // so that they can be processed.
2449 return last - first;
2450}
2451
2452}
2453
2454// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2455// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2456// This matches the behavior of Linux.
2457// Protected by g_console_output_buffer_lock.
2458static auto& g_console_output_buffer = *new std::vector<char>();
2459
2460// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2461static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2462 HANDLE console) {
2463 const int saved_errno = errno;
2464 std::vector<char> combined_buffer;
2465
2466 // Complete UTF-8 sequences that should be immediately written to the console.
2467 const char* utf8;
2468 size_t utf8_size;
2469
2470 adb_mutex_lock(&g_console_output_buffer_lock);
2471 if (g_console_output_buffer.empty()) {
2472 // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2473 // common case with plain ASCII), parse buf directly.
2474 utf8 = buf;
2475 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
2476 } else {
2477 // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2478 // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
2479 // combined_buffer, then parse it all together.
2480 combined_buffer.swap(g_console_output_buffer);
2481 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
2482
2483 utf8 = combined_buffer.data();
2484 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2485 &g_console_output_buffer);
2486 }
2487 adb_mutex_unlock(&g_console_output_buffer_lock);
2488
2489 std::wstring utf16;
2490
2491 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2492 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2493 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002494 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002495 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002496
2497 // Note that this does not do \n => \r\n translation because that
2498 // doesn't seem necessary for the Windows console. For the Windows
2499 // console \r moves to the beginning of the line and \n moves to a new
2500 // line.
2501
2502 // Flush any stream buffering so that our output is afterwards which
2503 // makes sense because our call is afterwards.
2504 (void)fflush(stream);
2505
2506 // Write UTF-16 to the console.
2507 DWORD written = 0;
Spencer Lowf373c352015-11-15 16:29:36 -08002508 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Low6815c072015-05-11 01:08:48 -07002509 errno = EIO;
2510 return -1;
2511 }
2512
Spencer Lowf373c352015-11-15 16:29:36 -08002513 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2514 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2515 // matches the Linux behavior.
2516 errno = saved_errno;
2517 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002518}
2519
2520// Function prototype because attributes cannot be placed on func definitions.
2521static int _console_vfprintf(const HANDLE console, FILE* stream,
2522 const char *format, va_list ap)
2523 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2524
2525// Internal function to format a UTF-8 string and write it to a Win32 console.
2526// Returns -1 on error.
2527static int _console_vfprintf(const HANDLE console, FILE* stream,
2528 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002529 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002530 std::string output_utf8;
2531
2532 // Format the string.
2533 // This could throw std::bad_alloc.
2534 android::base::StringAppendV(&output_utf8, format, ap);
2535
Spencer Lowf373c352015-11-15 16:29:36 -08002536 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2537 console);
2538 if (result != -1) {
2539 errno = saved_errno;
2540 } else {
2541 // If -1 was returned, errno has been set.
2542 }
2543 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002544}
2545
2546// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2547// Windows console.
2548int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2549 const HANDLE console = _get_console_handle(stream);
2550
2551 // If there is an associated Win32 console, write to it specially,
2552 // otherwise defer to the regular C Runtime, passing it UTF-8.
2553 if (console != NULL) {
2554 return _console_vfprintf(console, stream, format, ap);
2555 } else {
2556 // If vfprintf is a macro, undefine it, so we can call the real
2557 // C Runtime API.
2558#pragma push_macro("vfprintf")
2559#undef vfprintf
2560 return vfprintf(stream, format, ap);
2561#pragma pop_macro("vfprintf")
2562 }
2563}
2564
Spencer Lowf373c352015-11-15 16:29:36 -08002565// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2566int adb_vprintf(const char *format, va_list ap) {
2567 return adb_vfprintf(stdout, format, ap);
2568}
2569
Spencer Low6815c072015-05-11 01:08:48 -07002570// Version of fprintf() that takes UTF-8 and can write Unicode to a
2571// Windows console.
2572int adb_fprintf(FILE *stream, const char *format, ...) {
2573 va_list ap;
2574 va_start(ap, format);
2575 const int result = adb_vfprintf(stream, format, ap);
2576 va_end(ap);
2577
2578 return result;
2579}
2580
2581// Version of printf() that takes UTF-8 and can write Unicode to a
2582// Windows console.
2583int adb_printf(const char *format, ...) {
2584 va_list ap;
2585 va_start(ap, format);
2586 const int result = adb_vfprintf(stdout, format, ap);
2587 va_end(ap);
2588
2589 return result;
2590}
2591
2592// Version of fputs() that takes UTF-8 and can write Unicode to a
2593// Windows console.
2594int adb_fputs(const char* buf, FILE* stream) {
2595 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2596 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002597 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002598 return adb_fprintf(stream, "%s", buf);
2599}
2600
2601// Version of fputc() that takes UTF-8 and can write Unicode to a
2602// Windows console.
2603int adb_fputc(int ch, FILE* stream) {
2604 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002605 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002606 return EOF;
2607 }
2608 // For success, fputc returns the char, cast to unsigned char, then to int.
2609 return static_cast<unsigned char>(ch);
2610}
2611
Spencer Lowf373c352015-11-15 16:29:36 -08002612// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2613int adb_putchar(int ch) {
2614 return adb_fputc(ch, stdout);
2615}
2616
2617// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2618int adb_puts(const char* buf) {
2619 // adb_printf returns -1 on error, which is conveniently the same as EOF
2620 // which puts (and hence adb_puts) should return on error.
2621 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2622 return adb_printf("%s\n", buf);
2623}
2624
Spencer Low6815c072015-05-11 01:08:48 -07002625// Internal function to write UTF-8 to a Win32 console. Returns the number of
2626// items (of length size) written. On error, returns a short item count or 0.
2627static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2628 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002629 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2630 console);
Spencer Low6815c072015-05-11 01:08:48 -07002631 if (result == -1) {
2632 return 0;
2633 }
2634 return result / size;
2635}
2636
2637// Version of fwrite() that takes UTF-8 and can write Unicode to a
2638// Windows console.
2639size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2640 const HANDLE console = _get_console_handle(stream);
2641
2642 // If there is an associated Win32 console, write to it specially,
2643 // otherwise defer to the regular C Runtime, passing it UTF-8.
2644 if (console != NULL) {
2645 return _console_fwrite(ptr, size, nmemb, stream, console);
2646 } else {
2647 // If fwrite is a macro, undefine it, so we can call the real
2648 // C Runtime API.
2649#pragma push_macro("fwrite")
2650#undef fwrite
2651 return fwrite(ptr, size, nmemb, stream);
2652#pragma pop_macro("fwrite")
2653 }
2654}
2655
2656// Version of fopen() that takes a UTF-8 filename and can access a file with
2657// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002658FILE* adb_fopen(const char* path, const char* mode) {
2659 std::wstring path_wide;
2660 if (!android::base::UTF8ToWide(path, &path_wide)) {
2661 return nullptr;
2662 }
2663
2664 std::wstring mode_wide;
2665 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2666 return nullptr;
2667 }
2668
2669 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002670}
2671
Spencer Low50740f52015-09-08 17:13:04 -07002672// Return a lowercase version of the argument. Uses C Runtime tolower() on
2673// each byte which is not UTF-8 aware, and theoretically uses the current C
2674// Runtime locale (which in practice is not changed, so this becomes a ASCII
2675// conversion).
2676static std::string ToLower(const std::string& anycase) {
2677 // copy string
2678 std::string str(anycase);
2679 // transform the copy
2680 std::transform(str.begin(), str.end(), str.begin(), tolower);
2681 return str;
2682}
2683
2684extern "C" int main(int argc, char** argv);
2685
2686// Link with -municode to cause this wmain() to be used as the program
2687// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2688// regular main() with UTF-8 args.
2689extern "C" int wmain(int argc, wchar_t **argv) {
2690 // Convert args from UTF-16 to UTF-8 and pass that to main().
2691 NarrowArgs narrow_args(argc, argv);
2692 return main(argc, narrow_args.data());
2693}
2694
Spencer Low6815c072015-05-11 01:08:48 -07002695// Shadow UTF-8 environment variable name/value pairs that are created from
2696// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07002697// currently updated if putenv, setenv, unsetenv are called. Note that no
2698// thread synchronization is done, but we're called early enough in
2699// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002700static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002701
2702// Make sure that shadow UTF-8 environment variables are setup.
2703static void _ensure_env_setup() {
2704 // If some name/value pairs exist, then we've already done the setup below.
2705 if (g_environ_utf8.size() != 0) {
2706 return;
2707 }
2708
Spencer Low50740f52015-09-08 17:13:04 -07002709 if (_wenviron == nullptr) {
2710 // If _wenviron is null, then -municode probably wasn't used. That
2711 // linker flag will cause the entry point to setup _wenviron. It will
2712 // also require an implementation of wmain() (which we provide above).
2713 fatal("_wenviron is not set, did you link with -municode?");
2714 }
2715
Spencer Low6815c072015-05-11 01:08:48 -07002716 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2717 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2718 // to use the D() macro here because that tracing only works if the
2719 // ADB_TRACE environment variable is setup, but that env var can't be read
2720 // until this code completes.
2721 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2722 wchar_t* const equal = wcschr(*env, L'=');
2723 if (equal == nullptr) {
2724 // Malformed environment variable with no equal sign. Shouldn't
2725 // really happen, but we should be resilient to this.
2726 continue;
2727 }
2728
Spencer Low50f5bf12015-11-12 15:20:15 -08002729 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2730 // var because the program might never even read this particular variable.
2731 std::string name_utf8;
2732 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2733 continue;
2734 }
2735
Spencer Low50740f52015-09-08 17:13:04 -07002736 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002737 name_utf8 = ToLower(name_utf8);
2738
2739 std::string value_utf8;
2740 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2741 continue;
2742 }
2743
2744 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002745
Spencer Low50740f52015-09-08 17:13:04 -07002746 // Don't overwrite a previus env var with the same name. In reality,
2747 // the system probably won't let two env vars with the same name exist
2748 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002749 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002750 }
2751}
2752
2753// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002754// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002755char* adb_getenv(const char* name) {
2756 _ensure_env_setup();
2757
Spencer Low50740f52015-09-08 17:13:04 -07002758 // Case-insensitive search by searching for lowercase name in a map of
2759 // lowercase names.
2760 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002761 if (it == g_environ_utf8.end()) {
2762 return nullptr;
2763 }
2764
2765 return it->second;
2766}
2767
2768// Version of getcwd() that returns the current working directory in UTF-8.
2769char* adb_getcwd(char* buf, int size) {
2770 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2771 if (wbuf == nullptr) {
2772 return nullptr;
2773 }
2774
Spencer Low50f5bf12015-11-12 15:20:15 -08002775 std::string buf_utf8;
2776 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002777 free(wbuf);
2778 wbuf = nullptr;
2779
Spencer Low50f5bf12015-11-12 15:20:15 -08002780 if (!narrow_result) {
2781 return nullptr;
2782 }
2783
Spencer Low6815c072015-05-11 01:08:48 -07002784 // If size was specified, make sure all the chars will fit.
2785 if (size != 0) {
2786 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2787 errno = ERANGE;
2788 return nullptr;
2789 }
2790 }
2791
2792 // If buf was not specified, allocate storage.
2793 if (buf == nullptr) {
2794 if (size == 0) {
2795 size = buf_utf8.length() + 1;
2796 }
2797 buf = reinterpret_cast<char*>(malloc(size));
2798 if (buf == nullptr) {
2799 return nullptr;
2800 }
2801 }
2802
2803 // Destination buffer was allocated with enough space, or we've already
2804 // checked an existing buffer size for enough space.
2805 strcpy(buf, buf_utf8.c_str());
2806
2807 return buf;
2808}