blob: c36d77991893ed946464843d19abca743e664225 [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 Gao3777d2e2016-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 Gao3777d2e2016-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 Gaob6232b92016-02-17 16:45:39 -0800193#define WIN32_FH_BASE 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800194#define WIN32_MAX_FHS 128
195
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 Gaob6232b92016-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 Gaob6232b92016-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 Gao3777d2e2016-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 Gao3777d2e2016-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) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700729 D("closesocket failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800730 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700731 }
732 f->fh_socket = INVALID_SOCKET;
733 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734 f->mask = 0;
735 return 0;
736}
737
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700738static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739 errno = EPIPE;
740 return -1;
741}
742
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700743static int _fh_socket_read(FH f, void* buf, int len) {
744 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800745 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700746 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700747 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
748 // that to reduce spam and confusion.
749 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700750 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800751 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700752 }
Spencer Low5200c662015-07-30 23:07:55 -0700753 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800754 result = -1;
755 }
756 return result;
757}
758
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700759static int _fh_socket_write(FH f, const void* buf, int len) {
760 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800761 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700762 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700763 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
764 // that to reduce spam and confusion.
765 if (err != WSAEWOULDBLOCK) {
766 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800767 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700768 }
Spencer Low5200c662015-07-30 23:07:55 -0700769 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800770 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700771 } else {
772 // According to https://code.google.com/p/chromium/issues/detail?id=27870
773 // Winsock Layered Service Providers may cause this.
774 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
775 << f->name << ", but " << result
776 << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800777 }
778 return result;
779}
780
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800781/**************************************************************************/
782/**************************************************************************/
783/***** *****/
784/***** replacement for libs/cutils/socket_xxxx.c *****/
785/***** *****/
786/**************************************************************************/
787/**************************************************************************/
788
789#include <winsock2.h>
790
791static int _winsock_init;
792
793static void
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800794_init_winsock( void )
795{
Spencer Low5200c662015-07-30 23:07:55 -0700796 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Low87e97ee2015-08-12 18:19:16 -0700797 // to WSAStartup() which offers no real benefit.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800798 if (!_winsock_init) {
799 WSADATA wsaData;
800 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
801 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800802 fatal("adb: could not initialize Winsock: %s",
803 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800804 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800805 _winsock_init = 1;
Spencer Low87e97ee2015-08-12 18:19:16 -0700806
807 // Note that we do not call atexit() to register WSACleanup to be called
808 // at normal process termination because:
809 // 1) When exit() is called, there are still threads actively using
810 // Winsock because we don't cleanly shutdown all threads, so it
811 // doesn't make sense to call WSACleanup() and may cause problems
812 // with those threads.
813 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
814 // calls WSACleanup() which tries to unload a DLL, which tries to
815 // grab the LoaderLock. This conflicts with the device_poll_thread
816 // which holds the LoaderLock because AdbWinApi.dll calls
817 // setupapi.dll which tries to load wintrust.dll which tries to load
818 // crypt32.dll which calls atexit() which tries to acquire the C
819 // Runtime lock that the other thread holds.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820 }
821}
822
Spencer Low677fb432015-09-29 15:05:29 -0700823// Map a socket type to an explicit socket protocol instead of using the socket
824// protocol of 0. Explicit socket protocols are used by most apps and we should
825// do the same to reduce the chance of exercising uncommon code-paths that might
826// have problems or that might load different Winsock service providers that
827// have problems.
828static int GetSocketProtocolFromSocketType(int type) {
829 switch (type) {
830 case SOCK_STREAM:
831 return IPPROTO_TCP;
832 case SOCK_DGRAM:
833 return IPPROTO_UDP;
834 default:
835 LOG(FATAL) << "Unknown socket type: " << type;
836 return 0;
837 }
838}
839
Spencer Low5200c662015-07-30 23:07:55 -0700840int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800841 struct sockaddr_in addr;
842 SOCKET s;
843
Spencer Low5200c662015-07-30 23:07:55 -0700844 unique_fh f(_fh_alloc(&_fh_socket_class));
845 if (!f) {
846 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700848 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849
850 if (!_winsock_init)
851 _init_winsock();
852
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));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859 if(s == INVALID_SOCKET) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700860 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800861 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700862 D("%s", error->c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700863 return -1;
864 }
865 f->fh_socket = s;
866
867 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700868 // Save err just in case inet_ntoa() or ntohs() changes the last error.
869 const DWORD err = WSAGetLastError();
870 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
871 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
David Pursell5f787ed2016-01-27 08:52:53 -0800872 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700873 D("could not connect to %s:%d: %s",
Spencer Low5200c662015-07-30 23:07:55 -0700874 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800875 return -1;
876 }
877
Spencer Low5200c662015-07-30 23:07:55 -0700878 const int fd = _fh_to_int(f.get());
879 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
880 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700881 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low5200c662015-07-30 23:07:55 -0700882 fd );
883 f.release();
884 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800885}
886
887#define LISTEN_BACKLOG 4
888
Spencer Low5200c662015-07-30 23:07:55 -0700889// interface_address is INADDR_LOOPBACK or INADDR_ANY.
890static int _network_server(int port, int type, u_long interface_address,
891 std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800892 struct sockaddr_in addr;
893 SOCKET s;
894 int n;
895
Spencer Low5200c662015-07-30 23:07:55 -0700896 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800897 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700898 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800899 return -1;
900 }
901
902 if (!_winsock_init)
903 _init_winsock();
904
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) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700914 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800915 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700916 D("%s", error->c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700917 return -1;
918 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800919
920 f->fh_socket = s;
921
Spencer Lowbf7c6052015-08-11 16:45:32 -0700922 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
923 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800924 n = 1;
Spencer Low5200c662015-07-30 23:07:55 -0700925 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
926 sizeof(n)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700927 *error = android::base::StringPrintf(
928 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800929 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700930 D("%s", error->c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700931 return -1;
932 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800933
Spencer Lowbf7c6052015-08-11 16:45:32 -0700934 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
935 // Save err just in case inet_ntoa() or ntohs() changes the last error.
936 const DWORD err = WSAGetLastError();
937 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
938 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
David Pursell5f787ed2016-01-27 08:52:53 -0800939 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700940 D("could not bind to %s:%d: %s",
Spencer Low5200c662015-07-30 23:07:55 -0700941 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800942 return -1;
943 }
944 if (type == SOCK_STREAM) {
Spencer Low5200c662015-07-30 23:07:55 -0700945 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700946 *error = android::base::StringPrintf("cannot listen on socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800947 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700948 D("could not listen on %s:%d: %s",
Spencer Low5200c662015-07-30 23:07:55 -0700949 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800950 return -1;
951 }
952 }
Spencer Low5200c662015-07-30 23:07:55 -0700953 const int fd = _fh_to_int(f.get());
954 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
955 interface_address == INADDR_LOOPBACK ? "lo" : "any",
956 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700957 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low5200c662015-07-30 23:07:55 -0700958 fd );
959 f.release();
960 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800961}
962
Spencer Low5200c662015-07-30 23:07:55 -0700963int network_loopback_server(int port, int type, std::string* error) {
964 return _network_server(port, type, INADDR_LOOPBACK, error);
965}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966
Spencer Low5200c662015-07-30 23:07:55 -0700967int network_inaddr_any_server(int port, int type, std::string* error) {
968 return _network_server(port, type, INADDR_ANY, error);
969}
970
971int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
972 unique_fh f(_fh_alloc(&_fh_socket_class));
973 if (!f) {
974 *error = strerror(errno);
975 return -1;
976 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800977
Elliott Hughes381cfa92015-07-23 17:12:58 -0700978 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800979
Spencer Low5200c662015-07-30 23:07:55 -0700980 struct addrinfo hints;
981 memset(&hints, 0, sizeof(hints));
982 hints.ai_family = AF_UNSPEC;
983 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700984 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700985
986 char port_str[16];
987 snprintf(port_str, sizeof(port_str), "%d", port);
988
989 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700990
991#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
992 // TODO: When the Android SDK tools increases the Windows system
Spencer Lowd21dc822015-11-12 15:20:15 -0800993 // requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700994#else
995 // Otherwise, keep using getaddrinfo(), or do runtime API detection
996 // with GetProcAddress("GetAddrInfoW").
997#endif
Spencer Low5200c662015-07-30 23:07:55 -0700998 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700999 *error = android::base::StringPrintf(
1000 "cannot resolve host '%s' and port %s: %s", host.c_str(),
David Pursell5f787ed2016-01-27 08:52:53 -08001001 port_str, android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001002 D("%s", error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001003 return -1;
1004 }
Spencer Low5200c662015-07-30 23:07:55 -07001005 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
1006 addrinfo(addrinfo_ptr, freeaddrinfo);
1007 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001008
Spencer Low5200c662015-07-30 23:07:55 -07001009 // TODO: Try all the addresses if there's more than one? This just uses
1010 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
1011 // which tries all addresses, takes a timeout and more.
1012 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
1013 addrinfo->ai_protocol);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001014 if(s == INVALID_SOCKET) {
Spencer Lowbf7c6052015-08-11 16:45:32 -07001015 *error = android::base::StringPrintf("cannot create socket: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08001016 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001017 D("%s", error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 return -1;
1019 }
1020 f->fh_socket = s;
1021
Spencer Low5200c662015-07-30 23:07:55 -07001022 // TODO: Implement timeouts for Windows. Seems like the default in theory
1023 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
1024 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -07001025 // TODO: Use WSAAddressToString or inet_ntop on address.
1026 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
1027 host.c_str(), port_str,
David Pursell5f787ed2016-01-27 08:52:53 -08001028 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001029 D("could not connect to %s:%s:%s: %s",
Spencer Low5200c662015-07-30 23:07:55 -07001030 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
1031 error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001032 return -1;
1033 }
1034
Spencer Low5200c662015-07-30 23:07:55 -07001035 const int fd = _fh_to_int(f.get());
1036 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
1037 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001038 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low5200c662015-07-30 23:07:55 -07001039 type != SOCK_STREAM ? "udp" : "tcp", fd );
1040 f.release();
1041 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001042}
1043
1044#undef accept
1045int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
1046{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001047 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001049 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001050 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -07001051 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001052 return -1;
1053 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001054
Spencer Low5200c662015-07-30 23:07:55 -07001055 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001056 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001057 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1058 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001059 return -1;
1060 }
1061
1062 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1063 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001064 const DWORD err = WSAGetLastError();
Spencer Low5200c662015-07-30 23:07:55 -07001065 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursell5f787ed2016-01-27 08:52:53 -08001066 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low5200c662015-07-30 23:07:55 -07001067 _socket_set_errno( err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001068 return -1;
1069 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001070
Spencer Low5200c662015-07-30 23:07:55 -07001071 const int fd = _fh_to_int(fh.get());
1072 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001073 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low5200c662015-07-30 23:07:55 -07001074 fh.release();
1075 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001076}
1077
1078
Spencer Lowf055c192015-01-25 14:40:16 -08001079int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001080{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001081 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001082
Spencer Lowf055c192015-01-25 14:40:16 -08001083 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001084 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001085 errno = EBADF;
1086 return -1;
1087 }
Spencer Low677fb432015-09-29 15:05:29 -07001088
1089 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1090 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1091 // auto-tuning.
1092
Spencer Low5200c662015-07-30 23:07:55 -07001093 int result = setsockopt( fh->fh_socket, level, optname,
1094 reinterpret_cast<const char*>(optval), optlen );
1095 if ( result == SOCKET_ERROR ) {
1096 const DWORD err = WSAGetLastError();
David Pursell5f787ed2016-01-27 08:52:53 -08001097 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1098 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001099 _socket_set_errno( err );
1100 result = -1;
1101 }
1102 return result;
1103}
1104
Josh Gao3777d2e2016-02-16 17:34:53 -08001105int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1106 FH fh = _fh_from_int(fd, __func__);
1107
1108 if (!fh || fh->clazz != &_fh_socket_class) {
1109 D("adb_getsockname: invalid fd %d", fd);
1110 errno = EBADF;
1111 return -1;
1112 }
1113
1114 int result = getsockname(fh->fh_socket, sockaddr, optlen);
1115 if (result == SOCKET_ERROR) {
1116 const DWORD err = WSAGetLastError();
1117 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1118 android::base::SystemErrorCodeToString(err).c_str());
1119 _socket_set_errno(err);
1120 result = -1;
1121 }
1122 return result;
1123}
Spencer Low5200c662015-07-30 23:07:55 -07001124
1125int adb_shutdown(int fd)
1126{
1127 FH f = _fh_from_int(fd, __func__);
1128
1129 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001130 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001131 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001132 return -1;
1133 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001134
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001135 D( "adb_shutdown: %s", f->name);
Spencer Low5200c662015-07-30 23:07:55 -07001136 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1137 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001138 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001139 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001140 _socket_set_errno(err);
1141 return -1;
1142 }
1143 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001144}
1145
Josh Gao3777d2e2016-02-16 17:34:53 -08001146// Emulate socketpair(2) by binding and connecting to a socket.
1147int adb_socketpair(int sv[2]) {
1148 int server = -1;
1149 int client = -1;
1150 int accepted = -1;
1151 sockaddr_storage addr_storage;
1152 socklen_t addr_len = sizeof(addr_storage);
1153 sockaddr_in* addr = nullptr;
1154 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001155
Josh Gao3777d2e2016-02-16 17:34:53 -08001156 server = network_loopback_server(0, SOCK_STREAM, &error);
1157 if (server < 0) {
1158 D("adb_socketpair: failed to create server: %s", error.c_str());
1159 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001160 }
1161
Josh Gao3777d2e2016-02-16 17:34:53 -08001162 if (adb_getsockname(server, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1163 D("adb_socketpair: adb_getsockname failed: %s", strerror(errno));
1164 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001165 }
1166
Josh Gao3777d2e2016-02-16 17:34:53 -08001167 if (addr_storage.ss_family != AF_INET) {
1168 D("adb_socketpair: unknown address family received: %d", addr_storage.ss_family);
1169 errno = ECONNABORTED;
1170 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171 }
1172
Josh Gao3777d2e2016-02-16 17:34:53 -08001173 addr = reinterpret_cast<sockaddr_in*>(&addr_storage);
1174 D("adb_socketpair: bound on port %d", ntohs(addr->sin_port));
1175 client = network_loopback_client(ntohs(addr->sin_port), SOCK_STREAM, &error);
1176 if (client < 0) {
1177 D("adb_socketpair: failed to connect client: %s", error.c_str());
1178 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001179 }
1180
Josh Gao3777d2e2016-02-16 17:34:53 -08001181 accepted = adb_socket_accept(server, nullptr, nullptr);
1182 if (accepted < 0) {
1183 const DWORD err = WSAGetLastError();
1184 D("adb_socketpair: failed to accept: %s",
1185 android::base::SystemErrorCodeToString(err).c_str());
1186 _socket_set_errno(err);
1187 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001188 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001189 adb_close(server);
1190 sv[0] = client;
1191 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001192 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001193
Josh Gao3777d2e2016-02-16 17:34:53 -08001194fail:
1195 if (server >= 0) {
1196 adb_close(server);
1197 }
1198 if (client >= 0) {
1199 adb_close(client);
1200 }
1201 if (accepted >= 0) {
1202 adb_close(accepted);
1203 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001204 return -1;
1205}
1206
Josh Gao3777d2e2016-02-16 17:34:53 -08001207bool set_file_block_mode(int fd, bool block) {
1208 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001209
Josh Gao3777d2e2016-02-16 17:34:53 -08001210 if (!fh || !fh->used) {
1211 errno = EBADF;
1212 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001213 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001214
Josh Gao3777d2e2016-02-16 17:34:53 -08001215 if (fh->clazz == &_fh_socket_class) {
1216 u_long x = !block;
1217 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
1218 _socket_set_errno(WSAGetLastError());
1219 return false;
1220 }
1221 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001222 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001223 errno = ENOTSOCK;
1224 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001225 }
1226}
1227
Spencer Lowa30b79a2015-11-15 16:29:36 -08001228static adb_mutex_t g_console_output_buffer_lock;
1229
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001230void
1231adb_sysdeps_init( void )
1232{
1233#define ADB_MUTEX(x) InitializeCriticalSection( & x );
1234#include "mutex_list.h"
1235 InitializeCriticalSection( &_win32_lock );
Spencer Lowa30b79a2015-11-15 16:29:36 -08001236 InitializeCriticalSection( &g_console_output_buffer_lock );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001237}
1238
Spencer Low50184062015-03-01 15:06:21 -08001239/**************************************************************************/
1240/**************************************************************************/
1241/***** *****/
1242/***** Console Window Terminal Emulation *****/
1243/***** *****/
1244/**************************************************************************/
1245/**************************************************************************/
1246
1247// This reads input from a Win32 console window and translates it into Unix
1248// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1249// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1250// is emulated instead of xterm because it is probably more popular than xterm:
1251// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1252// supports modern fonts, etc. It seems best to emulate the terminal that most
1253// Android developers use because they'll fix apps (the shell, etc.) to keep
1254// working with that terminal's emulation.
1255//
1256// The point of this emulation is not to be perfect or to solve all issues with
1257// console windows on Windows, but to be better than the original code which
1258// just called read() (which called ReadFile(), which called ReadConsoleA())
1259// which did not support Ctrl-C, tab completion, shell input line editing
1260// keys, server echo, and more.
1261//
1262// This implementation reconfigures the console with SetConsoleMode(), then
1263// calls ReadConsoleInput() to get raw input which it remaps to Unix
1264// terminal-style sequences which is returned via unix_read() which is used
1265// by the 'adb shell' command.
1266//
1267// Code organization:
1268//
David Pursellc5b8ad82015-10-28 14:29:51 -07001269// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001270// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1271// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1272// * _console_read() is the main code of the emulation.
1273
David Pursellc5b8ad82015-10-28 14:29:51 -07001274// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1275// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1276// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1277static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1278 // First check isatty(); this is very fast and eliminates most non-console
1279 // FDs, but returns 1 for both consoles and character devices like NUL.
1280#pragma push_macro("isatty")
1281#undef isatty
1282 if (!isatty(fd)) {
1283 return nullptr;
1284 }
1285#pragma pop_macro("isatty")
1286
1287 // To differentiate between character devices and consoles we need to get
1288 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1289 // GENERIC_READ permissions.
1290 const intptr_t intptr_handle = _get_osfhandle(fd);
1291 if (intptr_handle == -1) {
1292 return nullptr;
1293 }
1294 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1295 DWORD temp_mode = 0;
1296 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1297 return nullptr;
1298 }
1299
1300 return handle;
1301}
1302
1303// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1304static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001305 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1306 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001307 const int fd = fileno(stream);
1308 if (fd < 0) {
1309 return nullptr;
1310 }
1311 return _get_console_handle(fd);
1312}
1313
1314int unix_isatty(int fd) {
1315 return _get_console_handle(fd) ? 1 : 0;
1316}
Spencer Low50184062015-03-01 15:06:21 -08001317
Spencer Low32762f42015-11-10 19:17:16 -08001318// Get the next KEY_EVENT_RECORD that should be processed.
1319static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001320 for (;;) {
1321 DWORD read_count = 0;
1322 memset(input_record, 0, sizeof(*input_record));
1323 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001324 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001325 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001326 errno = EIO;
1327 return false;
1328 }
1329
1330 if (read_count == 0) { // should be impossible
1331 fatal("ReadConsoleInputA returned 0");
1332 }
1333
1334 if (read_count != 1) { // should be impossible
1335 fatal("ReadConsoleInputA did not return one input record");
1336 }
1337
Spencer Low2e02dc62015-11-07 17:34:39 -08001338 // If the console window is resized, emulate SIGWINCH by breaking out
1339 // of read() with errno == EINTR. Note that there is no event on
1340 // vertical resize because we don't give the console our own custom
1341 // screen buffer (with CreateConsoleScreenBuffer() +
1342 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1343 // supports scrollback, but doesn't seem to raise an event for vertical
1344 // window resize.
1345 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1346 errno = EINTR;
1347 return false;
1348 }
1349
Spencer Low50184062015-03-01 15:06:21 -08001350 if ((input_record->EventType == KEY_EVENT) &&
1351 (input_record->Event.KeyEvent.bKeyDown)) {
1352 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1353 fatal("ReadConsoleInputA returned a key event with zero repeat"
1354 " count");
1355 }
1356
1357 // Got an interesting INPUT_RECORD, so return
1358 return true;
1359 }
1360 }
1361}
1362
Spencer Low50184062015-03-01 15:06:21 -08001363static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1364 return (control_key_state & SHIFT_PRESSED) != 0;
1365}
1366
1367static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1368 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1369}
1370
1371static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1372 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1373}
1374
1375static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1376 return (control_key_state & NUMLOCK_ON) != 0;
1377}
1378
1379static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1380 return (control_key_state & CAPSLOCK_ON) != 0;
1381}
1382
1383static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1384 return (control_key_state & ENHANCED_KEY) != 0;
1385}
1386
1387// Constants from MSDN for ToAscii().
1388static const BYTE TOASCII_KEY_OFF = 0x00;
1389static const BYTE TOASCII_KEY_DOWN = 0x80;
1390static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1391
1392// Given a key event, ignore a modifier key and return the character that was
1393// entered without the modifier. Writes to *ch and returns the number of bytes
1394// written.
1395static size_t _get_char_ignoring_modifier(char* const ch,
1396 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1397 const WORD modifier) {
1398 // If there is no character from Windows, try ignoring the specified
1399 // modifier and look for a character. Note that if AltGr is being used,
1400 // there will be a character from Windows.
1401 if (key_event->uChar.AsciiChar == '\0') {
1402 // Note that we read the control key state from the passed in argument
1403 // instead of from key_event since the argument has been normalized.
1404 if (((modifier == VK_SHIFT) &&
1405 _is_shift_pressed(control_key_state)) ||
1406 ((modifier == VK_CONTROL) &&
1407 _is_ctrl_pressed(control_key_state)) ||
1408 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1409
1410 BYTE key_state[256] = {0};
1411 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1412 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1413 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1414 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1415 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1416 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1417 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1418 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1419
1420 // cause this modifier to be ignored
1421 key_state[modifier] = TOASCII_KEY_OFF;
1422
1423 WORD translated = 0;
1424 if (ToAscii(key_event->wVirtualKeyCode,
1425 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1426 // Ignoring the modifier, we found a character.
1427 *ch = (CHAR)translated;
1428 return 1;
1429 }
1430 }
1431 }
1432
1433 // Just use whatever Windows told us originally.
1434 *ch = key_event->uChar.AsciiChar;
1435
1436 // If the character from Windows is NULL, return a size of zero.
1437 return (*ch == '\0') ? 0 : 1;
1438}
1439
1440// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1441// but taking into account the shift key. This is because for a sequence like
1442// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1443// we want to find the character ')'.
1444//
1445// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1446// because it is the default key-sequence to switch the input language.
1447// This is configurable in the Region and Language control panel.
1448static __inline__ size_t _get_non_control_char(char* const ch,
1449 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1450 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1451 VK_CONTROL);
1452}
1453
1454// Get without Alt.
1455static __inline__ size_t _get_non_alt_char(char* const ch,
1456 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1457 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1458 VK_MENU);
1459}
1460
1461// Ignore the control key, find the character from Windows, and apply any
1462// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1463// *pch and returns number of bytes written.
1464static size_t _get_control_character(char* const pch,
1465 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1466 const size_t len = _get_non_control_char(pch, key_event,
1467 control_key_state);
1468
1469 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1470 char ch = *pch;
1471 switch (ch) {
1472 case '2':
1473 case '@':
1474 case '`':
1475 ch = '\0';
1476 break;
1477 case '3':
1478 case '[':
1479 case '{':
1480 ch = '\x1b';
1481 break;
1482 case '4':
1483 case '\\':
1484 case '|':
1485 ch = '\x1c';
1486 break;
1487 case '5':
1488 case ']':
1489 case '}':
1490 ch = '\x1d';
1491 break;
1492 case '6':
1493 case '^':
1494 case '~':
1495 ch = '\x1e';
1496 break;
1497 case '7':
1498 case '-':
1499 case '_':
1500 ch = '\x1f';
1501 break;
1502 case '8':
1503 ch = '\x7f';
1504 break;
1505 case '/':
1506 if (!_is_alt_pressed(control_key_state)) {
1507 ch = '\x1f';
1508 }
1509 break;
1510 case '?':
1511 if (!_is_alt_pressed(control_key_state)) {
1512 ch = '\x7f';
1513 }
1514 break;
1515 }
1516 *pch = ch;
1517 }
1518
1519 return len;
1520}
1521
1522static DWORD _normalize_altgr_control_key_state(
1523 const KEY_EVENT_RECORD* const key_event) {
1524 DWORD control_key_state = key_event->dwControlKeyState;
1525
1526 // If we're in an AltGr situation where the AltGr key is down (depending on
1527 // the keyboard layout, that might be the physical right alt key which
1528 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1529 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1530 // a character (which indicates that there was an AltGr mapping), then act
1531 // as if alt and control are not really down for the purposes of modifiers.
1532 // This makes it so that if the user with, say, a German keyboard layout
1533 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1534 // output the key and we don't see the Alt and Ctrl keys.
1535 if (_is_ctrl_pressed(control_key_state) &&
1536 _is_alt_pressed(control_key_state)
1537 && (key_event->uChar.AsciiChar != '\0')) {
1538 // Try to remove as few bits as possible to improve our chances of
1539 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1540 // Left-Alt + Right-Ctrl + AltGr.
1541 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1542 // Remove Right-Alt.
1543 control_key_state &= ~RIGHT_ALT_PRESSED;
1544 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1545 // pressed, Left-Ctrl is almost always set, except if the user
1546 // presses Right-Ctrl, then AltGr (in that specific order) for
1547 // whatever reason. At any rate, make sure the bit is not set.
1548 control_key_state &= ~LEFT_CTRL_PRESSED;
1549 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1550 // Remove Left-Alt.
1551 control_key_state &= ~LEFT_ALT_PRESSED;
1552 // Whichever Ctrl key is down, remove it from the state. We only
1553 // remove one key, to improve our chances of detecting the
1554 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1555 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1556 // Remove Left-Ctrl.
1557 control_key_state &= ~LEFT_CTRL_PRESSED;
1558 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1559 // Remove Right-Ctrl.
1560 control_key_state &= ~RIGHT_CTRL_PRESSED;
1561 }
1562 }
1563
1564 // Note that this logic isn't 100% perfect because Windows doesn't
1565 // allow us to detect all combinations because a physical AltGr key
1566 // press shows up as two bits, plus some combinations are ambiguous
1567 // about what is actually physically pressed.
1568 }
1569
1570 return control_key_state;
1571}
1572
1573// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1574// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1575// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1576// appropriately.
1577static DWORD _normalize_keypad_control_key_state(const WORD vk,
1578 const DWORD control_key_state) {
1579 if (!_is_numlock_on(control_key_state)) {
1580 return control_key_state;
1581 }
1582 if (!_is_enhanced_key(control_key_state)) {
1583 switch (vk) {
1584 case VK_INSERT: // 0
1585 case VK_DELETE: // .
1586 case VK_END: // 1
1587 case VK_DOWN: // 2
1588 case VK_NEXT: // 3
1589 case VK_LEFT: // 4
1590 case VK_CLEAR: // 5
1591 case VK_RIGHT: // 6
1592 case VK_HOME: // 7
1593 case VK_UP: // 8
1594 case VK_PRIOR: // 9
1595 return control_key_state | SHIFT_PRESSED;
1596 }
1597 }
1598
1599 return control_key_state;
1600}
1601
1602static const char* _get_keypad_sequence(const DWORD control_key_state,
1603 const char* const normal, const char* const shifted) {
1604 if (_is_shift_pressed(control_key_state)) {
1605 // Shift is pressed and NumLock is off
1606 return shifted;
1607 } else {
1608 // Shift is not pressed and NumLock is off, or,
1609 // Shift is pressed and NumLock is on, in which case we want the
1610 // NumLock and Shift to neutralize each other, thus, we want the normal
1611 // sequence.
1612 return normal;
1613 }
1614 // If Shift is not pressed and NumLock is on, a different virtual key code
1615 // is returned by Windows, which can be taken care of by a different case
1616 // statement in _console_read().
1617}
1618
1619// Write sequence to buf and return the number of bytes written.
1620static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1621 DWORD control_key_state, const char* const normal) {
1622 // Copy the base sequence into buf.
1623 const size_t len = strlen(normal);
1624 memcpy(buf, normal, len);
1625
1626 int code = 0;
1627
1628 control_key_state = _normalize_keypad_control_key_state(vk,
1629 control_key_state);
1630
1631 if (_is_shift_pressed(control_key_state)) {
1632 code |= 0x1;
1633 }
1634 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1635 code |= 0x2;
1636 }
1637 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1638 code |= 0x4;
1639 }
1640 // If some modifier was held down, then we need to insert the modifier code
1641 if (code != 0) {
1642 if (len == 0) {
1643 // Should be impossible because caller should pass a string of
1644 // non-zero length.
1645 return 0;
1646 }
1647 size_t index = len - 1;
1648 const char lastChar = buf[index];
1649 if (lastChar != '~') {
1650 buf[index++] = '1';
1651 }
1652 buf[index++] = ';'; // modifier separator
1653 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1654 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1655 buf[index++] = '1' + code;
1656 buf[index++] = lastChar; // move ~ (or other last char) to the end
1657 return index;
1658 }
1659 return len;
1660}
1661
1662// Write sequence to buf and return the number of bytes written.
1663static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1664 const DWORD control_key_state, const char* const normal,
1665 const char shifted) {
1666 if (_is_shift_pressed(control_key_state)) {
1667 // Shift is pressed and NumLock is off
1668 if (shifted != '\0') {
1669 buf[0] = shifted;
1670 return sizeof(buf[0]);
1671 } else {
1672 return 0;
1673 }
1674 } else {
1675 // Shift is not pressed and NumLock is off, or,
1676 // Shift is pressed and NumLock is on, in which case we want the
1677 // NumLock and Shift to neutralize each other, thus, we want the normal
1678 // sequence.
1679 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1680 }
1681 // If Shift is not pressed and NumLock is on, a different virtual key code
1682 // is returned by Windows, which can be taken care of by a different case
1683 // statement in _console_read().
1684}
1685
1686// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1687// Standard German. Figure this out at runtime so we know what to output for
1688// Shift-VK_DELETE.
1689static char _get_decimal_char() {
1690 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1691}
1692
1693// Prefix the len bytes in buf with the escape character, and then return the
1694// new buffer length.
1695size_t _escape_prefix(char* const buf, const size_t len) {
1696 // If nothing to prefix, don't do anything. We might be called with
1697 // len == 0, if alt was held down with a dead key which produced nothing.
1698 if (len == 0) {
1699 return 0;
1700 }
1701
1702 memmove(&buf[1], buf, len);
1703 buf[0] = '\x1b';
1704 return len + 1;
1705}
1706
Spencer Low32762f42015-11-10 19:17:16 -08001707// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001708static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001709
1710// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1711// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001712static int _console_read(const HANDLE console, void* buf, size_t len) {
1713 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001714 // Read of zero bytes should not block waiting for something from the console.
1715 if (len == 0) {
1716 return 0;
1717 }
1718
1719 // Flush as much as possible from input buffer.
1720 if (!g_console_input_buffer.empty()) {
1721 const int bytes_read = std::min(len, g_console_input_buffer.size());
1722 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1723 const auto begin = g_console_input_buffer.begin();
1724 g_console_input_buffer.erase(begin, begin + bytes_read);
1725 return bytes_read;
1726 }
1727
1728 // Read from the actual console. This may block until input.
1729 INPUT_RECORD input_record;
1730 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001731 return -1;
1732 }
1733
Spencer Low32762f42015-11-10 19:17:16 -08001734 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001735 const WORD vk = key_event->wVirtualKeyCode;
1736 const CHAR ch = key_event->uChar.AsciiChar;
1737 const DWORD control_key_state = _normalize_altgr_control_key_state(
1738 key_event);
1739
1740 // The following emulation code should write the output sequence to
1741 // either seqstr or to seqbuf and seqbuflen.
1742 const char* seqstr = NULL; // NULL terminated C-string
1743 // Enough space for max sequence string below, plus modifiers and/or
1744 // escape prefix.
1745 char seqbuf[16];
1746 size_t seqbuflen = 0; // Space used in seqbuf.
1747
1748#define MATCH(vk, normal) \
1749 case (vk): \
1750 { \
1751 seqstr = (normal); \
1752 } \
1753 break;
1754
1755 // Modifier keys should affect the output sequence.
1756#define MATCH_MODIFIER(vk, normal) \
1757 case (vk): \
1758 { \
1759 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1760 control_key_state, (normal)); \
1761 } \
1762 break;
1763
1764 // The shift key should affect the output sequence.
1765#define MATCH_KEYPAD(vk, normal, shifted) \
1766 case (vk): \
1767 { \
1768 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1769 (shifted)); \
1770 } \
1771 break;
1772
1773 // The shift key and other modifier keys should affect the output
1774 // sequence.
1775#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1776 case (vk): \
1777 { \
1778 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1779 control_key_state, (normal), (shifted)); \
1780 } \
1781 break;
1782
1783#define ESC "\x1b"
1784#define CSI ESC "["
1785#define SS3 ESC "O"
1786
1787 // Only support normal mode, not application mode.
1788
1789 // Enhanced keys:
1790 // * 6-pack: insert, delete, home, end, page up, page down
1791 // * cursor keys: up, down, right, left
1792 // * keypad: divide, enter
1793 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1794 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1795 if (_is_enhanced_key(control_key_state)) {
1796 switch (vk) {
1797 case VK_RETURN: // Enter key on keypad
1798 if (_is_ctrl_pressed(control_key_state)) {
1799 seqstr = "\n";
1800 } else {
1801 seqstr = "\r";
1802 }
1803 break;
1804
1805 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1806 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1807
1808 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1809 // will be fixed soon to match xterm which sends CSI "F" and
1810 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1811 MATCH(VK_END, CSI "F");
1812 MATCH(VK_HOME, CSI "H");
1813
1814 MATCH_MODIFIER(VK_LEFT, CSI "D");
1815 MATCH_MODIFIER(VK_UP, CSI "A");
1816 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1817 MATCH_MODIFIER(VK_DOWN, CSI "B");
1818
1819 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1820 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1821
1822 MATCH(VK_DIVIDE, "/");
1823 }
1824 } else { // Non-enhanced keys:
1825 switch (vk) {
1826 case VK_BACK: // backspace
1827 if (_is_alt_pressed(control_key_state)) {
1828 seqstr = ESC "\x7f";
1829 } else {
1830 seqstr = "\x7f";
1831 }
1832 break;
1833
1834 case VK_TAB:
1835 if (_is_shift_pressed(control_key_state)) {
1836 seqstr = CSI "Z";
1837 } else {
1838 seqstr = "\t";
1839 }
1840 break;
1841
1842 // Number 5 key in keypad when NumLock is off, or if NumLock is
1843 // on and Shift is down.
1844 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1845
1846 case VK_RETURN: // Enter key on main keyboard
1847 if (_is_alt_pressed(control_key_state)) {
1848 seqstr = ESC "\n";
1849 } else if (_is_ctrl_pressed(control_key_state)) {
1850 seqstr = "\n";
1851 } else {
1852 seqstr = "\r";
1853 }
1854 break;
1855
1856 // VK_ESCAPE: Don't do any special handling. The OS uses many
1857 // of the sequences with Escape and many of the remaining
1858 // sequences don't produce bKeyDown messages, only !bKeyDown
1859 // for whatever reason.
1860
1861 case VK_SPACE:
1862 if (_is_alt_pressed(control_key_state)) {
1863 seqstr = ESC " ";
1864 } else if (_is_ctrl_pressed(control_key_state)) {
1865 seqbuf[0] = '\0'; // NULL char
1866 seqbuflen = 1;
1867 } else {
1868 seqstr = " ";
1869 }
1870 break;
1871
1872 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1873 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1874
1875 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1876 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1877
1878 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1879 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1880 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1881 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1882
1883 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1884 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1885 _get_decimal_char());
1886
1887 case 0x30: // 0
1888 case 0x31: // 1
1889 case 0x39: // 9
1890 case VK_OEM_1: // ;:
1891 case VK_OEM_PLUS: // =+
1892 case VK_OEM_COMMA: // ,<
1893 case VK_OEM_PERIOD: // .>
1894 case VK_OEM_7: // '"
1895 case VK_OEM_102: // depends on keyboard, could be <> or \|
1896 case VK_OEM_2: // /?
1897 case VK_OEM_3: // `~
1898 case VK_OEM_4: // [{
1899 case VK_OEM_5: // \|
1900 case VK_OEM_6: // ]}
1901 {
1902 seqbuflen = _get_control_character(seqbuf, key_event,
1903 control_key_state);
1904
1905 if (_is_alt_pressed(control_key_state)) {
1906 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1907 }
1908 }
1909 break;
1910
1911 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001912 case 0x33: // 3
1913 case 0x34: // 4
1914 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001915 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001916 case 0x37: // 7
1917 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001918 case VK_OEM_MINUS: // -_
1919 {
1920 seqbuflen = _get_control_character(seqbuf, key_event,
1921 control_key_state);
1922
1923 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1924 // prefix with escape.
1925 if (_is_alt_pressed(control_key_state) &&
1926 !(_is_ctrl_pressed(control_key_state) &&
1927 !_is_shift_pressed(control_key_state))) {
1928 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1929 }
1930 }
1931 break;
1932
Spencer Low50184062015-03-01 15:06:21 -08001933 case 0x41: // a
1934 case 0x42: // b
1935 case 0x43: // c
1936 case 0x44: // d
1937 case 0x45: // e
1938 case 0x46: // f
1939 case 0x47: // g
1940 case 0x48: // h
1941 case 0x49: // i
1942 case 0x4a: // j
1943 case 0x4b: // k
1944 case 0x4c: // l
1945 case 0x4d: // m
1946 case 0x4e: // n
1947 case 0x4f: // o
1948 case 0x50: // p
1949 case 0x51: // q
1950 case 0x52: // r
1951 case 0x53: // s
1952 case 0x54: // t
1953 case 0x55: // u
1954 case 0x56: // v
1955 case 0x57: // w
1956 case 0x58: // x
1957 case 0x59: // y
1958 case 0x5a: // z
1959 {
1960 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1961 control_key_state);
1962
1963 // If Alt is pressed, then prefix with escape.
1964 if (_is_alt_pressed(control_key_state)) {
1965 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1966 }
1967 }
1968 break;
1969
1970 // These virtual key codes are generated by the keys on the
1971 // keypad *when NumLock is on* and *Shift is up*.
1972 MATCH(VK_NUMPAD0, "0");
1973 MATCH(VK_NUMPAD1, "1");
1974 MATCH(VK_NUMPAD2, "2");
1975 MATCH(VK_NUMPAD3, "3");
1976 MATCH(VK_NUMPAD4, "4");
1977 MATCH(VK_NUMPAD5, "5");
1978 MATCH(VK_NUMPAD6, "6");
1979 MATCH(VK_NUMPAD7, "7");
1980 MATCH(VK_NUMPAD8, "8");
1981 MATCH(VK_NUMPAD9, "9");
1982
1983 MATCH(VK_MULTIPLY, "*");
1984 MATCH(VK_ADD, "+");
1985 MATCH(VK_SUBTRACT, "-");
1986 // VK_DECIMAL is generated by the . key on the keypad *when
1987 // NumLock is on* and *Shift is up* and the sequence is not
1988 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1989 // Windows Security screen to come up).
1990 case VK_DECIMAL:
1991 // U.S. English uses '.', Germany German uses ','.
1992 seqbuflen = _get_non_control_char(seqbuf, key_event,
1993 control_key_state);
1994 break;
1995
1996 MATCH_MODIFIER(VK_F1, SS3 "P");
1997 MATCH_MODIFIER(VK_F2, SS3 "Q");
1998 MATCH_MODIFIER(VK_F3, SS3 "R");
1999 MATCH_MODIFIER(VK_F4, SS3 "S");
2000 MATCH_MODIFIER(VK_F5, CSI "15~");
2001 MATCH_MODIFIER(VK_F6, CSI "17~");
2002 MATCH_MODIFIER(VK_F7, CSI "18~");
2003 MATCH_MODIFIER(VK_F8, CSI "19~");
2004 MATCH_MODIFIER(VK_F9, CSI "20~");
2005 MATCH_MODIFIER(VK_F10, CSI "21~");
2006 MATCH_MODIFIER(VK_F11, CSI "23~");
2007 MATCH_MODIFIER(VK_F12, CSI "24~");
2008
2009 MATCH_MODIFIER(VK_F13, CSI "25~");
2010 MATCH_MODIFIER(VK_F14, CSI "26~");
2011 MATCH_MODIFIER(VK_F15, CSI "28~");
2012 MATCH_MODIFIER(VK_F16, CSI "29~");
2013 MATCH_MODIFIER(VK_F17, CSI "31~");
2014 MATCH_MODIFIER(VK_F18, CSI "32~");
2015 MATCH_MODIFIER(VK_F19, CSI "33~");
2016 MATCH_MODIFIER(VK_F20, CSI "34~");
2017
2018 // MATCH_MODIFIER(VK_F21, ???);
2019 // MATCH_MODIFIER(VK_F22, ???);
2020 // MATCH_MODIFIER(VK_F23, ???);
2021 // MATCH_MODIFIER(VK_F24, ???);
2022 }
2023 }
2024
2025#undef MATCH
2026#undef MATCH_MODIFIER
2027#undef MATCH_KEYPAD
2028#undef MATCH_MODIFIER_KEYPAD
2029#undef ESC
2030#undef CSI
2031#undef SS3
2032
2033 const char* out;
2034 size_t outlen;
2035
2036 // Check for output in any of:
2037 // * seqstr is set (and strlen can be used to determine the length).
2038 // * seqbuf and seqbuflen are set
2039 // Fallback to ch from Windows.
2040 if (seqstr != NULL) {
2041 out = seqstr;
2042 outlen = strlen(seqstr);
2043 } else if (seqbuflen > 0) {
2044 out = seqbuf;
2045 outlen = seqbuflen;
2046 } else if (ch != '\0') {
2047 // Use whatever Windows told us it is.
2048 seqbuf[0] = ch;
2049 seqbuflen = 1;
2050 out = seqbuf;
2051 outlen = seqbuflen;
2052 } else {
2053 // No special handling for the virtual key code and Windows isn't
2054 // telling us a character code, then we don't know how to translate
2055 // the key press.
2056 //
2057 // Consume the input and 'continue' to cause us to get a new key
2058 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002059 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002060 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002061 continue;
2062 }
2063
Spencer Low32762f42015-11-10 19:17:16 -08002064 // put output wRepeatCount times into g_console_input_buffer
2065 while (key_event->wRepeatCount-- > 0) {
2066 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002067 }
2068
Spencer Low32762f42015-11-10 19:17:16 -08002069 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002070 }
2071}
2072
2073static DWORD _old_console_mode; // previous GetConsoleMode() result
2074static HANDLE _console_handle; // when set, console mode should be restored
2075
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002076void stdin_raw_init() {
2077 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002078 if (in == nullptr) {
2079 return;
2080 }
Spencer Low50184062015-03-01 15:06:21 -08002081
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002082 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2083 // calling the process Ctrl-C routine (configured by
2084 // SetConsoleCtrlHandler()).
2085 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2086 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2087 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002088 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2089 ENABLE_LINE_INPUT |
2090 ENABLE_ECHO_INPUT);
2091 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2092 new_console_mode |= ENABLE_WINDOW_INPUT;
2093
2094 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002095 // This really should not fail.
2096 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002097 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002098 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002099
2100 // Once this is set, it means that stdin has been configured for
2101 // reading from and that the old console mode should be restored later.
2102 _console_handle = in;
2103
2104 // Note that we don't need to configure C Runtime line-ending
2105 // translation because _console_read() does not call the C Runtime to
2106 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002107}
2108
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002109void stdin_raw_restore() {
2110 if (_console_handle != NULL) {
2111 const HANDLE in = _console_handle;
2112 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002113
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002114 if (!SetConsoleMode(in, _old_console_mode)) {
2115 // This really should not fail.
2116 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002117 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002118 }
2119 }
2120}
2121
Spencer Low2e02dc62015-11-07 17:34:39 -08002122// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2123int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08002124 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2125 // If it is a request to read from stdin, and stdin_raw_init() has been
2126 // called, and it successfully configured the console, then read from
2127 // the console using Win32 console APIs and partially emulate a unix
2128 // terminal.
2129 return _console_read(_console_handle, buf, len);
2130 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002131 // On older versions of Windows (definitely 7, definitely not 10),
2132 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002133 // we need to limit the read size.
2134 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002135 len = 4096;
2136 }
Spencer Low50184062015-03-01 15:06:21 -08002137 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002138 // can do LF/CR translation (which is overridable with _setmode()).
2139 // Undefine the macro that is set in sysdeps.h which bans calls to
2140 // plain read() in favor of unix_read() or adb_read().
2141#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002142#undef read
2143 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002144#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002145 }
2146}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002147
2148/**************************************************************************/
2149/**************************************************************************/
2150/***** *****/
2151/***** Unicode support *****/
2152/***** *****/
2153/**************************************************************************/
2154/**************************************************************************/
2155
2156// This implements support for using files with Unicode filenames and for
2157// outputting Unicode text to a Win32 console window. This is inspired from
2158// http://utf8everywhere.org/.
2159//
2160// Background
2161// ----------
2162//
2163// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2164// filenames to APIs such as open(). This works because filenames are largely
2165// opaque 'cookies' (perhaps excluding path separators).
2166//
2167// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2168// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2169// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2170// CreateFile() API is really just a macro that adds the W/A based on whether
2171// the UNICODE preprocessor symbol is defined).
2172//
2173// Options
2174// -------
2175//
2176// Thus, to write a portable program, there are a few options:
2177//
2178// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2179// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2180// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2181// open() API.
2182//
2183// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2184// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2185// potentially touching a lot of code.
2186//
2187// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2188// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2189// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2190// or C Runtime API.
2191//
2192// The Choice
2193// ----------
2194//
Spencer Lowd21dc822015-11-12 15:20:15 -08002195// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2196// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002197// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002198// args that are passed to main() at the beginning of program startup. We also use
2199// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002200// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2201//
2202// Unicode console output
2203// ----------------------
2204//
2205// The way to output Unicode to a Win32 console window is to call
2206// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002207// such as Lucida Console or Consolas, and in the case of East Asian languages
2208// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2209// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2210// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002211//
2212// The problem is getting the C Runtime to make fprintf and related APIs call
2213// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2214// promising, but the various modes have issues:
2215//
2216// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2217// UTF-16 do not display properly.
2218// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2219// totally wrong.
2220// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2221// handler to be called (upon a later I/O call), aborting the process.
2222// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2223// to output nothing.
2224//
2225// So the only solution is to write our own adb_fprintf() that converts UTF-8
2226// to UTF-16 and then calls WriteConsoleW().
2227
2228
Spencer Lowcf4ff642015-05-11 01:08:48 -07002229// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2230// be passed to main().
2231NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2232 narrow_args = new char*[argc + 1];
2233
2234 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002235 std::string arg_narrow;
2236 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2237 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2238 }
2239 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002240 }
2241 narrow_args[argc] = nullptr; // terminate
2242}
2243
2244NarrowArgs::~NarrowArgs() {
2245 if (narrow_args != nullptr) {
2246 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2247 free(*argp);
2248 }
2249 delete[] narrow_args;
2250 narrow_args = nullptr;
2251 }
2252}
2253
2254int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002255 std::wstring path_wide;
2256 if (!android::base::UTF8ToWide(path, &path_wide)) {
2257 return -1;
2258 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002259 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002260 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002261 } else {
2262 int mode;
2263 va_list args;
2264 va_start(args, options);
2265 mode = va_arg(args, int);
2266 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002267 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002268 }
2269}
2270
2271// Version of stat() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002272int adb_stat(const char* path, struct adb_stat* s) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002273#pragma push_macro("wstat")
2274// This definition of wstat seems to be missing from <sys/stat.h>.
2275#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
2276#ifdef _USE_32BIT_TIME_T
2277#define wstat _wstat32i64
2278#else
2279#define wstat _wstat64
2280#endif
2281#else
2282// <sys/stat.h> has a function prototype for wstat() that should be available.
2283#endif
2284
Spencer Lowd21dc822015-11-12 15:20:15 -08002285 std::wstring path_wide;
2286 if (!android::base::UTF8ToWide(path, &path_wide)) {
2287 return -1;
2288 }
2289
2290 return wstat(path_wide.c_str(), s);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002291
2292#pragma pop_macro("wstat")
2293}
2294
2295// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002296DIR* adb_opendir(const char* path) {
2297 std::wstring path_wide;
2298 if (!android::base::UTF8ToWide(path, &path_wide)) {
2299 return nullptr;
2300 }
2301
Spencer Lowcf4ff642015-05-11 01:08:48 -07002302 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2303 // the fields, but right now all the callers treat the structure as
2304 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002305 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002306}
2307
2308// Version of readdir() that returns UTF-8 paths.
2309struct dirent* adb_readdir(DIR* dir) {
2310 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2311 struct _wdirent* const went = _wreaddir(wdir);
2312 if (went == nullptr) {
2313 return nullptr;
2314 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002315
Spencer Lowcf4ff642015-05-11 01:08:48 -07002316 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002317 std::string name_utf8;
2318 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2319 return nullptr;
2320 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002321
2322 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2323 // space for UTF-16 wchar_t's) with UTF-8 char's.
2324 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2325
2326 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2327 // Name too big to fit in existing buffer.
2328 errno = ENOMEM;
2329 return nullptr;
2330 }
2331
2332 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2333 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2334 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2335 // bigger than the caller expects because they expect a dirent structure
2336 // which has a smaller d_name field. Ignore this since the caller should be
2337 // resilient.
2338
2339 // Rewrite the UTF-16 d_name field to UTF-8.
2340 strcpy(ent->d_name, name_utf8.c_str());
2341
2342 return ent;
2343}
2344
2345// Version of closedir() to go with our version of adb_opendir().
2346int adb_closedir(DIR* dir) {
2347 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2348}
2349
2350// Version of unlink() that takes a UTF-8 path.
2351int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002352 std::wstring wpath;
2353 if (!android::base::UTF8ToWide(path, &wpath)) {
2354 return -1;
2355 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002356
2357 int rc = _wunlink(wpath.c_str());
2358
2359 if (rc == -1 && errno == EACCES) {
2360 /* unlink returns EACCES when the file is read-only, so we first */
2361 /* try to make it writable, then unlink again... */
2362 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2363 if (rc == 0)
2364 rc = _wunlink(wpath.c_str());
2365 }
2366 return rc;
2367}
2368
2369// Version of mkdir() that takes a UTF-8 path.
2370int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002371 std::wstring path_wide;
2372 if (!android::base::UTF8ToWide(path, &path_wide)) {
2373 return -1;
2374 }
2375
2376 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002377}
2378
2379// Version of utime() that takes a UTF-8 path.
2380int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002381 std::wstring path_wide;
2382 if (!android::base::UTF8ToWide(path, &path_wide)) {
2383 return -1;
2384 }
2385
Spencer Lowcf4ff642015-05-11 01:08:48 -07002386 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2387 "utimbuf and _utimbuf should be the same size because they both "
2388 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002389 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002390}
2391
2392// Version of chmod() that takes a UTF-8 path.
2393int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002394 std::wstring path_wide;
2395 if (!android::base::UTF8ToWide(path, &path_wide)) {
2396 return -1;
2397 }
2398
2399 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002400}
2401
Spencer Lowa30b79a2015-11-15 16:29:36 -08002402// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2403static inline size_t utf8_codepoint_len(uint8_t ch) {
2404 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2405}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002406
Spencer Lowa30b79a2015-11-15 16:29:36 -08002407namespace internal {
2408
2409// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2410// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2411// remaining_bytes.
2412size_t ParseCompleteUTF8(const char* const first, const char* const last,
2413 std::vector<char>* const remaining_bytes) {
2414 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2415 // Current_after points one byte past the current byte to be examined.
2416 for (const char* current_after = last; current_after != first; --current_after) {
2417 const char* const current = current_after - 1;
2418 const char ch = *current;
2419 const char kHighBit = 0x80u;
2420 const char kTwoHighestBits = 0xC0u;
2421 if ((ch & kHighBit) == 0) { // high bit not set
2422 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2423 // bytes with no leading byte, so return the entire buffer.
2424 break;
2425 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2426 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2427 const size_t bytes_available = last - current;
2428 if (bytes_available < utf8_codepoint_len(ch)) {
2429 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2430 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2431 // to remaining_bytes.
2432 remaining_bytes->insert(remaining_bytes->end(), current, last);
2433 return current - first;
2434 } else {
2435 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2436 // trailing bytes with no lead byte, so return the entire buffer.
2437 break;
2438 }
2439 } else {
2440 // Trailing byte, so keep going backwards looking for the lead byte.
2441 }
2442 }
2443
2444 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2445 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2446 // so that they can be processed.
2447 return last - first;
2448}
2449
2450}
2451
2452// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2453// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2454// This matches the behavior of Linux.
2455// Protected by g_console_output_buffer_lock.
2456static auto& g_console_output_buffer = *new std::vector<char>();
2457
2458// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2459static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2460 HANDLE console) {
2461 const int saved_errno = errno;
2462 std::vector<char> combined_buffer;
2463
2464 // Complete UTF-8 sequences that should be immediately written to the console.
2465 const char* utf8;
2466 size_t utf8_size;
2467
2468 adb_mutex_lock(&g_console_output_buffer_lock);
2469 if (g_console_output_buffer.empty()) {
2470 // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2471 // common case with plain ASCII), parse buf directly.
2472 utf8 = buf;
2473 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
2474 } else {
2475 // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2476 // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
2477 // combined_buffer, then parse it all together.
2478 combined_buffer.swap(g_console_output_buffer);
2479 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
2480
2481 utf8 = combined_buffer.data();
2482 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2483 &g_console_output_buffer);
2484 }
2485 adb_mutex_unlock(&g_console_output_buffer_lock);
2486
2487 std::wstring utf16;
2488
2489 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2490 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2491 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002492 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002493 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002494
2495 // Note that this does not do \n => \r\n translation because that
2496 // doesn't seem necessary for the Windows console. For the Windows
2497 // console \r moves to the beginning of the line and \n moves to a new
2498 // line.
2499
2500 // Flush any stream buffering so that our output is afterwards which
2501 // makes sense because our call is afterwards.
2502 (void)fflush(stream);
2503
2504 // Write UTF-16 to the console.
2505 DWORD written = 0;
Spencer Lowa30b79a2015-11-15 16:29:36 -08002506 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002507 errno = EIO;
2508 return -1;
2509 }
2510
Spencer Lowa30b79a2015-11-15 16:29:36 -08002511 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2512 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2513 // matches the Linux behavior.
2514 errno = saved_errno;
2515 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002516}
2517
2518// Function prototype because attributes cannot be placed on func definitions.
2519static int _console_vfprintf(const HANDLE console, FILE* stream,
2520 const char *format, va_list ap)
2521 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2522
2523// Internal function to format a UTF-8 string and write it to a Win32 console.
2524// Returns -1 on error.
2525static int _console_vfprintf(const HANDLE console, FILE* stream,
2526 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002527 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002528 std::string output_utf8;
2529
2530 // Format the string.
2531 // This could throw std::bad_alloc.
2532 android::base::StringAppendV(&output_utf8, format, ap);
2533
Spencer Lowa30b79a2015-11-15 16:29:36 -08002534 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2535 console);
2536 if (result != -1) {
2537 errno = saved_errno;
2538 } else {
2539 // If -1 was returned, errno has been set.
2540 }
2541 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002542}
2543
2544// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2545// Windows console.
2546int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2547 const HANDLE console = _get_console_handle(stream);
2548
2549 // If there is an associated Win32 console, write to it specially,
2550 // otherwise defer to the regular C Runtime, passing it UTF-8.
2551 if (console != NULL) {
2552 return _console_vfprintf(console, stream, format, ap);
2553 } else {
2554 // If vfprintf is a macro, undefine it, so we can call the real
2555 // C Runtime API.
2556#pragma push_macro("vfprintf")
2557#undef vfprintf
2558 return vfprintf(stream, format, ap);
2559#pragma pop_macro("vfprintf")
2560 }
2561}
2562
Spencer Lowa30b79a2015-11-15 16:29:36 -08002563// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2564int adb_vprintf(const char *format, va_list ap) {
2565 return adb_vfprintf(stdout, format, ap);
2566}
2567
Spencer Lowcf4ff642015-05-11 01:08:48 -07002568// Version of fprintf() that takes UTF-8 and can write Unicode to a
2569// Windows console.
2570int adb_fprintf(FILE *stream, const char *format, ...) {
2571 va_list ap;
2572 va_start(ap, format);
2573 const int result = adb_vfprintf(stream, format, ap);
2574 va_end(ap);
2575
2576 return result;
2577}
2578
2579// Version of printf() that takes UTF-8 and can write Unicode to a
2580// Windows console.
2581int adb_printf(const char *format, ...) {
2582 va_list ap;
2583 va_start(ap, format);
2584 const int result = adb_vfprintf(stdout, format, ap);
2585 va_end(ap);
2586
2587 return result;
2588}
2589
2590// Version of fputs() that takes UTF-8 and can write Unicode to a
2591// Windows console.
2592int adb_fputs(const char* buf, FILE* stream) {
2593 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2594 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002595 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002596 return adb_fprintf(stream, "%s", buf);
2597}
2598
2599// Version of fputc() that takes UTF-8 and can write Unicode to a
2600// Windows console.
2601int adb_fputc(int ch, FILE* stream) {
2602 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002603 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002604 return EOF;
2605 }
2606 // For success, fputc returns the char, cast to unsigned char, then to int.
2607 return static_cast<unsigned char>(ch);
2608}
2609
Spencer Lowa30b79a2015-11-15 16:29:36 -08002610// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2611int adb_putchar(int ch) {
2612 return adb_fputc(ch, stdout);
2613}
2614
2615// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2616int adb_puts(const char* buf) {
2617 // adb_printf returns -1 on error, which is conveniently the same as EOF
2618 // which puts (and hence adb_puts) should return on error.
2619 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2620 return adb_printf("%s\n", buf);
2621}
2622
Spencer Lowcf4ff642015-05-11 01:08:48 -07002623// Internal function to write UTF-8 to a Win32 console. Returns the number of
2624// items (of length size) written. On error, returns a short item count or 0.
2625static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2626 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002627 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2628 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002629 if (result == -1) {
2630 return 0;
2631 }
2632 return result / size;
2633}
2634
2635// Version of fwrite() that takes UTF-8 and can write Unicode to a
2636// Windows console.
2637size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2638 const HANDLE console = _get_console_handle(stream);
2639
2640 // If there is an associated Win32 console, write to it specially,
2641 // otherwise defer to the regular C Runtime, passing it UTF-8.
2642 if (console != NULL) {
2643 return _console_fwrite(ptr, size, nmemb, stream, console);
2644 } else {
2645 // If fwrite is a macro, undefine it, so we can call the real
2646 // C Runtime API.
2647#pragma push_macro("fwrite")
2648#undef fwrite
2649 return fwrite(ptr, size, nmemb, stream);
2650#pragma pop_macro("fwrite")
2651 }
2652}
2653
2654// Version of fopen() that takes a UTF-8 filename and can access a file with
2655// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002656FILE* adb_fopen(const char* path, const char* mode) {
2657 std::wstring path_wide;
2658 if (!android::base::UTF8ToWide(path, &path_wide)) {
2659 return nullptr;
2660 }
2661
2662 std::wstring mode_wide;
2663 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2664 return nullptr;
2665 }
2666
2667 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002668}
2669
Spencer Lowe6ae5732015-09-08 17:13:04 -07002670// Return a lowercase version of the argument. Uses C Runtime tolower() on
2671// each byte which is not UTF-8 aware, and theoretically uses the current C
2672// Runtime locale (which in practice is not changed, so this becomes a ASCII
2673// conversion).
2674static std::string ToLower(const std::string& anycase) {
2675 // copy string
2676 std::string str(anycase);
2677 // transform the copy
2678 std::transform(str.begin(), str.end(), str.begin(), tolower);
2679 return str;
2680}
2681
2682extern "C" int main(int argc, char** argv);
2683
2684// Link with -municode to cause this wmain() to be used as the program
2685// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2686// regular main() with UTF-8 args.
2687extern "C" int wmain(int argc, wchar_t **argv) {
2688 // Convert args from UTF-16 to UTF-8 and pass that to main().
2689 NarrowArgs narrow_args(argc, argv);
2690 return main(argc, narrow_args.data());
2691}
2692
Spencer Lowcf4ff642015-05-11 01:08:48 -07002693// Shadow UTF-8 environment variable name/value pairs that are created from
2694// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002695// currently updated if putenv, setenv, unsetenv are called. Note that no
2696// thread synchronization is done, but we're called early enough in
2697// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002698static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002699
2700// Make sure that shadow UTF-8 environment variables are setup.
2701static void _ensure_env_setup() {
2702 // If some name/value pairs exist, then we've already done the setup below.
2703 if (g_environ_utf8.size() != 0) {
2704 return;
2705 }
2706
Spencer Lowe6ae5732015-09-08 17:13:04 -07002707 if (_wenviron == nullptr) {
2708 // If _wenviron is null, then -municode probably wasn't used. That
2709 // linker flag will cause the entry point to setup _wenviron. It will
2710 // also require an implementation of wmain() (which we provide above).
2711 fatal("_wenviron is not set, did you link with -municode?");
2712 }
2713
Spencer Lowcf4ff642015-05-11 01:08:48 -07002714 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2715 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2716 // to use the D() macro here because that tracing only works if the
2717 // ADB_TRACE environment variable is setup, but that env var can't be read
2718 // until this code completes.
2719 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2720 wchar_t* const equal = wcschr(*env, L'=');
2721 if (equal == nullptr) {
2722 // Malformed environment variable with no equal sign. Shouldn't
2723 // really happen, but we should be resilient to this.
2724 continue;
2725 }
2726
Spencer Lowd21dc822015-11-12 15:20:15 -08002727 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2728 // var because the program might never even read this particular variable.
2729 std::string name_utf8;
2730 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2731 continue;
2732 }
2733
Spencer Lowe6ae5732015-09-08 17:13:04 -07002734 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002735 name_utf8 = ToLower(name_utf8);
2736
2737 std::string value_utf8;
2738 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2739 continue;
2740 }
2741
2742 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002743
Spencer Lowe6ae5732015-09-08 17:13:04 -07002744 // Don't overwrite a previus env var with the same name. In reality,
2745 // the system probably won't let two env vars with the same name exist
2746 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002747 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002748 }
2749}
2750
2751// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002752// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002753char* adb_getenv(const char* name) {
2754 _ensure_env_setup();
2755
Spencer Lowe6ae5732015-09-08 17:13:04 -07002756 // Case-insensitive search by searching for lowercase name in a map of
2757 // lowercase names.
2758 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002759 if (it == g_environ_utf8.end()) {
2760 return nullptr;
2761 }
2762
2763 return it->second;
2764}
2765
2766// Version of getcwd() that returns the current working directory in UTF-8.
2767char* adb_getcwd(char* buf, int size) {
2768 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2769 if (wbuf == nullptr) {
2770 return nullptr;
2771 }
2772
Spencer Lowd21dc822015-11-12 15:20:15 -08002773 std::string buf_utf8;
2774 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002775 free(wbuf);
2776 wbuf = nullptr;
2777
Spencer Lowd21dc822015-11-12 15:20:15 -08002778 if (!narrow_result) {
2779 return nullptr;
2780 }
2781
Spencer Lowcf4ff642015-05-11 01:08:48 -07002782 // If size was specified, make sure all the chars will fit.
2783 if (size != 0) {
2784 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2785 errno = ERANGE;
2786 return nullptr;
2787 }
2788 }
2789
2790 // If buf was not specified, allocate storage.
2791 if (buf == nullptr) {
2792 if (size == 0) {
2793 size = buf_utf8.length() + 1;
2794 }
2795 buf = reinterpret_cast<char*>(malloc(size));
2796 if (buf == nullptr) {
2797 return nullptr;
2798 }
2799 }
2800
2801 // Destination buffer was allocated with enough space, or we've already
2802 // checked an existing buffer size for enough space.
2803 strcpy(buf, buf_utf8.c_str());
2804
2805 return buf;
2806}