blob: bc09fdcfbc0a5efe547ebde8cc8da135cc0c933d [file] [log] [blame]
Dan Albert33134262015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
30#include <string>
Spencer Lowcf4ff642015-05-11 01:08:48 -070031#include <unordered_map>
Josh Gaoaddab3d2016-02-16 17:34:53 -080032#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070033
Elliott Hughesd48dbd82015-07-24 11:35:40 -070034#include <cutils/sockets.h>
35
David Pursell5f787ed2016-01-27 08:52:53 -080036#include <android-base/errors.h>
Elliott Hughes4f713192015-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 Low5200c662015-07-30 23:07:55 -070041
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#include "adb.h"
Josh Gaoaddab3d2016-02-16 17:34:53 -080043#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080044
45extern void fatal(const char *fmt, ...);
46
Elliott Hughesa2f2e562015-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 Hughesa2f2e562015-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 Hughesa2f2e562015-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 Hughesa2f2e562015-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 Hughesa2f2e562015-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 Hughesa2f2e562015-04-16 16:47:02 -070087};
88
Josh Gao56e9bb92016-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 Projectdd7bc332009-03-03 19:32:55 -080093
Spencer Low2122c7a2015-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 Cui7a3f8d62015-09-02 17:44:28 -0700104 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800105 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700106 }
107 }
108}
109
The Android Open Source Projectdd7bc332009-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 Lowd21dc822015-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 Lowcf4ff642015-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 Projectdd7bc332009-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 Cui7a3f8d62015-09-02 17:44:28 -0700145 D("load_file: could not allocate %ld bytes", file_size );
The Android Open Source Projectdd7bc332009-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 Cui7a3f8d62015-09-02 17:44:28 -0700153 D("load_file: could not read %ld bytes from '%s'", file_size, fn);
The Android Open Source Projectdd7bc332009-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 Projectdd7bc332009-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 Projectdd7bc332009-03-03 19:32:55 -0800182 } u;
183
The Android Open Source Projectdd7bc332009-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 Projectdd7bc332009-03-03 19:32:55 -0800192
Josh Gao8443fd92016-02-17 16:45:39 -0800193#define WIN32_FH_BASE 2048
Josh Gaod1e23002016-04-18 11:09:28 -0700194#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800195
196static adb_mutex_t _win32_lock;
197static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700198static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800199
200static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700201_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800202{
203 FH f;
204
205 fd -= WIN32_FH_BASE;
206
Spencer Lowc3211552015-07-24 15:38:19 -0700207 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700208 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700209 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800210 errno = EBADF;
211 return NULL;
212 }
213
214 f = &_win32_fhs[fd];
215
216 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700217 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700218 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800219 errno = EBADF;
220 return NULL;
221 }
222
223 return f;
224}
225
226
227static int
228_fh_to_int( FH f )
229{
230 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
231 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
232
233 return -1;
234}
235
236static FH
237_fh_alloc( FHClass clazz )
238{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800239 FH f = NULL;
240
241 adb_mutex_lock( &_win32_lock );
242
Josh Gao8443fd92016-02-17 16:45:39 -0800243 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
244 if (_win32_fhs[i].clazz == NULL) {
245 f = &_win32_fhs[i];
246 _win32_fh_next = i + 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800247 goto Exit;
248 }
249 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700250 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowc3211552015-07-24 15:38:19 -0700251 errno = EMFILE; // Too many open files
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800252Exit:
253 if (f) {
Spencer Lowc3211552015-07-24 15:38:19 -0700254 f->clazz = clazz;
255 f->used = 1;
256 f->eof = 0;
257 f->name[0] = '\0';
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 clazz->_fh_init(f);
259 }
260 adb_mutex_unlock( &_win32_lock );
261 return f;
262}
263
264
265static int
266_fh_close( FH f )
267{
Spencer Lowc3211552015-07-24 15:38:19 -0700268 // Use lock so that closing only happens once and so that _fh_alloc can't
269 // allocate a FH that we're in the middle of closing.
270 adb_mutex_lock(&_win32_lock);
Josh Gao8443fd92016-02-17 16:45:39 -0800271
272 int offset = f - _win32_fhs;
273 if (_win32_fh_next > offset) {
274 _win32_fh_next = offset;
275 }
276
Spencer Lowc3211552015-07-24 15:38:19 -0700277 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800278 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700279 f->name[0] = '\0';
280 f->eof = 0;
281 f->used = 0;
282 f->clazz = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800283 }
Spencer Lowc3211552015-07-24 15:38:19 -0700284 adb_mutex_unlock(&_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800285 return 0;
286}
287
Spencer Low5200c662015-07-30 23:07:55 -0700288// Deleter for unique_fh.
289class fh_deleter {
290 public:
291 void operator()(struct FHRec_* fh) {
292 // We're called from a destructor and destructors should not overwrite
293 // errno because callers may do:
294 // errno = EBLAH;
295 // return -1; // calls destructor, which should not overwrite errno
296 const int saved_errno = errno;
297 _fh_close(fh);
298 errno = saved_errno;
299 }
300};
301
302// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
303typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
304
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800305/**************************************************************************/
306/**************************************************************************/
307/***** *****/
308/***** file-based descriptor handling *****/
309/***** *****/
310/**************************************************************************/
311/**************************************************************************/
312
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700313static void _fh_file_init( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800314 f->fh_handle = INVALID_HANDLE_VALUE;
315}
316
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700317static int _fh_file_close( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800318 CloseHandle( f->fh_handle );
319 f->fh_handle = INVALID_HANDLE_VALUE;
320 return 0;
321}
322
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700323static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800324 DWORD read_bytes;
325
326 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700327 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800328 errno = EIO;
329 return -1;
330 } else if (read_bytes < (DWORD)len) {
331 f->eof = 1;
332 }
333 return (int)read_bytes;
334}
335
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700336static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800337 DWORD wrote_bytes;
338
339 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700340 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800341 errno = EIO;
342 return -1;
343 } else if (wrote_bytes < (DWORD)len) {
344 f->eof = 1;
345 }
346 return (int)wrote_bytes;
347}
348
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700349static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800350 DWORD method;
351 DWORD result;
352
353 switch (origin)
354 {
355 case SEEK_SET: method = FILE_BEGIN; break;
356 case SEEK_CUR: method = FILE_CURRENT; break;
357 case SEEK_END: method = FILE_END; break;
358 default:
359 errno = EINVAL;
360 return -1;
361 }
362
363 result = SetFilePointer( f->fh_handle, pos, NULL, method );
364 if (result == INVALID_SET_FILE_POINTER) {
365 errno = EIO;
366 return -1;
367 } else {
368 f->eof = 0;
369 }
370 return (int)result;
371}
372
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800373
374/**************************************************************************/
375/**************************************************************************/
376/***** *****/
377/***** file-based descriptor handling *****/
378/***** *****/
379/**************************************************************************/
380/**************************************************************************/
381
382int adb_open(const char* path, int options)
383{
384 FH f;
385
386 DWORD desiredAccess = 0;
387 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
388
389 switch (options) {
390 case O_RDONLY:
391 desiredAccess = GENERIC_READ;
392 break;
393 case O_WRONLY:
394 desiredAccess = GENERIC_WRITE;
395 break;
396 case O_RDWR:
397 desiredAccess = GENERIC_READ | GENERIC_WRITE;
398 break;
399 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700400 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800401 errno = EINVAL;
402 return -1;
403 }
404
405 f = _fh_alloc( &_fh_file_class );
406 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800407 return -1;
408 }
409
Spencer Lowd21dc822015-11-12 15:20:15 -0800410 std::wstring path_wide;
411 if (!android::base::UTF8ToWide(path, &path_wide)) {
412 return -1;
413 }
414 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700415 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800416
417 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700418 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700420 D( "adb_open: could not open '%s': ", path );
421 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700423 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424 errno = ENOENT;
425 return -1;
426
427 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700428 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429 errno = ENOTDIR;
430 return -1;
431
432 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800433 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434 errno = ENOENT;
435 return -1;
436 }
437 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800438
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700440 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800441 return _fh_to_int(f);
442}
443
444/* ignore mode on Win32 */
445int adb_creat(const char* path, int mode)
446{
447 FH f;
448
449 f = _fh_alloc( &_fh_file_class );
450 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800451 return -1;
452 }
453
Spencer Lowd21dc822015-11-12 15:20:15 -0800454 std::wstring path_wide;
455 if (!android::base::UTF8ToWide(path, &path_wide)) {
456 return -1;
457 }
458 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700459 FILE_SHARE_READ | FILE_SHARE_WRITE,
460 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
461 NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462
463 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700464 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800465 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700466 D( "adb_creat: could not open '%s': ", path );
467 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800468 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700469 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800470 errno = ENOENT;
471 return -1;
472
473 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700474 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475 errno = ENOTDIR;
476 return -1;
477
478 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800479 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800480 errno = ENOENT;
481 return -1;
482 }
483 }
484 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700485 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800486 return _fh_to_int(f);
487}
488
489
490int adb_read(int fd, void* buf, int len)
491{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700492 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493
494 if (f == NULL) {
495 return -1;
496 }
497
498 return f->clazz->_fh_read( f, buf, len );
499}
500
501
502int adb_write(int fd, const void* buf, int len)
503{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700504 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505
506 if (f == NULL) {
507 return -1;
508 }
509
510 return f->clazz->_fh_write(f, buf, len);
511}
512
513
514int adb_lseek(int fd, int pos, int where)
515{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700516 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517
518 if (!f) {
519 return -1;
520 }
521
522 return f->clazz->_fh_lseek(f, pos, where);
523}
524
525
526int adb_close(int fd)
527{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700528 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800529
530 if (!f) {
531 return -1;
532 }
533
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700534 D( "adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800535 _fh_close(f);
536 return 0;
537}
538
Spencer Low0a796002015-10-18 16:45:09 -0700539// Overrides strerror() to handle error codes not supported by the Windows C
540// Runtime (MSVCRT.DLL).
541char* adb_strerror(int err) {
542 // sysdeps.h defines strerror to adb_strerror, but in this function, we
543 // want to call the real C Runtime strerror().
544#pragma push_macro("strerror")
545#undef strerror
546 const int saved_err = errno; // Save because we overwrite it later.
547
548 // Lookup the string for an unknown error.
549 char* errmsg = strerror(-1);
Elliott Hughes6d929972015-10-27 13:40:35 -0700550 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low0a796002015-10-18 16:45:09 -0700551
552 // Lookup the string for this error to see if the C Runtime has it.
553 errmsg = strerror(err);
Elliott Hughes6d929972015-10-27 13:40:35 -0700554 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low0a796002015-10-18 16:45:09 -0700555 // The CRT returned an error message and it is different than the error
556 // message for an unknown error, so it is probably valid, so use it.
557 } else {
558 // Check if we have a string for this error code.
559 const char* custom_msg = nullptr;
560 switch (err) {
561#pragma push_macro("ERR")
562#undef ERR
563#define ERR(errnum, desc) case errnum: custom_msg = desc; break
564 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
565 // Note that these cannot be longer than 94 characters because we
566 // pass this to _strerror() which has that requirement.
567 ERR(ECONNRESET, "Connection reset by peer");
568 ERR(EHOSTUNREACH, "No route to host");
569 ERR(ENETDOWN, "Network is down");
570 ERR(ENETRESET, "Network dropped connection because of reset");
571 ERR(ENOBUFS, "No buffer space available");
572 ERR(ENOPROTOOPT, "Protocol not available");
573 ERR(ENOTCONN, "Transport endpoint is not connected");
574 ERR(ENOTSOCK, "Socket operation on non-socket");
575 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
576#pragma pop_macro("ERR")
577 }
578
579 if (custom_msg != nullptr) {
580 // Use _strerror() to write our string into the writable per-thread
581 // buffer used by strerror()/_strerror(). _strerror() appends the
582 // msg for the current value of errno, so set errno to a consistent
583 // value for every call so that our code-path is always the same.
584 errno = 0;
585 errmsg = _strerror(custom_msg);
586 const size_t custom_msg_len = strlen(custom_msg);
587 // Just in case _strerror() returned a read-only string, check if
588 // the returned string starts with our custom message because that
589 // implies that the string is not read-only.
590 if ((errmsg != nullptr) &&
591 !strncmp(custom_msg, errmsg, custom_msg_len)) {
592 // _strerror() puts other text after our custom message, so
593 // remove that by terminating after our message.
594 errmsg[custom_msg_len] = '\0';
595 } else {
596 // For some reason nullptr was returned or a pointer to a
597 // read-only string was returned, so fallback to whatever
598 // strerror() can muster (probably "Unknown error" or some
599 // generic CRT error string).
600 errmsg = strerror(err);
601 }
602 } else {
603 // We don't have a custom message, so use whatever strerror(err)
604 // returned earlier.
605 }
606 }
607
608 errno = saved_err; // restore
609
610 return errmsg;
611#pragma pop_macro("strerror")
612}
613
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800614/**************************************************************************/
615/**************************************************************************/
616/***** *****/
617/***** socket-based file descriptors *****/
618/***** *****/
619/**************************************************************************/
620/**************************************************************************/
621
Spencer Lowf055c192015-01-25 14:40:16 -0800622#undef setsockopt
623
Spencer Low5200c662015-07-30 23:07:55 -0700624static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700625 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
626 // lot of POSIX and socket error codes, some of the resulting error codes
627 // are mapped to strings by adb_strerror() above.
Spencer Low5200c662015-07-30 23:07:55 -0700628 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800629 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700630 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
631 // case WSAEINTR: errno = EINTR; break;
632 case WSAEFAULT: errno = EFAULT; break;
633 case WSAEINVAL: errno = EINVAL; break;
634 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700635 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
636 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
637 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800638 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700639 case WSAENOTSOCK: errno = ENOTSOCK; break;
640 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
641 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
642 case WSAENETDOWN: errno = ENETDOWN; break;
643 case WSAENETRESET: errno = ENETRESET; break;
644 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
645 // to use EPIPE for these situations and there are some callers that look
646 // for EPIPE.
647 case WSAECONNABORTED: errno = EPIPE; break;
648 case WSAECONNRESET: errno = ECONNRESET; break;
649 case WSAENOBUFS: errno = ENOBUFS; break;
650 case WSAENOTCONN: errno = ENOTCONN; break;
651 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
652 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
653 // considerations: Reportedly send() can return zero on timeout, and POSIX
654 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
655 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
656 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800657 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700659 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700660 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800661 }
662}
663
Josh Gaoaddab3d2016-02-16 17:34:53 -0800664extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
665 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
666 int skipped = 0;
667 std::vector<WSAPOLLFD> sockets;
668 std::vector<adb_pollfd*> original;
669 for (size_t i = 0; i < nfds; ++i) {
670 FH fh = _fh_from_int(fds[i].fd, __func__);
671 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
672 D("adb_poll received bad FD %d", fds[i].fd);
673 fds[i].revents = POLLNVAL;
674 ++skipped;
675 } else {
676 WSAPOLLFD wsapollfd = {
677 .fd = fh->u.socket,
678 .events = static_cast<short>(fds[i].events)
679 };
680 sockets.push_back(wsapollfd);
681 original.push_back(&fds[i]);
682 }
Spencer Low5200c662015-07-30 23:07:55 -0700683 }
Josh Gaoaddab3d2016-02-16 17:34:53 -0800684
685 if (sockets.empty()) {
686 return skipped;
687 }
688
689 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
690 if (result == SOCKET_ERROR) {
691 _socket_set_errno(WSAGetLastError());
692 return -1;
693 }
694
695 // Map the results back onto the original set.
696 for (size_t i = 0; i < sockets.size(); ++i) {
697 original[i]->revents = sockets[i].revents;
698 }
699
700 // WSAPoll appears to return the number of unique FDs with avaiable events, instead of how many
701 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
702 // to do. Ignore its result and calculate the proper return value.
703 result = 0;
704 for (size_t i = 0; i < nfds; ++i) {
705 if (fds[i].revents != 0) {
706 ++result;
707 }
708 }
709 return result;
710}
711
712static void _fh_socket_init(FH f) {
713 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800714 f->mask = 0;
715}
716
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700717static int _fh_socket_close( FH f ) {
Spencer Low5200c662015-07-30 23:07:55 -0700718 if (f->fh_socket != INVALID_SOCKET) {
719 /* gently tell any peer that we're closing the socket */
720 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
721 // If the socket is not connected, this returns an error. We want to
722 // minimize logging spam, so don't log these errors for now.
723#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700724 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800725 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700726#endif
727 }
728 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gaoc1d252b2016-02-18 13:43:55 -0800729 // Don't set errno here, since adb_close will ignore it.
730 const DWORD err = WSAGetLastError();
731 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700732 }
733 f->fh_socket = INVALID_SOCKET;
734 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 f->mask = 0;
736 return 0;
737}
738
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700739static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800740 errno = EPIPE;
741 return -1;
742}
743
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700744static int _fh_socket_read(FH f, void* buf, int len) {
745 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800746 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700747 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700748 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
749 // that to reduce spam and confusion.
750 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700751 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800752 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700753 }
Spencer Low5200c662015-07-30 23:07:55 -0700754 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800755 result = -1;
756 }
757 return result;
758}
759
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700760static int _fh_socket_write(FH f, const void* buf, int len) {
761 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800762 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700763 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700764 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
765 // that to reduce spam and confusion.
766 if (err != WSAEWOULDBLOCK) {
767 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800768 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700769 }
Spencer Low5200c662015-07-30 23:07:55 -0700770 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800771 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700772 } else {
773 // According to https://code.google.com/p/chromium/issues/detail?id=27870
774 // Winsock Layered Service Providers may cause this.
775 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
776 << f->name << ", but " << result
777 << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800778 }
779 return result;
780}
781
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800782/**************************************************************************/
783/**************************************************************************/
784/***** *****/
785/***** replacement for libs/cutils/socket_xxxx.c *****/
786/***** *****/
787/**************************************************************************/
788/**************************************************************************/
789
790#include <winsock2.h>
791
792static int _winsock_init;
793
794static void
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800795_init_winsock( void )
796{
Spencer Low5200c662015-07-30 23:07:55 -0700797 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Low87e97ee2015-08-12 18:19:16 -0700798 // to WSAStartup() which offers no real benefit.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800799 if (!_winsock_init) {
800 WSADATA wsaData;
801 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
802 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800803 fatal("adb: could not initialize Winsock: %s",
804 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800805 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800806 _winsock_init = 1;
Spencer Low87e97ee2015-08-12 18:19:16 -0700807
808 // Note that we do not call atexit() to register WSACleanup to be called
809 // at normal process termination because:
810 // 1) When exit() is called, there are still threads actively using
811 // Winsock because we don't cleanly shutdown all threads, so it
812 // doesn't make sense to call WSACleanup() and may cause problems
813 // with those threads.
814 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
815 // calls WSACleanup() which tries to unload a DLL, which tries to
816 // grab the LoaderLock. This conflicts with the device_poll_thread
817 // which holds the LoaderLock because AdbWinApi.dll calls
818 // setupapi.dll which tries to load wintrust.dll which tries to load
819 // crypt32.dll which calls atexit() which tries to acquire the C
820 // Runtime lock that the other thread holds.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800821 }
822}
823
Spencer Low677fb432015-09-29 15:05:29 -0700824// Map a socket type to an explicit socket protocol instead of using the socket
825// protocol of 0. Explicit socket protocols are used by most apps and we should
826// do the same to reduce the chance of exercising uncommon code-paths that might
827// have problems or that might load different Winsock service providers that
828// have problems.
829static int GetSocketProtocolFromSocketType(int type) {
830 switch (type) {
831 case SOCK_STREAM:
832 return IPPROTO_TCP;
833 case SOCK_DGRAM:
834 return IPPROTO_UDP;
835 default:
836 LOG(FATAL) << "Unknown socket type: " << type;
837 return 0;
838 }
839}
840
Spencer Low5200c662015-07-30 23:07:55 -0700841int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800842 struct sockaddr_in addr;
Josh Gaoc1d252b2016-02-18 13:43:55 -0800843 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844
Josh Gaoc1d252b2016-02-18 13:43:55 -0800845 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700846 if (!f) {
847 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700849 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800850
Josh Gaoc1d252b2016-02-18 13:43:55 -0800851 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800852
853 memset(&addr, 0, sizeof(addr));
854 addr.sin_family = AF_INET;
855 addr.sin_port = htons(port);
856 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
857
Spencer Low677fb432015-09-29 15:05:29 -0700858 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gaoc1d252b2016-02-18 13:43:55 -0800859 if (s == INVALID_SOCKET) {
860 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700861 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gaoc1d252b2016-02-18 13:43:55 -0800862 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700863 D("%s", error->c_str());
Josh Gaoc1d252b2016-02-18 13:43:55 -0800864 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700865 return -1;
866 }
867 f->fh_socket = s;
868
Josh Gaoc1d252b2016-02-18 13:43:55 -0800869 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-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",
Josh Gaoc1d252b2016-02-18 13:43:55 -0800873 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
874 android::base::SystemErrorCodeToString(err).c_str());
875 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
876 error->c_str());
877 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800878 return -1;
879 }
880
Spencer Low5200c662015-07-30 23:07:55 -0700881 const int fd = _fh_to_int(f.get());
Josh Gaoc1d252b2016-02-18 13:43:55 -0800882 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
883 port);
884 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700885 f.release();
886 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800887}
888
889#define LISTEN_BACKLOG 4
890
Spencer Low5200c662015-07-30 23:07:55 -0700891// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gaoc1d252b2016-02-18 13:43:55 -0800892static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800893 struct sockaddr_in addr;
Josh Gaoc1d252b2016-02-18 13:43:55 -0800894 SOCKET s;
895 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800896
Josh Gaoc1d252b2016-02-18 13:43:55 -0800897 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800898 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700899 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800900 return -1;
901 }
902
Josh Gaoc1d252b2016-02-18 13:43:55 -0800903 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800904
905 memset(&addr, 0, sizeof(addr));
906 addr.sin_family = AF_INET;
907 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700908 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800909
Spencer Low5200c662015-07-30 23:07:55 -0700910 // TODO: Consider using dual-stack socket that can simultaneously listen on
911 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700912 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700913 if (s == INVALID_SOCKET) {
Josh Gaoc1d252b2016-02-18 13:43:55 -0800914 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700915 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gaoc1d252b2016-02-18 13:43:55 -0800916 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700917 D("%s", error->c_str());
Josh Gaoc1d252b2016-02-18 13:43:55 -0800918 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700919 return -1;
920 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800921
922 f->fh_socket = s;
923
Spencer Lowbf7c6052015-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 Projectdd7bc332009-03-03 19:32:55 -0800926 n = 1;
Josh Gaoc1d252b2016-02-18 13:43:55 -0800927 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
928 const DWORD err = WSAGetLastError();
929 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
930 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700931 D("%s", error->c_str());
Josh Gaoc1d252b2016-02-18 13:43:55 -0800932 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700933 return -1;
934 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800935
Josh Gaoc1d252b2016-02-18 13:43:55 -0800936 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700937 // Save err just in case inet_ntoa() or ntohs() changes the last error.
938 const DWORD err = WSAGetLastError();
Josh Gaoc1d252b2016-02-18 13:43:55 -0800939 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
940 ntohs(addr.sin_port),
941 android::base::SystemErrorCodeToString(err).c_str());
942 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
943 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800944 return -1;
945 }
946 if (type == SOCK_STREAM) {
Spencer Low5200c662015-07-30 23:07:55 -0700947 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Josh Gaoc1d252b2016-02-18 13:43:55 -0800948 const DWORD err = WSAGetLastError();
949 *error = android::base::StringPrintf(
950 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
951 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
952 error->c_str());
953 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800954 return -1;
955 }
956 }
Spencer Low5200c662015-07-30 23:07:55 -0700957 const int fd = _fh_to_int(f.get());
Josh Gaoc1d252b2016-02-18 13:43:55 -0800958 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
959 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
960 port);
961 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700962 f.release();
963 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800964}
965
Spencer Low5200c662015-07-30 23:07:55 -0700966int network_loopback_server(int port, int type, std::string* error) {
967 return _network_server(port, type, INADDR_LOOPBACK, error);
968}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800969
Spencer Low5200c662015-07-30 23:07:55 -0700970int network_inaddr_any_server(int port, int type, std::string* error) {
971 return _network_server(port, type, INADDR_ANY, error);
972}
973
974int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
975 unique_fh f(_fh_alloc(&_fh_socket_class));
976 if (!f) {
977 *error = strerror(errno);
978 return -1;
979 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800980
Elliott Hughes381cfa92015-07-23 17:12:58 -0700981 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800982
Spencer Low5200c662015-07-30 23:07:55 -0700983 struct addrinfo hints;
984 memset(&hints, 0, sizeof(hints));
985 hints.ai_family = AF_UNSPEC;
986 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700987 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700988
989 char port_str[16];
990 snprintf(port_str, sizeof(port_str), "%d", port);
991
992 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700993
994#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gaoc1d252b2016-02-18 13:43:55 -0800995// TODO: When the Android SDK tools increases the Windows system
996// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700997#else
Josh Gaoc1d252b2016-02-18 13:43:55 -0800998// Otherwise, keep using getaddrinfo(), or do runtime API detection
999// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -07001000#endif
Spencer Low5200c662015-07-30 23:07:55 -07001001 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gaoc1d252b2016-02-18 13:43:55 -08001002 const DWORD err = WSAGetLastError();
1003 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
1004 host.c_str(), port_str,
1005 android::base::SystemErrorCodeToString(err).c_str());
1006
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001007 D("%s", error->c_str());
Josh Gaoc1d252b2016-02-18 13:43:55 -08001008 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001009 return -1;
1010 }
Josh Gaoc1d252b2016-02-18 13:43:55 -08001011 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -07001012 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001013
Spencer Low5200c662015-07-30 23:07:55 -07001014 // TODO: Try all the addresses if there's more than one? This just uses
1015 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
1016 // which tries all addresses, takes a timeout and more.
Josh Gaoc1d252b2016-02-18 13:43:55 -08001017 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
1018 if (s == INVALID_SOCKET) {
1019 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -07001020 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gaoc1d252b2016-02-18 13:43:55 -08001021 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001022 D("%s", error->c_str());
Josh Gaoc1d252b2016-02-18 13:43:55 -08001023 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001024 return -1;
1025 }
1026 f->fh_socket = s;
1027
Spencer Low5200c662015-07-30 23:07:55 -07001028 // TODO: Implement timeouts for Windows. Seems like the default in theory
1029 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gaoc1d252b2016-02-18 13:43:55 -08001030 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -07001031 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gaoc1d252b2016-02-18 13:43:55 -08001032 const DWORD err = WSAGetLastError();
1033 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
1034 android::base::SystemErrorCodeToString(err).c_str());
1035 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
1036 port_str, error->c_str());
1037 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001038 return -1;
1039 }
1040
Spencer Low5200c662015-07-30 23:07:55 -07001041 const int fd = _fh_to_int(f.get());
Josh Gaoc1d252b2016-02-18 13:43:55 -08001042 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
1043 port);
1044 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
1045 fd);
Spencer Low5200c662015-07-30 23:07:55 -07001046 f.release();
1047 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001048}
1049
1050#undef accept
1051int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
1052{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001053 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001054
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001055 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001056 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -07001057 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001058 return -1;
1059 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001060
Spencer Low5200c662015-07-30 23:07:55 -07001061 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001062 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001063 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1064 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001065 return -1;
1066 }
1067
1068 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1069 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001070 const DWORD err = WSAGetLastError();
Spencer Low5200c662015-07-30 23:07:55 -07001071 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursell5f787ed2016-01-27 08:52:53 -08001072 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low5200c662015-07-30 23:07:55 -07001073 _socket_set_errno( err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001074 return -1;
1075 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001076
Spencer Low5200c662015-07-30 23:07:55 -07001077 const int fd = _fh_to_int(fh.get());
1078 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001079 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low5200c662015-07-30 23:07:55 -07001080 fh.release();
1081 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001082}
1083
1084
Spencer Lowf055c192015-01-25 14:40:16 -08001085int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001086{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001087 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001088
Spencer Lowf055c192015-01-25 14:40:16 -08001089 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001090 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001091 errno = EBADF;
1092 return -1;
1093 }
Spencer Low677fb432015-09-29 15:05:29 -07001094
1095 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1096 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1097 // auto-tuning.
1098
Spencer Low5200c662015-07-30 23:07:55 -07001099 int result = setsockopt( fh->fh_socket, level, optname,
1100 reinterpret_cast<const char*>(optval), optlen );
1101 if ( result == SOCKET_ERROR ) {
1102 const DWORD err = WSAGetLastError();
David Pursell5f787ed2016-01-27 08:52:53 -08001103 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1104 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001105 _socket_set_errno( err );
1106 result = -1;
1107 }
1108 return result;
1109}
1110
Josh Gaoaddab3d2016-02-16 17:34:53 -08001111int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1112 FH fh = _fh_from_int(fd, __func__);
1113
1114 if (!fh || fh->clazz != &_fh_socket_class) {
1115 D("adb_getsockname: invalid fd %d", fd);
1116 errno = EBADF;
1117 return -1;
1118 }
1119
1120 int result = getsockname(fh->fh_socket, sockaddr, optlen);
1121 if (result == SOCKET_ERROR) {
1122 const DWORD err = WSAGetLastError();
1123 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1124 android::base::SystemErrorCodeToString(err).c_str());
1125 _socket_set_errno(err);
1126 result = -1;
1127 }
1128 return result;
1129}
Spencer Low5200c662015-07-30 23:07:55 -07001130
1131int adb_shutdown(int fd)
1132{
1133 FH f = _fh_from_int(fd, __func__);
1134
1135 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001136 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001137 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001138 return -1;
1139 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001140
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001141 D( "adb_shutdown: %s", f->name);
Spencer Low5200c662015-07-30 23:07:55 -07001142 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1143 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001144 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001145 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001146 _socket_set_errno(err);
1147 return -1;
1148 }
1149 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001150}
1151
Josh Gaoaddab3d2016-02-16 17:34:53 -08001152// Emulate socketpair(2) by binding and connecting to a socket.
1153int adb_socketpair(int sv[2]) {
1154 int server = -1;
1155 int client = -1;
1156 int accepted = -1;
1157 sockaddr_storage addr_storage;
1158 socklen_t addr_len = sizeof(addr_storage);
1159 sockaddr_in* addr = nullptr;
1160 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001161
Josh Gaoaddab3d2016-02-16 17:34:53 -08001162 server = network_loopback_server(0, SOCK_STREAM, &error);
1163 if (server < 0) {
1164 D("adb_socketpair: failed to create server: %s", error.c_str());
1165 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001166 }
1167
Josh Gaoaddab3d2016-02-16 17:34:53 -08001168 if (adb_getsockname(server, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1169 D("adb_socketpair: adb_getsockname failed: %s", strerror(errno));
1170 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171 }
1172
Josh Gaoaddab3d2016-02-16 17:34:53 -08001173 if (addr_storage.ss_family != AF_INET) {
1174 D("adb_socketpair: unknown address family received: %d", addr_storage.ss_family);
1175 errno = ECONNABORTED;
1176 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001177 }
1178
Josh Gaoaddab3d2016-02-16 17:34:53 -08001179 addr = reinterpret_cast<sockaddr_in*>(&addr_storage);
1180 D("adb_socketpair: bound on port %d", ntohs(addr->sin_port));
1181 client = network_loopback_client(ntohs(addr->sin_port), SOCK_STREAM, &error);
1182 if (client < 0) {
1183 D("adb_socketpair: failed to connect client: %s", error.c_str());
1184 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185 }
1186
Josh Gaoaddab3d2016-02-16 17:34:53 -08001187 accepted = adb_socket_accept(server, nullptr, nullptr);
1188 if (accepted < 0) {
Josh Gaoc1d252b2016-02-18 13:43:55 -08001189 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoaddab3d2016-02-16 17:34:53 -08001190 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001191 }
Josh Gaoaddab3d2016-02-16 17:34:53 -08001192 adb_close(server);
1193 sv[0] = client;
1194 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001195 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001196
Josh Gaoaddab3d2016-02-16 17:34:53 -08001197fail:
1198 if (server >= 0) {
1199 adb_close(server);
1200 }
1201 if (client >= 0) {
1202 adb_close(client);
1203 }
1204 if (accepted >= 0) {
1205 adb_close(accepted);
1206 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001207 return -1;
1208}
1209
Josh Gaoaddab3d2016-02-16 17:34:53 -08001210bool set_file_block_mode(int fd, bool block) {
1211 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001212
Josh Gaoaddab3d2016-02-16 17:34:53 -08001213 if (!fh || !fh->used) {
1214 errno = EBADF;
1215 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001216 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001217
Josh Gaoaddab3d2016-02-16 17:34:53 -08001218 if (fh->clazz == &_fh_socket_class) {
1219 u_long x = !block;
1220 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
1221 _socket_set_errno(WSAGetLastError());
1222 return false;
1223 }
1224 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001225 } else {
Josh Gaoaddab3d2016-02-16 17:34:53 -08001226 errno = ENOTSOCK;
1227 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001228 }
1229}
1230
David Pursella76e5f02016-02-22 14:27:23 -08001231bool set_tcp_keepalive(int fd, int interval_sec) {
1232 FH fh = _fh_from_int(fd, __func__);
1233
1234 if (!fh || fh->clazz != &_fh_socket_class) {
1235 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1236 errno = EBADF;
1237 return false;
1238 }
1239
1240 tcp_keepalive keepalive;
1241 keepalive.onoff = (interval_sec > 0);
1242 keepalive.keepalivetime = interval_sec * 1000;
1243 keepalive.keepaliveinterval = interval_sec * 1000;
1244
1245 DWORD bytes_returned = 0;
1246 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1247 &bytes_returned, nullptr, nullptr) != 0) {
1248 const DWORD err = WSAGetLastError();
1249 D("set_tcp_keepalive(%d) failed: %s", fd,
1250 android::base::SystemErrorCodeToString(err).c_str());
1251 _socket_set_errno(err);
1252 return false;
1253 }
1254
1255 return true;
1256}
1257
Spencer Lowa30b79a2015-11-15 16:29:36 -08001258static adb_mutex_t g_console_output_buffer_lock;
1259
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001260void
1261adb_sysdeps_init( void )
1262{
1263#define ADB_MUTEX(x) InitializeCriticalSection( & x );
1264#include "mutex_list.h"
1265 InitializeCriticalSection( &_win32_lock );
Spencer Lowa30b79a2015-11-15 16:29:36 -08001266 InitializeCriticalSection( &g_console_output_buffer_lock );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001267}
1268
Spencer Low50184062015-03-01 15:06:21 -08001269/**************************************************************************/
1270/**************************************************************************/
1271/***** *****/
1272/***** Console Window Terminal Emulation *****/
1273/***** *****/
1274/**************************************************************************/
1275/**************************************************************************/
1276
1277// This reads input from a Win32 console window and translates it into Unix
1278// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1279// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1280// is emulated instead of xterm because it is probably more popular than xterm:
1281// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1282// supports modern fonts, etc. It seems best to emulate the terminal that most
1283// Android developers use because they'll fix apps (the shell, etc.) to keep
1284// working with that terminal's emulation.
1285//
1286// The point of this emulation is not to be perfect or to solve all issues with
1287// console windows on Windows, but to be better than the original code which
1288// just called read() (which called ReadFile(), which called ReadConsoleA())
1289// which did not support Ctrl-C, tab completion, shell input line editing
1290// keys, server echo, and more.
1291//
1292// This implementation reconfigures the console with SetConsoleMode(), then
1293// calls ReadConsoleInput() to get raw input which it remaps to Unix
1294// terminal-style sequences which is returned via unix_read() which is used
1295// by the 'adb shell' command.
1296//
1297// Code organization:
1298//
David Pursellc5b8ad82015-10-28 14:29:51 -07001299// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001300// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1301// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1302// * _console_read() is the main code of the emulation.
1303
David Pursellc5b8ad82015-10-28 14:29:51 -07001304// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1305// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1306// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1307static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1308 // First check isatty(); this is very fast and eliminates most non-console
1309 // FDs, but returns 1 for both consoles and character devices like NUL.
1310#pragma push_macro("isatty")
1311#undef isatty
1312 if (!isatty(fd)) {
1313 return nullptr;
1314 }
1315#pragma pop_macro("isatty")
1316
1317 // To differentiate between character devices and consoles we need to get
1318 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1319 // GENERIC_READ permissions.
1320 const intptr_t intptr_handle = _get_osfhandle(fd);
1321 if (intptr_handle == -1) {
1322 return nullptr;
1323 }
1324 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1325 DWORD temp_mode = 0;
1326 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1327 return nullptr;
1328 }
1329
1330 return handle;
1331}
1332
1333// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1334static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001335 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1336 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001337 const int fd = fileno(stream);
1338 if (fd < 0) {
1339 return nullptr;
1340 }
1341 return _get_console_handle(fd);
1342}
1343
1344int unix_isatty(int fd) {
1345 return _get_console_handle(fd) ? 1 : 0;
1346}
Spencer Low50184062015-03-01 15:06:21 -08001347
Spencer Low32762f42015-11-10 19:17:16 -08001348// Get the next KEY_EVENT_RECORD that should be processed.
1349static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001350 for (;;) {
1351 DWORD read_count = 0;
1352 memset(input_record, 0, sizeof(*input_record));
1353 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001354 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001355 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001356 errno = EIO;
1357 return false;
1358 }
1359
1360 if (read_count == 0) { // should be impossible
1361 fatal("ReadConsoleInputA returned 0");
1362 }
1363
1364 if (read_count != 1) { // should be impossible
1365 fatal("ReadConsoleInputA did not return one input record");
1366 }
1367
Spencer Low2e02dc62015-11-07 17:34:39 -08001368 // If the console window is resized, emulate SIGWINCH by breaking out
1369 // of read() with errno == EINTR. Note that there is no event on
1370 // vertical resize because we don't give the console our own custom
1371 // screen buffer (with CreateConsoleScreenBuffer() +
1372 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1373 // supports scrollback, but doesn't seem to raise an event for vertical
1374 // window resize.
1375 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1376 errno = EINTR;
1377 return false;
1378 }
1379
Spencer Low50184062015-03-01 15:06:21 -08001380 if ((input_record->EventType == KEY_EVENT) &&
1381 (input_record->Event.KeyEvent.bKeyDown)) {
1382 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1383 fatal("ReadConsoleInputA returned a key event with zero repeat"
1384 " count");
1385 }
1386
1387 // Got an interesting INPUT_RECORD, so return
1388 return true;
1389 }
1390 }
1391}
1392
Spencer Low50184062015-03-01 15:06:21 -08001393static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1394 return (control_key_state & SHIFT_PRESSED) != 0;
1395}
1396
1397static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1398 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1399}
1400
1401static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1402 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1403}
1404
1405static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1406 return (control_key_state & NUMLOCK_ON) != 0;
1407}
1408
1409static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1410 return (control_key_state & CAPSLOCK_ON) != 0;
1411}
1412
1413static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1414 return (control_key_state & ENHANCED_KEY) != 0;
1415}
1416
1417// Constants from MSDN for ToAscii().
1418static const BYTE TOASCII_KEY_OFF = 0x00;
1419static const BYTE TOASCII_KEY_DOWN = 0x80;
1420static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1421
1422// Given a key event, ignore a modifier key and return the character that was
1423// entered without the modifier. Writes to *ch and returns the number of bytes
1424// written.
1425static size_t _get_char_ignoring_modifier(char* const ch,
1426 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1427 const WORD modifier) {
1428 // If there is no character from Windows, try ignoring the specified
1429 // modifier and look for a character. Note that if AltGr is being used,
1430 // there will be a character from Windows.
1431 if (key_event->uChar.AsciiChar == '\0') {
1432 // Note that we read the control key state from the passed in argument
1433 // instead of from key_event since the argument has been normalized.
1434 if (((modifier == VK_SHIFT) &&
1435 _is_shift_pressed(control_key_state)) ||
1436 ((modifier == VK_CONTROL) &&
1437 _is_ctrl_pressed(control_key_state)) ||
1438 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1439
1440 BYTE key_state[256] = {0};
1441 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1442 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1443 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1444 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1445 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1446 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1447 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1448 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1449
1450 // cause this modifier to be ignored
1451 key_state[modifier] = TOASCII_KEY_OFF;
1452
1453 WORD translated = 0;
1454 if (ToAscii(key_event->wVirtualKeyCode,
1455 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1456 // Ignoring the modifier, we found a character.
1457 *ch = (CHAR)translated;
1458 return 1;
1459 }
1460 }
1461 }
1462
1463 // Just use whatever Windows told us originally.
1464 *ch = key_event->uChar.AsciiChar;
1465
1466 // If the character from Windows is NULL, return a size of zero.
1467 return (*ch == '\0') ? 0 : 1;
1468}
1469
1470// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1471// but taking into account the shift key. This is because for a sequence like
1472// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1473// we want to find the character ')'.
1474//
1475// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1476// because it is the default key-sequence to switch the input language.
1477// This is configurable in the Region and Language control panel.
1478static __inline__ size_t _get_non_control_char(char* const ch,
1479 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1480 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1481 VK_CONTROL);
1482}
1483
1484// Get without Alt.
1485static __inline__ size_t _get_non_alt_char(char* const ch,
1486 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1487 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1488 VK_MENU);
1489}
1490
1491// Ignore the control key, find the character from Windows, and apply any
1492// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1493// *pch and returns number of bytes written.
1494static size_t _get_control_character(char* const pch,
1495 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1496 const size_t len = _get_non_control_char(pch, key_event,
1497 control_key_state);
1498
1499 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1500 char ch = *pch;
1501 switch (ch) {
1502 case '2':
1503 case '@':
1504 case '`':
1505 ch = '\0';
1506 break;
1507 case '3':
1508 case '[':
1509 case '{':
1510 ch = '\x1b';
1511 break;
1512 case '4':
1513 case '\\':
1514 case '|':
1515 ch = '\x1c';
1516 break;
1517 case '5':
1518 case ']':
1519 case '}':
1520 ch = '\x1d';
1521 break;
1522 case '6':
1523 case '^':
1524 case '~':
1525 ch = '\x1e';
1526 break;
1527 case '7':
1528 case '-':
1529 case '_':
1530 ch = '\x1f';
1531 break;
1532 case '8':
1533 ch = '\x7f';
1534 break;
1535 case '/':
1536 if (!_is_alt_pressed(control_key_state)) {
1537 ch = '\x1f';
1538 }
1539 break;
1540 case '?':
1541 if (!_is_alt_pressed(control_key_state)) {
1542 ch = '\x7f';
1543 }
1544 break;
1545 }
1546 *pch = ch;
1547 }
1548
1549 return len;
1550}
1551
1552static DWORD _normalize_altgr_control_key_state(
1553 const KEY_EVENT_RECORD* const key_event) {
1554 DWORD control_key_state = key_event->dwControlKeyState;
1555
1556 // If we're in an AltGr situation where the AltGr key is down (depending on
1557 // the keyboard layout, that might be the physical right alt key which
1558 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1559 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1560 // a character (which indicates that there was an AltGr mapping), then act
1561 // as if alt and control are not really down for the purposes of modifiers.
1562 // This makes it so that if the user with, say, a German keyboard layout
1563 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1564 // output the key and we don't see the Alt and Ctrl keys.
1565 if (_is_ctrl_pressed(control_key_state) &&
1566 _is_alt_pressed(control_key_state)
1567 && (key_event->uChar.AsciiChar != '\0')) {
1568 // Try to remove as few bits as possible to improve our chances of
1569 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1570 // Left-Alt + Right-Ctrl + AltGr.
1571 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1572 // Remove Right-Alt.
1573 control_key_state &= ~RIGHT_ALT_PRESSED;
1574 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1575 // pressed, Left-Ctrl is almost always set, except if the user
1576 // presses Right-Ctrl, then AltGr (in that specific order) for
1577 // whatever reason. At any rate, make sure the bit is not set.
1578 control_key_state &= ~LEFT_CTRL_PRESSED;
1579 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1580 // Remove Left-Alt.
1581 control_key_state &= ~LEFT_ALT_PRESSED;
1582 // Whichever Ctrl key is down, remove it from the state. We only
1583 // remove one key, to improve our chances of detecting the
1584 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1585 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1586 // Remove Left-Ctrl.
1587 control_key_state &= ~LEFT_CTRL_PRESSED;
1588 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1589 // Remove Right-Ctrl.
1590 control_key_state &= ~RIGHT_CTRL_PRESSED;
1591 }
1592 }
1593
1594 // Note that this logic isn't 100% perfect because Windows doesn't
1595 // allow us to detect all combinations because a physical AltGr key
1596 // press shows up as two bits, plus some combinations are ambiguous
1597 // about what is actually physically pressed.
1598 }
1599
1600 return control_key_state;
1601}
1602
1603// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1604// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1605// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1606// appropriately.
1607static DWORD _normalize_keypad_control_key_state(const WORD vk,
1608 const DWORD control_key_state) {
1609 if (!_is_numlock_on(control_key_state)) {
1610 return control_key_state;
1611 }
1612 if (!_is_enhanced_key(control_key_state)) {
1613 switch (vk) {
1614 case VK_INSERT: // 0
1615 case VK_DELETE: // .
1616 case VK_END: // 1
1617 case VK_DOWN: // 2
1618 case VK_NEXT: // 3
1619 case VK_LEFT: // 4
1620 case VK_CLEAR: // 5
1621 case VK_RIGHT: // 6
1622 case VK_HOME: // 7
1623 case VK_UP: // 8
1624 case VK_PRIOR: // 9
1625 return control_key_state | SHIFT_PRESSED;
1626 }
1627 }
1628
1629 return control_key_state;
1630}
1631
1632static const char* _get_keypad_sequence(const DWORD control_key_state,
1633 const char* const normal, const char* const shifted) {
1634 if (_is_shift_pressed(control_key_state)) {
1635 // Shift is pressed and NumLock is off
1636 return shifted;
1637 } else {
1638 // Shift is not pressed and NumLock is off, or,
1639 // Shift is pressed and NumLock is on, in which case we want the
1640 // NumLock and Shift to neutralize each other, thus, we want the normal
1641 // sequence.
1642 return normal;
1643 }
1644 // If Shift is not pressed and NumLock is on, a different virtual key code
1645 // is returned by Windows, which can be taken care of by a different case
1646 // statement in _console_read().
1647}
1648
1649// Write sequence to buf and return the number of bytes written.
1650static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1651 DWORD control_key_state, const char* const normal) {
1652 // Copy the base sequence into buf.
1653 const size_t len = strlen(normal);
1654 memcpy(buf, normal, len);
1655
1656 int code = 0;
1657
1658 control_key_state = _normalize_keypad_control_key_state(vk,
1659 control_key_state);
1660
1661 if (_is_shift_pressed(control_key_state)) {
1662 code |= 0x1;
1663 }
1664 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1665 code |= 0x2;
1666 }
1667 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1668 code |= 0x4;
1669 }
1670 // If some modifier was held down, then we need to insert the modifier code
1671 if (code != 0) {
1672 if (len == 0) {
1673 // Should be impossible because caller should pass a string of
1674 // non-zero length.
1675 return 0;
1676 }
1677 size_t index = len - 1;
1678 const char lastChar = buf[index];
1679 if (lastChar != '~') {
1680 buf[index++] = '1';
1681 }
1682 buf[index++] = ';'; // modifier separator
1683 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1684 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1685 buf[index++] = '1' + code;
1686 buf[index++] = lastChar; // move ~ (or other last char) to the end
1687 return index;
1688 }
1689 return len;
1690}
1691
1692// Write sequence to buf and return the number of bytes written.
1693static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1694 const DWORD control_key_state, const char* const normal,
1695 const char shifted) {
1696 if (_is_shift_pressed(control_key_state)) {
1697 // Shift is pressed and NumLock is off
1698 if (shifted != '\0') {
1699 buf[0] = shifted;
1700 return sizeof(buf[0]);
1701 } else {
1702 return 0;
1703 }
1704 } else {
1705 // Shift is not pressed and NumLock is off, or,
1706 // Shift is pressed and NumLock is on, in which case we want the
1707 // NumLock and Shift to neutralize each other, thus, we want the normal
1708 // sequence.
1709 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1710 }
1711 // If Shift is not pressed and NumLock is on, a different virtual key code
1712 // is returned by Windows, which can be taken care of by a different case
1713 // statement in _console_read().
1714}
1715
1716// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1717// Standard German. Figure this out at runtime so we know what to output for
1718// Shift-VK_DELETE.
1719static char _get_decimal_char() {
1720 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1721}
1722
1723// Prefix the len bytes in buf with the escape character, and then return the
1724// new buffer length.
1725size_t _escape_prefix(char* const buf, const size_t len) {
1726 // If nothing to prefix, don't do anything. We might be called with
1727 // len == 0, if alt was held down with a dead key which produced nothing.
1728 if (len == 0) {
1729 return 0;
1730 }
1731
1732 memmove(&buf[1], buf, len);
1733 buf[0] = '\x1b';
1734 return len + 1;
1735}
1736
Spencer Low32762f42015-11-10 19:17:16 -08001737// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001738static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001739
1740// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1741// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001742static int _console_read(const HANDLE console, void* buf, size_t len) {
1743 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001744 // Read of zero bytes should not block waiting for something from the console.
1745 if (len == 0) {
1746 return 0;
1747 }
1748
1749 // Flush as much as possible from input buffer.
1750 if (!g_console_input_buffer.empty()) {
1751 const int bytes_read = std::min(len, g_console_input_buffer.size());
1752 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1753 const auto begin = g_console_input_buffer.begin();
1754 g_console_input_buffer.erase(begin, begin + bytes_read);
1755 return bytes_read;
1756 }
1757
1758 // Read from the actual console. This may block until input.
1759 INPUT_RECORD input_record;
1760 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001761 return -1;
1762 }
1763
Spencer Low32762f42015-11-10 19:17:16 -08001764 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001765 const WORD vk = key_event->wVirtualKeyCode;
1766 const CHAR ch = key_event->uChar.AsciiChar;
1767 const DWORD control_key_state = _normalize_altgr_control_key_state(
1768 key_event);
1769
1770 // The following emulation code should write the output sequence to
1771 // either seqstr or to seqbuf and seqbuflen.
1772 const char* seqstr = NULL; // NULL terminated C-string
1773 // Enough space for max sequence string below, plus modifiers and/or
1774 // escape prefix.
1775 char seqbuf[16];
1776 size_t seqbuflen = 0; // Space used in seqbuf.
1777
1778#define MATCH(vk, normal) \
1779 case (vk): \
1780 { \
1781 seqstr = (normal); \
1782 } \
1783 break;
1784
1785 // Modifier keys should affect the output sequence.
1786#define MATCH_MODIFIER(vk, normal) \
1787 case (vk): \
1788 { \
1789 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1790 control_key_state, (normal)); \
1791 } \
1792 break;
1793
1794 // The shift key should affect the output sequence.
1795#define MATCH_KEYPAD(vk, normal, shifted) \
1796 case (vk): \
1797 { \
1798 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1799 (shifted)); \
1800 } \
1801 break;
1802
1803 // The shift key and other modifier keys should affect the output
1804 // sequence.
1805#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1806 case (vk): \
1807 { \
1808 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1809 control_key_state, (normal), (shifted)); \
1810 } \
1811 break;
1812
1813#define ESC "\x1b"
1814#define CSI ESC "["
1815#define SS3 ESC "O"
1816
1817 // Only support normal mode, not application mode.
1818
1819 // Enhanced keys:
1820 // * 6-pack: insert, delete, home, end, page up, page down
1821 // * cursor keys: up, down, right, left
1822 // * keypad: divide, enter
1823 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1824 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1825 if (_is_enhanced_key(control_key_state)) {
1826 switch (vk) {
1827 case VK_RETURN: // Enter key on keypad
1828 if (_is_ctrl_pressed(control_key_state)) {
1829 seqstr = "\n";
1830 } else {
1831 seqstr = "\r";
1832 }
1833 break;
1834
1835 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1836 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1837
1838 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1839 // will be fixed soon to match xterm which sends CSI "F" and
1840 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1841 MATCH(VK_END, CSI "F");
1842 MATCH(VK_HOME, CSI "H");
1843
1844 MATCH_MODIFIER(VK_LEFT, CSI "D");
1845 MATCH_MODIFIER(VK_UP, CSI "A");
1846 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1847 MATCH_MODIFIER(VK_DOWN, CSI "B");
1848
1849 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1850 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1851
1852 MATCH(VK_DIVIDE, "/");
1853 }
1854 } else { // Non-enhanced keys:
1855 switch (vk) {
1856 case VK_BACK: // backspace
1857 if (_is_alt_pressed(control_key_state)) {
1858 seqstr = ESC "\x7f";
1859 } else {
1860 seqstr = "\x7f";
1861 }
1862 break;
1863
1864 case VK_TAB:
1865 if (_is_shift_pressed(control_key_state)) {
1866 seqstr = CSI "Z";
1867 } else {
1868 seqstr = "\t";
1869 }
1870 break;
1871
1872 // Number 5 key in keypad when NumLock is off, or if NumLock is
1873 // on and Shift is down.
1874 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1875
1876 case VK_RETURN: // Enter key on main keyboard
1877 if (_is_alt_pressed(control_key_state)) {
1878 seqstr = ESC "\n";
1879 } else if (_is_ctrl_pressed(control_key_state)) {
1880 seqstr = "\n";
1881 } else {
1882 seqstr = "\r";
1883 }
1884 break;
1885
1886 // VK_ESCAPE: Don't do any special handling. The OS uses many
1887 // of the sequences with Escape and many of the remaining
1888 // sequences don't produce bKeyDown messages, only !bKeyDown
1889 // for whatever reason.
1890
1891 case VK_SPACE:
1892 if (_is_alt_pressed(control_key_state)) {
1893 seqstr = ESC " ";
1894 } else if (_is_ctrl_pressed(control_key_state)) {
1895 seqbuf[0] = '\0'; // NULL char
1896 seqbuflen = 1;
1897 } else {
1898 seqstr = " ";
1899 }
1900 break;
1901
1902 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1903 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1904
1905 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1906 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1907
1908 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1909 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1910 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1911 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1912
1913 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1914 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1915 _get_decimal_char());
1916
1917 case 0x30: // 0
1918 case 0x31: // 1
1919 case 0x39: // 9
1920 case VK_OEM_1: // ;:
1921 case VK_OEM_PLUS: // =+
1922 case VK_OEM_COMMA: // ,<
1923 case VK_OEM_PERIOD: // .>
1924 case VK_OEM_7: // '"
1925 case VK_OEM_102: // depends on keyboard, could be <> or \|
1926 case VK_OEM_2: // /?
1927 case VK_OEM_3: // `~
1928 case VK_OEM_4: // [{
1929 case VK_OEM_5: // \|
1930 case VK_OEM_6: // ]}
1931 {
1932 seqbuflen = _get_control_character(seqbuf, key_event,
1933 control_key_state);
1934
1935 if (_is_alt_pressed(control_key_state)) {
1936 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1937 }
1938 }
1939 break;
1940
1941 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001942 case 0x33: // 3
1943 case 0x34: // 4
1944 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001945 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001946 case 0x37: // 7
1947 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001948 case VK_OEM_MINUS: // -_
1949 {
1950 seqbuflen = _get_control_character(seqbuf, key_event,
1951 control_key_state);
1952
1953 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1954 // prefix with escape.
1955 if (_is_alt_pressed(control_key_state) &&
1956 !(_is_ctrl_pressed(control_key_state) &&
1957 !_is_shift_pressed(control_key_state))) {
1958 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1959 }
1960 }
1961 break;
1962
Spencer Low50184062015-03-01 15:06:21 -08001963 case 0x41: // a
1964 case 0x42: // b
1965 case 0x43: // c
1966 case 0x44: // d
1967 case 0x45: // e
1968 case 0x46: // f
1969 case 0x47: // g
1970 case 0x48: // h
1971 case 0x49: // i
1972 case 0x4a: // j
1973 case 0x4b: // k
1974 case 0x4c: // l
1975 case 0x4d: // m
1976 case 0x4e: // n
1977 case 0x4f: // o
1978 case 0x50: // p
1979 case 0x51: // q
1980 case 0x52: // r
1981 case 0x53: // s
1982 case 0x54: // t
1983 case 0x55: // u
1984 case 0x56: // v
1985 case 0x57: // w
1986 case 0x58: // x
1987 case 0x59: // y
1988 case 0x5a: // z
1989 {
1990 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1991 control_key_state);
1992
1993 // If Alt is pressed, then prefix with escape.
1994 if (_is_alt_pressed(control_key_state)) {
1995 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1996 }
1997 }
1998 break;
1999
2000 // These virtual key codes are generated by the keys on the
2001 // keypad *when NumLock is on* and *Shift is up*.
2002 MATCH(VK_NUMPAD0, "0");
2003 MATCH(VK_NUMPAD1, "1");
2004 MATCH(VK_NUMPAD2, "2");
2005 MATCH(VK_NUMPAD3, "3");
2006 MATCH(VK_NUMPAD4, "4");
2007 MATCH(VK_NUMPAD5, "5");
2008 MATCH(VK_NUMPAD6, "6");
2009 MATCH(VK_NUMPAD7, "7");
2010 MATCH(VK_NUMPAD8, "8");
2011 MATCH(VK_NUMPAD9, "9");
2012
2013 MATCH(VK_MULTIPLY, "*");
2014 MATCH(VK_ADD, "+");
2015 MATCH(VK_SUBTRACT, "-");
2016 // VK_DECIMAL is generated by the . key on the keypad *when
2017 // NumLock is on* and *Shift is up* and the sequence is not
2018 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
2019 // Windows Security screen to come up).
2020 case VK_DECIMAL:
2021 // U.S. English uses '.', Germany German uses ','.
2022 seqbuflen = _get_non_control_char(seqbuf, key_event,
2023 control_key_state);
2024 break;
2025
2026 MATCH_MODIFIER(VK_F1, SS3 "P");
2027 MATCH_MODIFIER(VK_F2, SS3 "Q");
2028 MATCH_MODIFIER(VK_F3, SS3 "R");
2029 MATCH_MODIFIER(VK_F4, SS3 "S");
2030 MATCH_MODIFIER(VK_F5, CSI "15~");
2031 MATCH_MODIFIER(VK_F6, CSI "17~");
2032 MATCH_MODIFIER(VK_F7, CSI "18~");
2033 MATCH_MODIFIER(VK_F8, CSI "19~");
2034 MATCH_MODIFIER(VK_F9, CSI "20~");
2035 MATCH_MODIFIER(VK_F10, CSI "21~");
2036 MATCH_MODIFIER(VK_F11, CSI "23~");
2037 MATCH_MODIFIER(VK_F12, CSI "24~");
2038
2039 MATCH_MODIFIER(VK_F13, CSI "25~");
2040 MATCH_MODIFIER(VK_F14, CSI "26~");
2041 MATCH_MODIFIER(VK_F15, CSI "28~");
2042 MATCH_MODIFIER(VK_F16, CSI "29~");
2043 MATCH_MODIFIER(VK_F17, CSI "31~");
2044 MATCH_MODIFIER(VK_F18, CSI "32~");
2045 MATCH_MODIFIER(VK_F19, CSI "33~");
2046 MATCH_MODIFIER(VK_F20, CSI "34~");
2047
2048 // MATCH_MODIFIER(VK_F21, ???);
2049 // MATCH_MODIFIER(VK_F22, ???);
2050 // MATCH_MODIFIER(VK_F23, ???);
2051 // MATCH_MODIFIER(VK_F24, ???);
2052 }
2053 }
2054
2055#undef MATCH
2056#undef MATCH_MODIFIER
2057#undef MATCH_KEYPAD
2058#undef MATCH_MODIFIER_KEYPAD
2059#undef ESC
2060#undef CSI
2061#undef SS3
2062
2063 const char* out;
2064 size_t outlen;
2065
2066 // Check for output in any of:
2067 // * seqstr is set (and strlen can be used to determine the length).
2068 // * seqbuf and seqbuflen are set
2069 // Fallback to ch from Windows.
2070 if (seqstr != NULL) {
2071 out = seqstr;
2072 outlen = strlen(seqstr);
2073 } else if (seqbuflen > 0) {
2074 out = seqbuf;
2075 outlen = seqbuflen;
2076 } else if (ch != '\0') {
2077 // Use whatever Windows told us it is.
2078 seqbuf[0] = ch;
2079 seqbuflen = 1;
2080 out = seqbuf;
2081 outlen = seqbuflen;
2082 } else {
2083 // No special handling for the virtual key code and Windows isn't
2084 // telling us a character code, then we don't know how to translate
2085 // the key press.
2086 //
2087 // Consume the input and 'continue' to cause us to get a new key
2088 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002089 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002090 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002091 continue;
2092 }
2093
Spencer Low32762f42015-11-10 19:17:16 -08002094 // put output wRepeatCount times into g_console_input_buffer
2095 while (key_event->wRepeatCount-- > 0) {
2096 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002097 }
2098
Spencer Low32762f42015-11-10 19:17:16 -08002099 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002100 }
2101}
2102
2103static DWORD _old_console_mode; // previous GetConsoleMode() result
2104static HANDLE _console_handle; // when set, console mode should be restored
2105
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002106void stdin_raw_init() {
2107 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002108 if (in == nullptr) {
2109 return;
2110 }
Spencer Low50184062015-03-01 15:06:21 -08002111
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002112 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2113 // calling the process Ctrl-C routine (configured by
2114 // SetConsoleCtrlHandler()).
2115 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2116 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2117 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002118 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2119 ENABLE_LINE_INPUT |
2120 ENABLE_ECHO_INPUT);
2121 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2122 new_console_mode |= ENABLE_WINDOW_INPUT;
2123
2124 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002125 // This really should not fail.
2126 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002127 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002128 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002129
2130 // Once this is set, it means that stdin has been configured for
2131 // reading from and that the old console mode should be restored later.
2132 _console_handle = in;
2133
2134 // Note that we don't need to configure C Runtime line-ending
2135 // translation because _console_read() does not call the C Runtime to
2136 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002137}
2138
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002139void stdin_raw_restore() {
2140 if (_console_handle != NULL) {
2141 const HANDLE in = _console_handle;
2142 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002143
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002144 if (!SetConsoleMode(in, _old_console_mode)) {
2145 // This really should not fail.
2146 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002147 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002148 }
2149 }
2150}
2151
Spencer Low2e02dc62015-11-07 17:34:39 -08002152// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2153int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08002154 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2155 // If it is a request to read from stdin, and stdin_raw_init() has been
2156 // called, and it successfully configured the console, then read from
2157 // the console using Win32 console APIs and partially emulate a unix
2158 // terminal.
2159 return _console_read(_console_handle, buf, len);
2160 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002161 // On older versions of Windows (definitely 7, definitely not 10),
2162 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002163 // we need to limit the read size.
2164 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002165 len = 4096;
2166 }
Spencer Low50184062015-03-01 15:06:21 -08002167 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002168 // can do LF/CR translation (which is overridable with _setmode()).
2169 // Undefine the macro that is set in sysdeps.h which bans calls to
2170 // plain read() in favor of unix_read() or adb_read().
2171#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002172#undef read
2173 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002174#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002175 }
2176}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002177
2178/**************************************************************************/
2179/**************************************************************************/
2180/***** *****/
2181/***** Unicode support *****/
2182/***** *****/
2183/**************************************************************************/
2184/**************************************************************************/
2185
2186// This implements support for using files with Unicode filenames and for
2187// outputting Unicode text to a Win32 console window. This is inspired from
2188// http://utf8everywhere.org/.
2189//
2190// Background
2191// ----------
2192//
2193// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2194// filenames to APIs such as open(). This works because filenames are largely
2195// opaque 'cookies' (perhaps excluding path separators).
2196//
2197// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2198// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2199// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2200// CreateFile() API is really just a macro that adds the W/A based on whether
2201// the UNICODE preprocessor symbol is defined).
2202//
2203// Options
2204// -------
2205//
2206// Thus, to write a portable program, there are a few options:
2207//
2208// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2209// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2210// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2211// open() API.
2212//
2213// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2214// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2215// potentially touching a lot of code.
2216//
2217// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2218// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2219// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2220// or C Runtime API.
2221//
2222// The Choice
2223// ----------
2224//
Spencer Lowd21dc822015-11-12 15:20:15 -08002225// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2226// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002227// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002228// args that are passed to main() at the beginning of program startup. We also use
2229// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002230// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2231//
2232// Unicode console output
2233// ----------------------
2234//
2235// The way to output Unicode to a Win32 console window is to call
2236// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002237// such as Lucida Console or Consolas, and in the case of East Asian languages
2238// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2239// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2240// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002241//
2242// The problem is getting the C Runtime to make fprintf and related APIs call
2243// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2244// promising, but the various modes have issues:
2245//
2246// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2247// UTF-16 do not display properly.
2248// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2249// totally wrong.
2250// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2251// handler to be called (upon a later I/O call), aborting the process.
2252// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2253// to output nothing.
2254//
2255// So the only solution is to write our own adb_fprintf() that converts UTF-8
2256// to UTF-16 and then calls WriteConsoleW().
2257
2258
Spencer Lowcf4ff642015-05-11 01:08:48 -07002259// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2260// be passed to main().
2261NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2262 narrow_args = new char*[argc + 1];
2263
2264 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002265 std::string arg_narrow;
2266 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2267 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2268 }
2269 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002270 }
2271 narrow_args[argc] = nullptr; // terminate
2272}
2273
2274NarrowArgs::~NarrowArgs() {
2275 if (narrow_args != nullptr) {
2276 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2277 free(*argp);
2278 }
2279 delete[] narrow_args;
2280 narrow_args = nullptr;
2281 }
2282}
2283
2284int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002285 std::wstring path_wide;
2286 if (!android::base::UTF8ToWide(path, &path_wide)) {
2287 return -1;
2288 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002289 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002290 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002291 } else {
2292 int mode;
2293 va_list args;
2294 va_start(args, options);
2295 mode = va_arg(args, int);
2296 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002297 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002298 }
2299}
2300
2301// Version of stat() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002302int adb_stat(const char* path, struct adb_stat* s) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002303#pragma push_macro("wstat")
2304// This definition of wstat seems to be missing from <sys/stat.h>.
2305#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
2306#ifdef _USE_32BIT_TIME_T
2307#define wstat _wstat32i64
2308#else
2309#define wstat _wstat64
2310#endif
2311#else
2312// <sys/stat.h> has a function prototype for wstat() that should be available.
2313#endif
2314
Spencer Lowd21dc822015-11-12 15:20:15 -08002315 std::wstring path_wide;
2316 if (!android::base::UTF8ToWide(path, &path_wide)) {
2317 return -1;
2318 }
2319
2320 return wstat(path_wide.c_str(), s);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002321
2322#pragma pop_macro("wstat")
2323}
2324
2325// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002326DIR* adb_opendir(const char* path) {
2327 std::wstring path_wide;
2328 if (!android::base::UTF8ToWide(path, &path_wide)) {
2329 return nullptr;
2330 }
2331
Spencer Lowcf4ff642015-05-11 01:08:48 -07002332 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2333 // the fields, but right now all the callers treat the structure as
2334 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002335 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002336}
2337
2338// Version of readdir() that returns UTF-8 paths.
2339struct dirent* adb_readdir(DIR* dir) {
2340 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2341 struct _wdirent* const went = _wreaddir(wdir);
2342 if (went == nullptr) {
2343 return nullptr;
2344 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002345
Spencer Lowcf4ff642015-05-11 01:08:48 -07002346 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002347 std::string name_utf8;
2348 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2349 return nullptr;
2350 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002351
2352 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2353 // space for UTF-16 wchar_t's) with UTF-8 char's.
2354 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2355
2356 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2357 // Name too big to fit in existing buffer.
2358 errno = ENOMEM;
2359 return nullptr;
2360 }
2361
2362 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2363 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2364 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2365 // bigger than the caller expects because they expect a dirent structure
2366 // which has a smaller d_name field. Ignore this since the caller should be
2367 // resilient.
2368
2369 // Rewrite the UTF-16 d_name field to UTF-8.
2370 strcpy(ent->d_name, name_utf8.c_str());
2371
2372 return ent;
2373}
2374
2375// Version of closedir() to go with our version of adb_opendir().
2376int adb_closedir(DIR* dir) {
2377 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2378}
2379
2380// Version of unlink() that takes a UTF-8 path.
2381int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002382 std::wstring wpath;
2383 if (!android::base::UTF8ToWide(path, &wpath)) {
2384 return -1;
2385 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002386
2387 int rc = _wunlink(wpath.c_str());
2388
2389 if (rc == -1 && errno == EACCES) {
2390 /* unlink returns EACCES when the file is read-only, so we first */
2391 /* try to make it writable, then unlink again... */
2392 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2393 if (rc == 0)
2394 rc = _wunlink(wpath.c_str());
2395 }
2396 return rc;
2397}
2398
2399// Version of mkdir() that takes a UTF-8 path.
2400int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002401 std::wstring path_wide;
2402 if (!android::base::UTF8ToWide(path, &path_wide)) {
2403 return -1;
2404 }
2405
2406 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002407}
2408
2409// Version of utime() that takes a UTF-8 path.
2410int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002411 std::wstring path_wide;
2412 if (!android::base::UTF8ToWide(path, &path_wide)) {
2413 return -1;
2414 }
2415
Spencer Lowcf4ff642015-05-11 01:08:48 -07002416 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2417 "utimbuf and _utimbuf should be the same size because they both "
2418 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002419 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002420}
2421
2422// Version of chmod() that takes a UTF-8 path.
2423int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002424 std::wstring path_wide;
2425 if (!android::base::UTF8ToWide(path, &path_wide)) {
2426 return -1;
2427 }
2428
2429 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002430}
2431
Spencer Lowa30b79a2015-11-15 16:29:36 -08002432// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2433static inline size_t utf8_codepoint_len(uint8_t ch) {
2434 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2435}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002436
Spencer Lowa30b79a2015-11-15 16:29:36 -08002437namespace internal {
2438
2439// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2440// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2441// remaining_bytes.
2442size_t ParseCompleteUTF8(const char* const first, const char* const last,
2443 std::vector<char>* const remaining_bytes) {
2444 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2445 // Current_after points one byte past the current byte to be examined.
2446 for (const char* current_after = last; current_after != first; --current_after) {
2447 const char* const current = current_after - 1;
2448 const char ch = *current;
2449 const char kHighBit = 0x80u;
2450 const char kTwoHighestBits = 0xC0u;
2451 if ((ch & kHighBit) == 0) { // high bit not set
2452 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2453 // bytes with no leading byte, so return the entire buffer.
2454 break;
2455 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2456 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2457 const size_t bytes_available = last - current;
2458 if (bytes_available < utf8_codepoint_len(ch)) {
2459 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2460 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2461 // to remaining_bytes.
2462 remaining_bytes->insert(remaining_bytes->end(), current, last);
2463 return current - first;
2464 } else {
2465 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2466 // trailing bytes with no lead byte, so return the entire buffer.
2467 break;
2468 }
2469 } else {
2470 // Trailing byte, so keep going backwards looking for the lead byte.
2471 }
2472 }
2473
2474 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2475 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2476 // so that they can be processed.
2477 return last - first;
2478}
2479
2480}
2481
2482// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2483// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2484// This matches the behavior of Linux.
2485// Protected by g_console_output_buffer_lock.
2486static auto& g_console_output_buffer = *new std::vector<char>();
2487
2488// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2489static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2490 HANDLE console) {
2491 const int saved_errno = errno;
2492 std::vector<char> combined_buffer;
2493
2494 // Complete UTF-8 sequences that should be immediately written to the console.
2495 const char* utf8;
2496 size_t utf8_size;
2497
2498 adb_mutex_lock(&g_console_output_buffer_lock);
2499 if (g_console_output_buffer.empty()) {
2500 // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2501 // common case with plain ASCII), parse buf directly.
2502 utf8 = buf;
2503 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
2504 } else {
2505 // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2506 // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
2507 // combined_buffer, then parse it all together.
2508 combined_buffer.swap(g_console_output_buffer);
2509 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
2510
2511 utf8 = combined_buffer.data();
2512 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2513 &g_console_output_buffer);
2514 }
2515 adb_mutex_unlock(&g_console_output_buffer_lock);
2516
2517 std::wstring utf16;
2518
2519 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2520 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2521 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002522 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002523 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002524
2525 // Note that this does not do \n => \r\n translation because that
2526 // doesn't seem necessary for the Windows console. For the Windows
2527 // console \r moves to the beginning of the line and \n moves to a new
2528 // line.
2529
2530 // Flush any stream buffering so that our output is afterwards which
2531 // makes sense because our call is afterwards.
2532 (void)fflush(stream);
2533
2534 // Write UTF-16 to the console.
2535 DWORD written = 0;
Spencer Lowa30b79a2015-11-15 16:29:36 -08002536 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002537 errno = EIO;
2538 return -1;
2539 }
2540
Spencer Lowa30b79a2015-11-15 16:29:36 -08002541 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2542 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2543 // matches the Linux behavior.
2544 errno = saved_errno;
2545 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002546}
2547
2548// Function prototype because attributes cannot be placed on func definitions.
2549static int _console_vfprintf(const HANDLE console, FILE* stream,
2550 const char *format, va_list ap)
2551 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2552
2553// Internal function to format a UTF-8 string and write it to a Win32 console.
2554// Returns -1 on error.
2555static int _console_vfprintf(const HANDLE console, FILE* stream,
2556 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002557 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002558 std::string output_utf8;
2559
2560 // Format the string.
2561 // This could throw std::bad_alloc.
2562 android::base::StringAppendV(&output_utf8, format, ap);
2563
Spencer Lowa30b79a2015-11-15 16:29:36 -08002564 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2565 console);
2566 if (result != -1) {
2567 errno = saved_errno;
2568 } else {
2569 // If -1 was returned, errno has been set.
2570 }
2571 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002572}
2573
2574// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2575// Windows console.
2576int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2577 const HANDLE console = _get_console_handle(stream);
2578
2579 // If there is an associated Win32 console, write to it specially,
2580 // otherwise defer to the regular C Runtime, passing it UTF-8.
2581 if (console != NULL) {
2582 return _console_vfprintf(console, stream, format, ap);
2583 } else {
2584 // If vfprintf is a macro, undefine it, so we can call the real
2585 // C Runtime API.
2586#pragma push_macro("vfprintf")
2587#undef vfprintf
2588 return vfprintf(stream, format, ap);
2589#pragma pop_macro("vfprintf")
2590 }
2591}
2592
Spencer Lowa30b79a2015-11-15 16:29:36 -08002593// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2594int adb_vprintf(const char *format, va_list ap) {
2595 return adb_vfprintf(stdout, format, ap);
2596}
2597
Spencer Lowcf4ff642015-05-11 01:08:48 -07002598// Version of fprintf() that takes UTF-8 and can write Unicode to a
2599// Windows console.
2600int adb_fprintf(FILE *stream, const char *format, ...) {
2601 va_list ap;
2602 va_start(ap, format);
2603 const int result = adb_vfprintf(stream, format, ap);
2604 va_end(ap);
2605
2606 return result;
2607}
2608
2609// Version of printf() that takes UTF-8 and can write Unicode to a
2610// Windows console.
2611int adb_printf(const char *format, ...) {
2612 va_list ap;
2613 va_start(ap, format);
2614 const int result = adb_vfprintf(stdout, format, ap);
2615 va_end(ap);
2616
2617 return result;
2618}
2619
2620// Version of fputs() that takes UTF-8 and can write Unicode to a
2621// Windows console.
2622int adb_fputs(const char* buf, FILE* stream) {
2623 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2624 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002625 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002626 return adb_fprintf(stream, "%s", buf);
2627}
2628
2629// Version of fputc() that takes UTF-8 and can write Unicode to a
2630// Windows console.
2631int adb_fputc(int ch, FILE* stream) {
2632 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002633 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002634 return EOF;
2635 }
2636 // For success, fputc returns the char, cast to unsigned char, then to int.
2637 return static_cast<unsigned char>(ch);
2638}
2639
Spencer Lowa30b79a2015-11-15 16:29:36 -08002640// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2641int adb_putchar(int ch) {
2642 return adb_fputc(ch, stdout);
2643}
2644
2645// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2646int adb_puts(const char* buf) {
2647 // adb_printf returns -1 on error, which is conveniently the same as EOF
2648 // which puts (and hence adb_puts) should return on error.
2649 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2650 return adb_printf("%s\n", buf);
2651}
2652
Spencer Lowcf4ff642015-05-11 01:08:48 -07002653// Internal function to write UTF-8 to a Win32 console. Returns the number of
2654// items (of length size) written. On error, returns a short item count or 0.
2655static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2656 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002657 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2658 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002659 if (result == -1) {
2660 return 0;
2661 }
2662 return result / size;
2663}
2664
2665// Version of fwrite() that takes UTF-8 and can write Unicode to a
2666// Windows console.
2667size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2668 const HANDLE console = _get_console_handle(stream);
2669
2670 // If there is an associated Win32 console, write to it specially,
2671 // otherwise defer to the regular C Runtime, passing it UTF-8.
2672 if (console != NULL) {
2673 return _console_fwrite(ptr, size, nmemb, stream, console);
2674 } else {
2675 // If fwrite is a macro, undefine it, so we can call the real
2676 // C Runtime API.
2677#pragma push_macro("fwrite")
2678#undef fwrite
2679 return fwrite(ptr, size, nmemb, stream);
2680#pragma pop_macro("fwrite")
2681 }
2682}
2683
2684// Version of fopen() that takes a UTF-8 filename and can access a file with
2685// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002686FILE* adb_fopen(const char* path, const char* mode) {
2687 std::wstring path_wide;
2688 if (!android::base::UTF8ToWide(path, &path_wide)) {
2689 return nullptr;
2690 }
2691
2692 std::wstring mode_wide;
2693 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2694 return nullptr;
2695 }
2696
2697 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002698}
2699
Spencer Lowe6ae5732015-09-08 17:13:04 -07002700// Return a lowercase version of the argument. Uses C Runtime tolower() on
2701// each byte which is not UTF-8 aware, and theoretically uses the current C
2702// Runtime locale (which in practice is not changed, so this becomes a ASCII
2703// conversion).
2704static std::string ToLower(const std::string& anycase) {
2705 // copy string
2706 std::string str(anycase);
2707 // transform the copy
2708 std::transform(str.begin(), str.end(), str.begin(), tolower);
2709 return str;
2710}
2711
2712extern "C" int main(int argc, char** argv);
2713
2714// Link with -municode to cause this wmain() to be used as the program
2715// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2716// regular main() with UTF-8 args.
2717extern "C" int wmain(int argc, wchar_t **argv) {
2718 // Convert args from UTF-16 to UTF-8 and pass that to main().
2719 NarrowArgs narrow_args(argc, argv);
2720 return main(argc, narrow_args.data());
2721}
2722
Spencer Lowcf4ff642015-05-11 01:08:48 -07002723// Shadow UTF-8 environment variable name/value pairs that are created from
2724// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002725// currently updated if putenv, setenv, unsetenv are called. Note that no
2726// thread synchronization is done, but we're called early enough in
2727// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002728static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002729
2730// Make sure that shadow UTF-8 environment variables are setup.
2731static void _ensure_env_setup() {
2732 // If some name/value pairs exist, then we've already done the setup below.
2733 if (g_environ_utf8.size() != 0) {
2734 return;
2735 }
2736
Spencer Lowe6ae5732015-09-08 17:13:04 -07002737 if (_wenviron == nullptr) {
2738 // If _wenviron is null, then -municode probably wasn't used. That
2739 // linker flag will cause the entry point to setup _wenviron. It will
2740 // also require an implementation of wmain() (which we provide above).
2741 fatal("_wenviron is not set, did you link with -municode?");
2742 }
2743
Spencer Lowcf4ff642015-05-11 01:08:48 -07002744 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2745 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2746 // to use the D() macro here because that tracing only works if the
2747 // ADB_TRACE environment variable is setup, but that env var can't be read
2748 // until this code completes.
2749 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2750 wchar_t* const equal = wcschr(*env, L'=');
2751 if (equal == nullptr) {
2752 // Malformed environment variable with no equal sign. Shouldn't
2753 // really happen, but we should be resilient to this.
2754 continue;
2755 }
2756
Spencer Lowd21dc822015-11-12 15:20:15 -08002757 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2758 // var because the program might never even read this particular variable.
2759 std::string name_utf8;
2760 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2761 continue;
2762 }
2763
Spencer Lowe6ae5732015-09-08 17:13:04 -07002764 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002765 name_utf8 = ToLower(name_utf8);
2766
2767 std::string value_utf8;
2768 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2769 continue;
2770 }
2771
2772 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002773
Spencer Lowe6ae5732015-09-08 17:13:04 -07002774 // Don't overwrite a previus env var with the same name. In reality,
2775 // the system probably won't let two env vars with the same name exist
2776 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002777 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002778 }
2779}
2780
2781// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002782// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002783char* adb_getenv(const char* name) {
2784 _ensure_env_setup();
2785
Spencer Lowe6ae5732015-09-08 17:13:04 -07002786 // Case-insensitive search by searching for lowercase name in a map of
2787 // lowercase names.
2788 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002789 if (it == g_environ_utf8.end()) {
2790 return nullptr;
2791 }
2792
2793 return it->second;
2794}
2795
2796// Version of getcwd() that returns the current working directory in UTF-8.
2797char* adb_getcwd(char* buf, int size) {
2798 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2799 if (wbuf == nullptr) {
2800 return nullptr;
2801 }
2802
Spencer Lowd21dc822015-11-12 15:20:15 -08002803 std::string buf_utf8;
2804 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002805 free(wbuf);
2806 wbuf = nullptr;
2807
Spencer Lowd21dc822015-11-12 15:20:15 -08002808 if (!narrow_result) {
2809 return nullptr;
2810 }
2811
Spencer Lowcf4ff642015-05-11 01:08:48 -07002812 // If size was specified, make sure all the chars will fit.
2813 if (size != 0) {
2814 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2815 errno = ERANGE;
2816 return nullptr;
2817 }
2818 }
2819
2820 // If buf was not specified, allocate storage.
2821 if (buf == nullptr) {
2822 if (size == 0) {
2823 size = buf_utf8.length() + 1;
2824 }
2825 buf = reinterpret_cast<char*>(malloc(size));
2826 if (buf == nullptr) {
2827 return nullptr;
2828 }
2829 }
2830
2831 // Destination buffer was allocated with enough space, or we've already
2832 // checked an existing buffer size for enough space.
2833 strcpy(buf, buf_utf8.c_str());
2834
2835 return buf;
2836}