blob: ee27406903a7d2ef4ae1ee23515513d21c3eac69 [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/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800113/***** common file descriptor handling *****/
114/***** *****/
115/**************************************************************************/
116/**************************************************************************/
117
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800118typedef struct FHRec_
119{
120 FHClass clazz;
121 int used;
122 int eof;
123 union {
124 HANDLE handle;
125 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800126 } u;
127
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800128 int mask;
129
130 char name[32];
131
132} FHRec;
133
134#define fh_handle u.handle
135#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800136
Josh Gaob6232b92016-02-17 16:45:39 -0800137#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700138#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800139
140static adb_mutex_t _win32_lock;
141static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700142static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800143
144static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700145_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800146{
147 FH f;
148
149 fd -= WIN32_FH_BASE;
150
Spencer Lowc3211552015-07-24 15:38:19 -0700151 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700152 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700153 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800154 errno = EBADF;
155 return NULL;
156 }
157
158 f = &_win32_fhs[fd];
159
160 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700161 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700162 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800163 errno = EBADF;
164 return NULL;
165 }
166
167 return f;
168}
169
170
171static int
172_fh_to_int( FH f )
173{
174 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
175 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
176
177 return -1;
178}
179
180static FH
181_fh_alloc( FHClass clazz )
182{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800183 FH f = NULL;
184
185 adb_mutex_lock( &_win32_lock );
186
Josh Gaob6232b92016-02-17 16:45:39 -0800187 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
188 if (_win32_fhs[i].clazz == NULL) {
189 f = &_win32_fhs[i];
190 _win32_fh_next = i + 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800191 goto Exit;
192 }
193 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700194 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowc3211552015-07-24 15:38:19 -0700195 errno = EMFILE; // Too many open files
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800196Exit:
197 if (f) {
Spencer Lowc3211552015-07-24 15:38:19 -0700198 f->clazz = clazz;
199 f->used = 1;
200 f->eof = 0;
201 f->name[0] = '\0';
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800202 clazz->_fh_init(f);
203 }
204 adb_mutex_unlock( &_win32_lock );
205 return f;
206}
207
208
209static int
210_fh_close( FH f )
211{
Spencer Lowc3211552015-07-24 15:38:19 -0700212 // Use lock so that closing only happens once and so that _fh_alloc can't
213 // allocate a FH that we're in the middle of closing.
214 adb_mutex_lock(&_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800215
216 int offset = f - _win32_fhs;
217 if (_win32_fh_next > offset) {
218 _win32_fh_next = offset;
219 }
220
Spencer Lowc3211552015-07-24 15:38:19 -0700221 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800222 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700223 f->name[0] = '\0';
224 f->eof = 0;
225 f->used = 0;
226 f->clazz = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800227 }
Spencer Lowc3211552015-07-24 15:38:19 -0700228 adb_mutex_unlock(&_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800229 return 0;
230}
231
Spencer Low5200c662015-07-30 23:07:55 -0700232// Deleter for unique_fh.
233class fh_deleter {
234 public:
235 void operator()(struct FHRec_* fh) {
236 // We're called from a destructor and destructors should not overwrite
237 // errno because callers may do:
238 // errno = EBLAH;
239 // return -1; // calls destructor, which should not overwrite errno
240 const int saved_errno = errno;
241 _fh_close(fh);
242 errno = saved_errno;
243 }
244};
245
246// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
247typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
248
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800249/**************************************************************************/
250/**************************************************************************/
251/***** *****/
252/***** file-based descriptor handling *****/
253/***** *****/
254/**************************************************************************/
255/**************************************************************************/
256
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700257static void _fh_file_init( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 f->fh_handle = INVALID_HANDLE_VALUE;
259}
260
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700261static int _fh_file_close( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 CloseHandle( f->fh_handle );
263 f->fh_handle = INVALID_HANDLE_VALUE;
264 return 0;
265}
266
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700267static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800268 DWORD read_bytes;
269
270 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700271 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272 errno = EIO;
273 return -1;
274 } else if (read_bytes < (DWORD)len) {
275 f->eof = 1;
276 }
277 return (int)read_bytes;
278}
279
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700280static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281 DWORD wrote_bytes;
282
283 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700284 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800285 errno = EIO;
286 return -1;
287 } else if (wrote_bytes < (DWORD)len) {
288 f->eof = 1;
289 }
290 return (int)wrote_bytes;
291}
292
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700293static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294 DWORD method;
295 DWORD result;
296
297 switch (origin)
298 {
299 case SEEK_SET: method = FILE_BEGIN; break;
300 case SEEK_CUR: method = FILE_CURRENT; break;
301 case SEEK_END: method = FILE_END; break;
302 default:
303 errno = EINVAL;
304 return -1;
305 }
306
307 result = SetFilePointer( f->fh_handle, pos, NULL, method );
308 if (result == INVALID_SET_FILE_POINTER) {
309 errno = EIO;
310 return -1;
311 } else {
312 f->eof = 0;
313 }
314 return (int)result;
315}
316
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800317
318/**************************************************************************/
319/**************************************************************************/
320/***** *****/
321/***** file-based descriptor handling *****/
322/***** *****/
323/**************************************************************************/
324/**************************************************************************/
325
326int adb_open(const char* path, int options)
327{
328 FH f;
329
330 DWORD desiredAccess = 0;
331 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
332
333 switch (options) {
334 case O_RDONLY:
335 desiredAccess = GENERIC_READ;
336 break;
337 case O_WRONLY:
338 desiredAccess = GENERIC_WRITE;
339 break;
340 case O_RDWR:
341 desiredAccess = GENERIC_READ | GENERIC_WRITE;
342 break;
343 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700344 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800345 errno = EINVAL;
346 return -1;
347 }
348
349 f = _fh_alloc( &_fh_file_class );
350 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351 return -1;
352 }
353
Spencer Lowd21dc822015-11-12 15:20:15 -0800354 std::wstring path_wide;
355 if (!android::base::UTF8ToWide(path, &path_wide)) {
356 return -1;
357 }
358 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700359 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800360
361 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700362 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700364 D( "adb_open: could not open '%s': ", path );
365 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800366 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700367 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800368 errno = ENOENT;
369 return -1;
370
371 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700372 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800373 errno = ENOTDIR;
374 return -1;
375
376 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800377 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800378 errno = ENOENT;
379 return -1;
380 }
381 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800382
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800383 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700384 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800385 return _fh_to_int(f);
386}
387
388/* ignore mode on Win32 */
389int adb_creat(const char* path, int mode)
390{
391 FH f;
392
393 f = _fh_alloc( &_fh_file_class );
394 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800395 return -1;
396 }
397
Spencer Lowd21dc822015-11-12 15:20:15 -0800398 std::wstring path_wide;
399 if (!android::base::UTF8ToWide(path, &path_wide)) {
400 return -1;
401 }
402 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700403 FILE_SHARE_READ | FILE_SHARE_WRITE,
404 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
405 NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800406
407 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700408 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700410 D( "adb_creat: could not open '%s': ", path );
411 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800412 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700413 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800414 errno = ENOENT;
415 return -1;
416
417 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700418 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419 errno = ENOTDIR;
420 return -1;
421
422 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800423 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424 errno = ENOENT;
425 return -1;
426 }
427 }
428 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700429 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800430 return _fh_to_int(f);
431}
432
433
434int adb_read(int fd, void* buf, int len)
435{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700436 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800437
438 if (f == NULL) {
439 return -1;
440 }
441
442 return f->clazz->_fh_read( f, buf, len );
443}
444
445
446int adb_write(int fd, const void* buf, int len)
447{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700448 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800449
450 if (f == NULL) {
451 return -1;
452 }
453
454 return f->clazz->_fh_write(f, buf, len);
455}
456
457
458int adb_lseek(int fd, int pos, int where)
459{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700460 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800461
462 if (!f) {
463 return -1;
464 }
465
466 return f->clazz->_fh_lseek(f, pos, where);
467}
468
469
470int adb_close(int fd)
471{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700472 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473
474 if (!f) {
475 return -1;
476 }
477
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700478 D( "adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 _fh_close(f);
480 return 0;
481}
482
Spencer Low0a796002015-10-18 16:45:09 -0700483// Overrides strerror() to handle error codes not supported by the Windows C
484// Runtime (MSVCRT.DLL).
485char* adb_strerror(int err) {
486 // sysdeps.h defines strerror to adb_strerror, but in this function, we
487 // want to call the real C Runtime strerror().
488#pragma push_macro("strerror")
489#undef strerror
490 const int saved_err = errno; // Save because we overwrite it later.
491
492 // Lookup the string for an unknown error.
493 char* errmsg = strerror(-1);
Elliott Hughes6d929972015-10-27 13:40:35 -0700494 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low0a796002015-10-18 16:45:09 -0700495
496 // Lookup the string for this error to see if the C Runtime has it.
497 errmsg = strerror(err);
Elliott Hughes6d929972015-10-27 13:40:35 -0700498 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low0a796002015-10-18 16:45:09 -0700499 // The CRT returned an error message and it is different than the error
500 // message for an unknown error, so it is probably valid, so use it.
501 } else {
502 // Check if we have a string for this error code.
503 const char* custom_msg = nullptr;
504 switch (err) {
505#pragma push_macro("ERR")
506#undef ERR
507#define ERR(errnum, desc) case errnum: custom_msg = desc; break
508 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
509 // Note that these cannot be longer than 94 characters because we
510 // pass this to _strerror() which has that requirement.
511 ERR(ECONNRESET, "Connection reset by peer");
512 ERR(EHOSTUNREACH, "No route to host");
513 ERR(ENETDOWN, "Network is down");
514 ERR(ENETRESET, "Network dropped connection because of reset");
515 ERR(ENOBUFS, "No buffer space available");
516 ERR(ENOPROTOOPT, "Protocol not available");
517 ERR(ENOTCONN, "Transport endpoint is not connected");
518 ERR(ENOTSOCK, "Socket operation on non-socket");
519 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
520#pragma pop_macro("ERR")
521 }
522
523 if (custom_msg != nullptr) {
524 // Use _strerror() to write our string into the writable per-thread
525 // buffer used by strerror()/_strerror(). _strerror() appends the
526 // msg for the current value of errno, so set errno to a consistent
527 // value for every call so that our code-path is always the same.
528 errno = 0;
529 errmsg = _strerror(custom_msg);
530 const size_t custom_msg_len = strlen(custom_msg);
531 // Just in case _strerror() returned a read-only string, check if
532 // the returned string starts with our custom message because that
533 // implies that the string is not read-only.
534 if ((errmsg != nullptr) &&
535 !strncmp(custom_msg, errmsg, custom_msg_len)) {
536 // _strerror() puts other text after our custom message, so
537 // remove that by terminating after our message.
538 errmsg[custom_msg_len] = '\0';
539 } else {
540 // For some reason nullptr was returned or a pointer to a
541 // read-only string was returned, so fallback to whatever
542 // strerror() can muster (probably "Unknown error" or some
543 // generic CRT error string).
544 errmsg = strerror(err);
545 }
546 } else {
547 // We don't have a custom message, so use whatever strerror(err)
548 // returned earlier.
549 }
550 }
551
552 errno = saved_err; // restore
553
554 return errmsg;
555#pragma pop_macro("strerror")
556}
557
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558/**************************************************************************/
559/**************************************************************************/
560/***** *****/
561/***** socket-based file descriptors *****/
562/***** *****/
563/**************************************************************************/
564/**************************************************************************/
565
Spencer Lowf055c192015-01-25 14:40:16 -0800566#undef setsockopt
567
Spencer Low5200c662015-07-30 23:07:55 -0700568static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700569 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
570 // lot of POSIX and socket error codes, some of the resulting error codes
571 // are mapped to strings by adb_strerror() above.
Spencer Low5200c662015-07-30 23:07:55 -0700572 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800573 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700574 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
575 // case WSAEINTR: errno = EINTR; break;
576 case WSAEFAULT: errno = EFAULT; break;
577 case WSAEINVAL: errno = EINVAL; break;
578 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700579 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
580 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
581 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800582 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700583 case WSAENOTSOCK: errno = ENOTSOCK; break;
584 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
585 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
586 case WSAENETDOWN: errno = ENETDOWN; break;
587 case WSAENETRESET: errno = ENETRESET; break;
588 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
589 // to use EPIPE for these situations and there are some callers that look
590 // for EPIPE.
591 case WSAECONNABORTED: errno = EPIPE; break;
592 case WSAECONNRESET: errno = ECONNRESET; break;
593 case WSAENOBUFS: errno = ENOBUFS; break;
594 case WSAENOTCONN: errno = ENOTCONN; break;
595 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
596 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
597 // considerations: Reportedly send() can return zero on timeout, and POSIX
598 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
599 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
600 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800601 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700603 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700604 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800605 }
606}
607
Josh Gao3777d2e2016-02-16 17:34:53 -0800608extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
609 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
610 int skipped = 0;
611 std::vector<WSAPOLLFD> sockets;
612 std::vector<adb_pollfd*> original;
613 for (size_t i = 0; i < nfds; ++i) {
614 FH fh = _fh_from_int(fds[i].fd, __func__);
615 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
616 D("adb_poll received bad FD %d", fds[i].fd);
617 fds[i].revents = POLLNVAL;
618 ++skipped;
619 } else {
620 WSAPOLLFD wsapollfd = {
621 .fd = fh->u.socket,
622 .events = static_cast<short>(fds[i].events)
623 };
624 sockets.push_back(wsapollfd);
625 original.push_back(&fds[i]);
626 }
Spencer Low5200c662015-07-30 23:07:55 -0700627 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800628
629 if (sockets.empty()) {
630 return skipped;
631 }
632
633 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
634 if (result == SOCKET_ERROR) {
635 _socket_set_errno(WSAGetLastError());
636 return -1;
637 }
638
639 // Map the results back onto the original set.
640 for (size_t i = 0; i < sockets.size(); ++i) {
641 original[i]->revents = sockets[i].revents;
642 }
643
644 // WSAPoll appears to return the number of unique FDs with avaiable events, instead of how many
645 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
646 // to do. Ignore its result and calculate the proper return value.
647 result = 0;
648 for (size_t i = 0; i < nfds; ++i) {
649 if (fds[i].revents != 0) {
650 ++result;
651 }
652 }
653 return result;
654}
655
656static void _fh_socket_init(FH f) {
657 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658 f->mask = 0;
659}
660
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700661static int _fh_socket_close( FH f ) {
Spencer Low5200c662015-07-30 23:07:55 -0700662 if (f->fh_socket != INVALID_SOCKET) {
663 /* gently tell any peer that we're closing the socket */
664 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
665 // If the socket is not connected, this returns an error. We want to
666 // minimize logging spam, so don't log these errors for now.
667#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700668 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800669 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700670#endif
671 }
672 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800673 // Don't set errno here, since adb_close will ignore it.
674 const DWORD err = WSAGetLastError();
675 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700676 }
677 f->fh_socket = INVALID_SOCKET;
678 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679 f->mask = 0;
680 return 0;
681}
682
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700683static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800684 errno = EPIPE;
685 return -1;
686}
687
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700688static int _fh_socket_read(FH f, void* buf, int len) {
689 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800690 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700691 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700692 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
693 // that to reduce spam and confusion.
694 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700695 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800696 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700697 }
Spencer Low5200c662015-07-30 23:07:55 -0700698 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800699 result = -1;
700 }
701 return result;
702}
703
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700704static int _fh_socket_write(FH f, const void* buf, int len) {
705 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800706 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700707 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700708 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
709 // that to reduce spam and confusion.
710 if (err != WSAEWOULDBLOCK) {
711 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800712 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700713 }
Spencer Low5200c662015-07-30 23:07:55 -0700714 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700716 } else {
717 // According to https://code.google.com/p/chromium/issues/detail?id=27870
718 // Winsock Layered Service Providers may cause this.
719 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
720 << f->name << ", but " << result
721 << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800722 }
723 return result;
724}
725
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726/**************************************************************************/
727/**************************************************************************/
728/***** *****/
729/***** replacement for libs/cutils/socket_xxxx.c *****/
730/***** *****/
731/**************************************************************************/
732/**************************************************************************/
733
734#include <winsock2.h>
735
736static int _winsock_init;
737
738static void
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739_init_winsock( void )
740{
Spencer Low5200c662015-07-30 23:07:55 -0700741 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Low87e97ee2015-08-12 18:19:16 -0700742 // to WSAStartup() which offers no real benefit.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800743 if (!_winsock_init) {
744 WSADATA wsaData;
745 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
746 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800747 fatal("adb: could not initialize Winsock: %s",
748 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800749 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800750 _winsock_init = 1;
Spencer Low87e97ee2015-08-12 18:19:16 -0700751
752 // Note that we do not call atexit() to register WSACleanup to be called
753 // at normal process termination because:
754 // 1) When exit() is called, there are still threads actively using
755 // Winsock because we don't cleanly shutdown all threads, so it
756 // doesn't make sense to call WSACleanup() and may cause problems
757 // with those threads.
758 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
759 // calls WSACleanup() which tries to unload a DLL, which tries to
760 // grab the LoaderLock. This conflicts with the device_poll_thread
761 // which holds the LoaderLock because AdbWinApi.dll calls
762 // setupapi.dll which tries to load wintrust.dll which tries to load
763 // crypt32.dll which calls atexit() which tries to acquire the C
764 // Runtime lock that the other thread holds.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800765 }
766}
767
Spencer Low677fb432015-09-29 15:05:29 -0700768// Map a socket type to an explicit socket protocol instead of using the socket
769// protocol of 0. Explicit socket protocols are used by most apps and we should
770// do the same to reduce the chance of exercising uncommon code-paths that might
771// have problems or that might load different Winsock service providers that
772// have problems.
773static int GetSocketProtocolFromSocketType(int type) {
774 switch (type) {
775 case SOCK_STREAM:
776 return IPPROTO_TCP;
777 case SOCK_DGRAM:
778 return IPPROTO_UDP;
779 default:
780 LOG(FATAL) << "Unknown socket type: " << type;
781 return 0;
782 }
783}
784
Spencer Low5200c662015-07-30 23:07:55 -0700785int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800787 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800788
Josh Gao6487e742016-02-18 13:43:55 -0800789 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700790 if (!f) {
791 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800792 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700793 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800794
Josh Gao6487e742016-02-18 13:43:55 -0800795 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800796
797 memset(&addr, 0, sizeof(addr));
798 addr.sin_family = AF_INET;
799 addr.sin_port = htons(port);
800 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
801
Spencer Low677fb432015-09-29 15:05:29 -0700802 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800803 if (s == INVALID_SOCKET) {
804 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700805 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800806 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700807 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800808 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700809 return -1;
810 }
811 f->fh_socket = s;
812
Josh Gao6487e742016-02-18 13:43:55 -0800813 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700814 // Save err just in case inet_ntoa() or ntohs() changes the last error.
815 const DWORD err = WSAGetLastError();
816 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800817 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
818 android::base::SystemErrorCodeToString(err).c_str());
819 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
820 error->c_str());
821 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 return -1;
823 }
824
Spencer Low5200c662015-07-30 23:07:55 -0700825 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800826 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
827 port);
828 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700829 f.release();
830 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800831}
832
833#define LISTEN_BACKLOG 4
834
Spencer Low5200c662015-07-30 23:07:55 -0700835// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800836static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800837 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800838 SOCKET s;
839 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800840
Josh Gao6487e742016-02-18 13:43:55 -0800841 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800842 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700843 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844 return -1;
845 }
846
Josh Gao6487e742016-02-18 13:43:55 -0800847 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848
849 memset(&addr, 0, sizeof(addr));
850 addr.sin_family = AF_INET;
851 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700852 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853
Spencer Low5200c662015-07-30 23:07:55 -0700854 // TODO: Consider using dual-stack socket that can simultaneously listen on
855 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700856 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700857 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800858 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700859 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800860 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700861 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800862 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700863 return -1;
864 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865
866 f->fh_socket = s;
867
Spencer Lowbf7c6052015-08-11 16:45:32 -0700868 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
869 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800870 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800871 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
872 const DWORD err = WSAGetLastError();
873 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
874 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700875 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800876 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700877 return -1;
878 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800879
Josh Gao6487e742016-02-18 13:43:55 -0800880 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700881 // Save err just in case inet_ntoa() or ntohs() changes the last error.
882 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800883 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
884 ntohs(addr.sin_port),
885 android::base::SystemErrorCodeToString(err).c_str());
886 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
887 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800888 return -1;
889 }
890 if (type == SOCK_STREAM) {
Spencer Low5200c662015-07-30 23:07:55 -0700891 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800892 const DWORD err = WSAGetLastError();
893 *error = android::base::StringPrintf(
894 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
895 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
896 error->c_str());
897 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800898 return -1;
899 }
900 }
Spencer Low5200c662015-07-30 23:07:55 -0700901 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800902 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
903 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
904 port);
905 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700906 f.release();
907 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800908}
909
Spencer Low5200c662015-07-30 23:07:55 -0700910int network_loopback_server(int port, int type, std::string* error) {
911 return _network_server(port, type, INADDR_LOOPBACK, error);
912}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800913
Spencer Low5200c662015-07-30 23:07:55 -0700914int network_inaddr_any_server(int port, int type, std::string* error) {
915 return _network_server(port, type, INADDR_ANY, error);
916}
917
918int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
919 unique_fh f(_fh_alloc(&_fh_socket_class));
920 if (!f) {
921 *error = strerror(errno);
922 return -1;
923 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800924
Elliott Hughes381cfa92015-07-23 17:12:58 -0700925 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800926
Spencer Low5200c662015-07-30 23:07:55 -0700927 struct addrinfo hints;
928 memset(&hints, 0, sizeof(hints));
929 hints.ai_family = AF_UNSPEC;
930 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700931 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700932
933 char port_str[16];
934 snprintf(port_str, sizeof(port_str), "%d", port);
935
936 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700937
938#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800939// TODO: When the Android SDK tools increases the Windows system
940// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700941#else
Josh Gao6487e742016-02-18 13:43:55 -0800942// Otherwise, keep using getaddrinfo(), or do runtime API detection
943// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700944#endif
Spencer Low5200c662015-07-30 23:07:55 -0700945 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800946 const DWORD err = WSAGetLastError();
947 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
948 host.c_str(), port_str,
949 android::base::SystemErrorCodeToString(err).c_str());
950
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700951 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800952 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800953 return -1;
954 }
Josh Gao6487e742016-02-18 13:43:55 -0800955 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700956 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800957
Spencer Low5200c662015-07-30 23:07:55 -0700958 // TODO: Try all the addresses if there's more than one? This just uses
959 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
960 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800961 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
962 if (s == INVALID_SOCKET) {
963 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700964 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800965 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700966 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800967 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800968 return -1;
969 }
970 f->fh_socket = s;
971
Spencer Low5200c662015-07-30 23:07:55 -0700972 // TODO: Implement timeouts for Windows. Seems like the default in theory
973 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800974 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700975 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800976 const DWORD err = WSAGetLastError();
977 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
978 android::base::SystemErrorCodeToString(err).c_str());
979 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
980 port_str, error->c_str());
981 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800982 return -1;
983 }
984
Spencer Low5200c662015-07-30 23:07:55 -0700985 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800986 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
987 port);
988 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
989 fd);
Spencer Low5200c662015-07-30 23:07:55 -0700990 f.release();
991 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800992}
993
994#undef accept
995int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
996{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700997 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200998
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800999 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001000 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -07001001 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001002 return -1;
1003 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001004
Spencer Low5200c662015-07-30 23:07:55 -07001005 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001006 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001007 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1008 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001009 return -1;
1010 }
1011
1012 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1013 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001014 const DWORD err = WSAGetLastError();
Spencer Low5200c662015-07-30 23:07:55 -07001015 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursell5f787ed2016-01-27 08:52:53 -08001016 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low5200c662015-07-30 23:07:55 -07001017 _socket_set_errno( err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 return -1;
1019 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001020
Spencer Low5200c662015-07-30 23:07:55 -07001021 const int fd = _fh_to_int(fh.get());
1022 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001023 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low5200c662015-07-30 23:07:55 -07001024 fh.release();
1025 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001026}
1027
1028
Spencer Lowf055c192015-01-25 14:40:16 -08001029int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001030{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001031 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001032
Spencer Lowf055c192015-01-25 14:40:16 -08001033 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001034 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001035 errno = EBADF;
1036 return -1;
1037 }
Spencer Low677fb432015-09-29 15:05:29 -07001038
1039 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1040 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1041 // auto-tuning.
1042
Spencer Low5200c662015-07-30 23:07:55 -07001043 int result = setsockopt( fh->fh_socket, level, optname,
1044 reinterpret_cast<const char*>(optval), optlen );
1045 if ( result == SOCKET_ERROR ) {
1046 const DWORD err = WSAGetLastError();
David Pursell5f787ed2016-01-27 08:52:53 -08001047 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1048 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001049 _socket_set_errno( err );
1050 result = -1;
1051 }
1052 return result;
1053}
1054
Josh Gao3777d2e2016-02-16 17:34:53 -08001055int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1056 FH fh = _fh_from_int(fd, __func__);
1057
1058 if (!fh || fh->clazz != &_fh_socket_class) {
1059 D("adb_getsockname: invalid fd %d", fd);
1060 errno = EBADF;
1061 return -1;
1062 }
1063
1064 int result = getsockname(fh->fh_socket, sockaddr, optlen);
1065 if (result == SOCKET_ERROR) {
1066 const DWORD err = WSAGetLastError();
1067 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1068 android::base::SystemErrorCodeToString(err).c_str());
1069 _socket_set_errno(err);
1070 result = -1;
1071 }
1072 return result;
1073}
Spencer Low5200c662015-07-30 23:07:55 -07001074
David Purselleaae97e2016-04-07 11:25:48 -07001075int adb_socket_get_local_port(int fd) {
1076 sockaddr_storage addr_storage;
1077 socklen_t addr_len = sizeof(addr_storage);
1078
1079 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1080 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1081 return -1;
1082 }
1083
1084 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1085 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1086 errno = ECONNABORTED;
1087 return -1;
1088 }
1089
1090 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1091}
1092
Spencer Low5200c662015-07-30 23:07:55 -07001093int adb_shutdown(int fd)
1094{
1095 FH f = _fh_from_int(fd, __func__);
1096
1097 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001098 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001099 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001100 return -1;
1101 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001102
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001103 D( "adb_shutdown: %s", f->name);
Spencer Low5200c662015-07-30 23:07:55 -07001104 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1105 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001106 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001107 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001108 _socket_set_errno(err);
1109 return -1;
1110 }
1111 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001112}
1113
Josh Gao3777d2e2016-02-16 17:34:53 -08001114// Emulate socketpair(2) by binding and connecting to a socket.
1115int adb_socketpair(int sv[2]) {
1116 int server = -1;
1117 int client = -1;
1118 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001119 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001120 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001121
Josh Gao3777d2e2016-02-16 17:34:53 -08001122 server = network_loopback_server(0, SOCK_STREAM, &error);
1123 if (server < 0) {
1124 D("adb_socketpair: failed to create server: %s", error.c_str());
1125 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001126 }
1127
David Purselleaae97e2016-04-07 11:25:48 -07001128 local_port = adb_socket_get_local_port(server);
1129 if (local_port < 0) {
1130 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001131 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001132 }
David Purselleaae97e2016-04-07 11:25:48 -07001133 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001134
David Purselleaae97e2016-04-07 11:25:48 -07001135 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001136 if (client < 0) {
1137 D("adb_socketpair: failed to connect client: %s", error.c_str());
1138 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001139 }
1140
Josh Gao3777d2e2016-02-16 17:34:53 -08001141 accepted = adb_socket_accept(server, nullptr, nullptr);
1142 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001143 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001144 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001145 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001146 adb_close(server);
1147 sv[0] = client;
1148 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001149 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001150
Josh Gao3777d2e2016-02-16 17:34:53 -08001151fail:
1152 if (server >= 0) {
1153 adb_close(server);
1154 }
1155 if (client >= 0) {
1156 adb_close(client);
1157 }
1158 if (accepted >= 0) {
1159 adb_close(accepted);
1160 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001161 return -1;
1162}
1163
Josh Gao3777d2e2016-02-16 17:34:53 -08001164bool set_file_block_mode(int fd, bool block) {
1165 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001166
Josh Gao3777d2e2016-02-16 17:34:53 -08001167 if (!fh || !fh->used) {
1168 errno = EBADF;
1169 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001170 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171
Josh Gao3777d2e2016-02-16 17:34:53 -08001172 if (fh->clazz == &_fh_socket_class) {
1173 u_long x = !block;
1174 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
1175 _socket_set_errno(WSAGetLastError());
1176 return false;
1177 }
1178 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001179 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001180 errno = ENOTSOCK;
1181 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001182 }
1183}
1184
David Pursellbfd95032016-02-22 14:27:23 -08001185bool set_tcp_keepalive(int fd, int interval_sec) {
1186 FH fh = _fh_from_int(fd, __func__);
1187
1188 if (!fh || fh->clazz != &_fh_socket_class) {
1189 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1190 errno = EBADF;
1191 return false;
1192 }
1193
1194 tcp_keepalive keepalive;
1195 keepalive.onoff = (interval_sec > 0);
1196 keepalive.keepalivetime = interval_sec * 1000;
1197 keepalive.keepaliveinterval = interval_sec * 1000;
1198
1199 DWORD bytes_returned = 0;
1200 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1201 &bytes_returned, nullptr, nullptr) != 0) {
1202 const DWORD err = WSAGetLastError();
1203 D("set_tcp_keepalive(%d) failed: %s", fd,
1204 android::base::SystemErrorCodeToString(err).c_str());
1205 _socket_set_errno(err);
1206 return false;
1207 }
1208
1209 return true;
1210}
1211
Spencer Lowa30b79a2015-11-15 16:29:36 -08001212static adb_mutex_t g_console_output_buffer_lock;
1213
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001214void
1215adb_sysdeps_init( void )
1216{
1217#define ADB_MUTEX(x) InitializeCriticalSection( & x );
1218#include "mutex_list.h"
1219 InitializeCriticalSection( &_win32_lock );
Spencer Lowa30b79a2015-11-15 16:29:36 -08001220 InitializeCriticalSection( &g_console_output_buffer_lock );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001221}
1222
Spencer Low50184062015-03-01 15:06:21 -08001223/**************************************************************************/
1224/**************************************************************************/
1225/***** *****/
1226/***** Console Window Terminal Emulation *****/
1227/***** *****/
1228/**************************************************************************/
1229/**************************************************************************/
1230
1231// This reads input from a Win32 console window and translates it into Unix
1232// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1233// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1234// is emulated instead of xterm because it is probably more popular than xterm:
1235// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1236// supports modern fonts, etc. It seems best to emulate the terminal that most
1237// Android developers use because they'll fix apps (the shell, etc.) to keep
1238// working with that terminal's emulation.
1239//
1240// The point of this emulation is not to be perfect or to solve all issues with
1241// console windows on Windows, but to be better than the original code which
1242// just called read() (which called ReadFile(), which called ReadConsoleA())
1243// which did not support Ctrl-C, tab completion, shell input line editing
1244// keys, server echo, and more.
1245//
1246// This implementation reconfigures the console with SetConsoleMode(), then
1247// calls ReadConsoleInput() to get raw input which it remaps to Unix
1248// terminal-style sequences which is returned via unix_read() which is used
1249// by the 'adb shell' command.
1250//
1251// Code organization:
1252//
David Pursellc5b8ad82015-10-28 14:29:51 -07001253// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001254// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1255// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1256// * _console_read() is the main code of the emulation.
1257
David Pursellc5b8ad82015-10-28 14:29:51 -07001258// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1259// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1260// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1261static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1262 // First check isatty(); this is very fast and eliminates most non-console
1263 // FDs, but returns 1 for both consoles and character devices like NUL.
1264#pragma push_macro("isatty")
1265#undef isatty
1266 if (!isatty(fd)) {
1267 return nullptr;
1268 }
1269#pragma pop_macro("isatty")
1270
1271 // To differentiate between character devices and consoles we need to get
1272 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1273 // GENERIC_READ permissions.
1274 const intptr_t intptr_handle = _get_osfhandle(fd);
1275 if (intptr_handle == -1) {
1276 return nullptr;
1277 }
1278 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1279 DWORD temp_mode = 0;
1280 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1281 return nullptr;
1282 }
1283
1284 return handle;
1285}
1286
1287// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1288static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001289 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1290 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001291 const int fd = fileno(stream);
1292 if (fd < 0) {
1293 return nullptr;
1294 }
1295 return _get_console_handle(fd);
1296}
1297
1298int unix_isatty(int fd) {
1299 return _get_console_handle(fd) ? 1 : 0;
1300}
Spencer Low50184062015-03-01 15:06:21 -08001301
Spencer Low32762f42015-11-10 19:17:16 -08001302// Get the next KEY_EVENT_RECORD that should be processed.
1303static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001304 for (;;) {
1305 DWORD read_count = 0;
1306 memset(input_record, 0, sizeof(*input_record));
1307 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001308 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001309 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001310 errno = EIO;
1311 return false;
1312 }
1313
1314 if (read_count == 0) { // should be impossible
1315 fatal("ReadConsoleInputA returned 0");
1316 }
1317
1318 if (read_count != 1) { // should be impossible
1319 fatal("ReadConsoleInputA did not return one input record");
1320 }
1321
Spencer Low2e02dc62015-11-07 17:34:39 -08001322 // If the console window is resized, emulate SIGWINCH by breaking out
1323 // of read() with errno == EINTR. Note that there is no event on
1324 // vertical resize because we don't give the console our own custom
1325 // screen buffer (with CreateConsoleScreenBuffer() +
1326 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1327 // supports scrollback, but doesn't seem to raise an event for vertical
1328 // window resize.
1329 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1330 errno = EINTR;
1331 return false;
1332 }
1333
Spencer Low50184062015-03-01 15:06:21 -08001334 if ((input_record->EventType == KEY_EVENT) &&
1335 (input_record->Event.KeyEvent.bKeyDown)) {
1336 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1337 fatal("ReadConsoleInputA returned a key event with zero repeat"
1338 " count");
1339 }
1340
1341 // Got an interesting INPUT_RECORD, so return
1342 return true;
1343 }
1344 }
1345}
1346
Spencer Low50184062015-03-01 15:06:21 -08001347static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1348 return (control_key_state & SHIFT_PRESSED) != 0;
1349}
1350
1351static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1352 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1353}
1354
1355static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1356 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1357}
1358
1359static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1360 return (control_key_state & NUMLOCK_ON) != 0;
1361}
1362
1363static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1364 return (control_key_state & CAPSLOCK_ON) != 0;
1365}
1366
1367static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1368 return (control_key_state & ENHANCED_KEY) != 0;
1369}
1370
1371// Constants from MSDN for ToAscii().
1372static const BYTE TOASCII_KEY_OFF = 0x00;
1373static const BYTE TOASCII_KEY_DOWN = 0x80;
1374static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1375
1376// Given a key event, ignore a modifier key and return the character that was
1377// entered without the modifier. Writes to *ch and returns the number of bytes
1378// written.
1379static size_t _get_char_ignoring_modifier(char* const ch,
1380 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1381 const WORD modifier) {
1382 // If there is no character from Windows, try ignoring the specified
1383 // modifier and look for a character. Note that if AltGr is being used,
1384 // there will be a character from Windows.
1385 if (key_event->uChar.AsciiChar == '\0') {
1386 // Note that we read the control key state from the passed in argument
1387 // instead of from key_event since the argument has been normalized.
1388 if (((modifier == VK_SHIFT) &&
1389 _is_shift_pressed(control_key_state)) ||
1390 ((modifier == VK_CONTROL) &&
1391 _is_ctrl_pressed(control_key_state)) ||
1392 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1393
1394 BYTE key_state[256] = {0};
1395 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1396 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1397 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1398 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1399 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1400 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1401 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1402 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1403
1404 // cause this modifier to be ignored
1405 key_state[modifier] = TOASCII_KEY_OFF;
1406
1407 WORD translated = 0;
1408 if (ToAscii(key_event->wVirtualKeyCode,
1409 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1410 // Ignoring the modifier, we found a character.
1411 *ch = (CHAR)translated;
1412 return 1;
1413 }
1414 }
1415 }
1416
1417 // Just use whatever Windows told us originally.
1418 *ch = key_event->uChar.AsciiChar;
1419
1420 // If the character from Windows is NULL, return a size of zero.
1421 return (*ch == '\0') ? 0 : 1;
1422}
1423
1424// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1425// but taking into account the shift key. This is because for a sequence like
1426// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1427// we want to find the character ')'.
1428//
1429// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1430// because it is the default key-sequence to switch the input language.
1431// This is configurable in the Region and Language control panel.
1432static __inline__ size_t _get_non_control_char(char* const ch,
1433 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1434 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1435 VK_CONTROL);
1436}
1437
1438// Get without Alt.
1439static __inline__ size_t _get_non_alt_char(char* const ch,
1440 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1441 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1442 VK_MENU);
1443}
1444
1445// Ignore the control key, find the character from Windows, and apply any
1446// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1447// *pch and returns number of bytes written.
1448static size_t _get_control_character(char* const pch,
1449 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1450 const size_t len = _get_non_control_char(pch, key_event,
1451 control_key_state);
1452
1453 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1454 char ch = *pch;
1455 switch (ch) {
1456 case '2':
1457 case '@':
1458 case '`':
1459 ch = '\0';
1460 break;
1461 case '3':
1462 case '[':
1463 case '{':
1464 ch = '\x1b';
1465 break;
1466 case '4':
1467 case '\\':
1468 case '|':
1469 ch = '\x1c';
1470 break;
1471 case '5':
1472 case ']':
1473 case '}':
1474 ch = '\x1d';
1475 break;
1476 case '6':
1477 case '^':
1478 case '~':
1479 ch = '\x1e';
1480 break;
1481 case '7':
1482 case '-':
1483 case '_':
1484 ch = '\x1f';
1485 break;
1486 case '8':
1487 ch = '\x7f';
1488 break;
1489 case '/':
1490 if (!_is_alt_pressed(control_key_state)) {
1491 ch = '\x1f';
1492 }
1493 break;
1494 case '?':
1495 if (!_is_alt_pressed(control_key_state)) {
1496 ch = '\x7f';
1497 }
1498 break;
1499 }
1500 *pch = ch;
1501 }
1502
1503 return len;
1504}
1505
1506static DWORD _normalize_altgr_control_key_state(
1507 const KEY_EVENT_RECORD* const key_event) {
1508 DWORD control_key_state = key_event->dwControlKeyState;
1509
1510 // If we're in an AltGr situation where the AltGr key is down (depending on
1511 // the keyboard layout, that might be the physical right alt key which
1512 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1513 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1514 // a character (which indicates that there was an AltGr mapping), then act
1515 // as if alt and control are not really down for the purposes of modifiers.
1516 // This makes it so that if the user with, say, a German keyboard layout
1517 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1518 // output the key and we don't see the Alt and Ctrl keys.
1519 if (_is_ctrl_pressed(control_key_state) &&
1520 _is_alt_pressed(control_key_state)
1521 && (key_event->uChar.AsciiChar != '\0')) {
1522 // Try to remove as few bits as possible to improve our chances of
1523 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1524 // Left-Alt + Right-Ctrl + AltGr.
1525 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1526 // Remove Right-Alt.
1527 control_key_state &= ~RIGHT_ALT_PRESSED;
1528 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1529 // pressed, Left-Ctrl is almost always set, except if the user
1530 // presses Right-Ctrl, then AltGr (in that specific order) for
1531 // whatever reason. At any rate, make sure the bit is not set.
1532 control_key_state &= ~LEFT_CTRL_PRESSED;
1533 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1534 // Remove Left-Alt.
1535 control_key_state &= ~LEFT_ALT_PRESSED;
1536 // Whichever Ctrl key is down, remove it from the state. We only
1537 // remove one key, to improve our chances of detecting the
1538 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1539 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1540 // Remove Left-Ctrl.
1541 control_key_state &= ~LEFT_CTRL_PRESSED;
1542 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1543 // Remove Right-Ctrl.
1544 control_key_state &= ~RIGHT_CTRL_PRESSED;
1545 }
1546 }
1547
1548 // Note that this logic isn't 100% perfect because Windows doesn't
1549 // allow us to detect all combinations because a physical AltGr key
1550 // press shows up as two bits, plus some combinations are ambiguous
1551 // about what is actually physically pressed.
1552 }
1553
1554 return control_key_state;
1555}
1556
1557// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1558// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1559// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1560// appropriately.
1561static DWORD _normalize_keypad_control_key_state(const WORD vk,
1562 const DWORD control_key_state) {
1563 if (!_is_numlock_on(control_key_state)) {
1564 return control_key_state;
1565 }
1566 if (!_is_enhanced_key(control_key_state)) {
1567 switch (vk) {
1568 case VK_INSERT: // 0
1569 case VK_DELETE: // .
1570 case VK_END: // 1
1571 case VK_DOWN: // 2
1572 case VK_NEXT: // 3
1573 case VK_LEFT: // 4
1574 case VK_CLEAR: // 5
1575 case VK_RIGHT: // 6
1576 case VK_HOME: // 7
1577 case VK_UP: // 8
1578 case VK_PRIOR: // 9
1579 return control_key_state | SHIFT_PRESSED;
1580 }
1581 }
1582
1583 return control_key_state;
1584}
1585
1586static const char* _get_keypad_sequence(const DWORD control_key_state,
1587 const char* const normal, const char* const shifted) {
1588 if (_is_shift_pressed(control_key_state)) {
1589 // Shift is pressed and NumLock is off
1590 return shifted;
1591 } else {
1592 // Shift is not pressed and NumLock is off, or,
1593 // Shift is pressed and NumLock is on, in which case we want the
1594 // NumLock and Shift to neutralize each other, thus, we want the normal
1595 // sequence.
1596 return normal;
1597 }
1598 // If Shift is not pressed and NumLock is on, a different virtual key code
1599 // is returned by Windows, which can be taken care of by a different case
1600 // statement in _console_read().
1601}
1602
1603// Write sequence to buf and return the number of bytes written.
1604static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1605 DWORD control_key_state, const char* const normal) {
1606 // Copy the base sequence into buf.
1607 const size_t len = strlen(normal);
1608 memcpy(buf, normal, len);
1609
1610 int code = 0;
1611
1612 control_key_state = _normalize_keypad_control_key_state(vk,
1613 control_key_state);
1614
1615 if (_is_shift_pressed(control_key_state)) {
1616 code |= 0x1;
1617 }
1618 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1619 code |= 0x2;
1620 }
1621 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1622 code |= 0x4;
1623 }
1624 // If some modifier was held down, then we need to insert the modifier code
1625 if (code != 0) {
1626 if (len == 0) {
1627 // Should be impossible because caller should pass a string of
1628 // non-zero length.
1629 return 0;
1630 }
1631 size_t index = len - 1;
1632 const char lastChar = buf[index];
1633 if (lastChar != '~') {
1634 buf[index++] = '1';
1635 }
1636 buf[index++] = ';'; // modifier separator
1637 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1638 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1639 buf[index++] = '1' + code;
1640 buf[index++] = lastChar; // move ~ (or other last char) to the end
1641 return index;
1642 }
1643 return len;
1644}
1645
1646// Write sequence to buf and return the number of bytes written.
1647static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1648 const DWORD control_key_state, const char* const normal,
1649 const char shifted) {
1650 if (_is_shift_pressed(control_key_state)) {
1651 // Shift is pressed and NumLock is off
1652 if (shifted != '\0') {
1653 buf[0] = shifted;
1654 return sizeof(buf[0]);
1655 } else {
1656 return 0;
1657 }
1658 } else {
1659 // Shift is not pressed and NumLock is off, or,
1660 // Shift is pressed and NumLock is on, in which case we want the
1661 // NumLock and Shift to neutralize each other, thus, we want the normal
1662 // sequence.
1663 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1664 }
1665 // If Shift is not pressed and NumLock is on, a different virtual key code
1666 // is returned by Windows, which can be taken care of by a different case
1667 // statement in _console_read().
1668}
1669
1670// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1671// Standard German. Figure this out at runtime so we know what to output for
1672// Shift-VK_DELETE.
1673static char _get_decimal_char() {
1674 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1675}
1676
1677// Prefix the len bytes in buf with the escape character, and then return the
1678// new buffer length.
1679size_t _escape_prefix(char* const buf, const size_t len) {
1680 // If nothing to prefix, don't do anything. We might be called with
1681 // len == 0, if alt was held down with a dead key which produced nothing.
1682 if (len == 0) {
1683 return 0;
1684 }
1685
1686 memmove(&buf[1], buf, len);
1687 buf[0] = '\x1b';
1688 return len + 1;
1689}
1690
Spencer Low32762f42015-11-10 19:17:16 -08001691// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001692static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001693
1694// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1695// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001696static int _console_read(const HANDLE console, void* buf, size_t len) {
1697 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001698 // Read of zero bytes should not block waiting for something from the console.
1699 if (len == 0) {
1700 return 0;
1701 }
1702
1703 // Flush as much as possible from input buffer.
1704 if (!g_console_input_buffer.empty()) {
1705 const int bytes_read = std::min(len, g_console_input_buffer.size());
1706 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1707 const auto begin = g_console_input_buffer.begin();
1708 g_console_input_buffer.erase(begin, begin + bytes_read);
1709 return bytes_read;
1710 }
1711
1712 // Read from the actual console. This may block until input.
1713 INPUT_RECORD input_record;
1714 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001715 return -1;
1716 }
1717
Spencer Low32762f42015-11-10 19:17:16 -08001718 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001719 const WORD vk = key_event->wVirtualKeyCode;
1720 const CHAR ch = key_event->uChar.AsciiChar;
1721 const DWORD control_key_state = _normalize_altgr_control_key_state(
1722 key_event);
1723
1724 // The following emulation code should write the output sequence to
1725 // either seqstr or to seqbuf and seqbuflen.
1726 const char* seqstr = NULL; // NULL terminated C-string
1727 // Enough space for max sequence string below, plus modifiers and/or
1728 // escape prefix.
1729 char seqbuf[16];
1730 size_t seqbuflen = 0; // Space used in seqbuf.
1731
1732#define MATCH(vk, normal) \
1733 case (vk): \
1734 { \
1735 seqstr = (normal); \
1736 } \
1737 break;
1738
1739 // Modifier keys should affect the output sequence.
1740#define MATCH_MODIFIER(vk, normal) \
1741 case (vk): \
1742 { \
1743 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1744 control_key_state, (normal)); \
1745 } \
1746 break;
1747
1748 // The shift key should affect the output sequence.
1749#define MATCH_KEYPAD(vk, normal, shifted) \
1750 case (vk): \
1751 { \
1752 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1753 (shifted)); \
1754 } \
1755 break;
1756
1757 // The shift key and other modifier keys should affect the output
1758 // sequence.
1759#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1760 case (vk): \
1761 { \
1762 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1763 control_key_state, (normal), (shifted)); \
1764 } \
1765 break;
1766
1767#define ESC "\x1b"
1768#define CSI ESC "["
1769#define SS3 ESC "O"
1770
1771 // Only support normal mode, not application mode.
1772
1773 // Enhanced keys:
1774 // * 6-pack: insert, delete, home, end, page up, page down
1775 // * cursor keys: up, down, right, left
1776 // * keypad: divide, enter
1777 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1778 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1779 if (_is_enhanced_key(control_key_state)) {
1780 switch (vk) {
1781 case VK_RETURN: // Enter key on keypad
1782 if (_is_ctrl_pressed(control_key_state)) {
1783 seqstr = "\n";
1784 } else {
1785 seqstr = "\r";
1786 }
1787 break;
1788
1789 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1790 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1791
1792 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1793 // will be fixed soon to match xterm which sends CSI "F" and
1794 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1795 MATCH(VK_END, CSI "F");
1796 MATCH(VK_HOME, CSI "H");
1797
1798 MATCH_MODIFIER(VK_LEFT, CSI "D");
1799 MATCH_MODIFIER(VK_UP, CSI "A");
1800 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1801 MATCH_MODIFIER(VK_DOWN, CSI "B");
1802
1803 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1804 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1805
1806 MATCH(VK_DIVIDE, "/");
1807 }
1808 } else { // Non-enhanced keys:
1809 switch (vk) {
1810 case VK_BACK: // backspace
1811 if (_is_alt_pressed(control_key_state)) {
1812 seqstr = ESC "\x7f";
1813 } else {
1814 seqstr = "\x7f";
1815 }
1816 break;
1817
1818 case VK_TAB:
1819 if (_is_shift_pressed(control_key_state)) {
1820 seqstr = CSI "Z";
1821 } else {
1822 seqstr = "\t";
1823 }
1824 break;
1825
1826 // Number 5 key in keypad when NumLock is off, or if NumLock is
1827 // on and Shift is down.
1828 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1829
1830 case VK_RETURN: // Enter key on main keyboard
1831 if (_is_alt_pressed(control_key_state)) {
1832 seqstr = ESC "\n";
1833 } else if (_is_ctrl_pressed(control_key_state)) {
1834 seqstr = "\n";
1835 } else {
1836 seqstr = "\r";
1837 }
1838 break;
1839
1840 // VK_ESCAPE: Don't do any special handling. The OS uses many
1841 // of the sequences with Escape and many of the remaining
1842 // sequences don't produce bKeyDown messages, only !bKeyDown
1843 // for whatever reason.
1844
1845 case VK_SPACE:
1846 if (_is_alt_pressed(control_key_state)) {
1847 seqstr = ESC " ";
1848 } else if (_is_ctrl_pressed(control_key_state)) {
1849 seqbuf[0] = '\0'; // NULL char
1850 seqbuflen = 1;
1851 } else {
1852 seqstr = " ";
1853 }
1854 break;
1855
1856 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1857 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1858
1859 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1860 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1861
1862 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1863 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1864 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1865 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1866
1867 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1868 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1869 _get_decimal_char());
1870
1871 case 0x30: // 0
1872 case 0x31: // 1
1873 case 0x39: // 9
1874 case VK_OEM_1: // ;:
1875 case VK_OEM_PLUS: // =+
1876 case VK_OEM_COMMA: // ,<
1877 case VK_OEM_PERIOD: // .>
1878 case VK_OEM_7: // '"
1879 case VK_OEM_102: // depends on keyboard, could be <> or \|
1880 case VK_OEM_2: // /?
1881 case VK_OEM_3: // `~
1882 case VK_OEM_4: // [{
1883 case VK_OEM_5: // \|
1884 case VK_OEM_6: // ]}
1885 {
1886 seqbuflen = _get_control_character(seqbuf, key_event,
1887 control_key_state);
1888
1889 if (_is_alt_pressed(control_key_state)) {
1890 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1891 }
1892 }
1893 break;
1894
1895 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001896 case 0x33: // 3
1897 case 0x34: // 4
1898 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001899 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001900 case 0x37: // 7
1901 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001902 case VK_OEM_MINUS: // -_
1903 {
1904 seqbuflen = _get_control_character(seqbuf, key_event,
1905 control_key_state);
1906
1907 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1908 // prefix with escape.
1909 if (_is_alt_pressed(control_key_state) &&
1910 !(_is_ctrl_pressed(control_key_state) &&
1911 !_is_shift_pressed(control_key_state))) {
1912 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1913 }
1914 }
1915 break;
1916
Spencer Low50184062015-03-01 15:06:21 -08001917 case 0x41: // a
1918 case 0x42: // b
1919 case 0x43: // c
1920 case 0x44: // d
1921 case 0x45: // e
1922 case 0x46: // f
1923 case 0x47: // g
1924 case 0x48: // h
1925 case 0x49: // i
1926 case 0x4a: // j
1927 case 0x4b: // k
1928 case 0x4c: // l
1929 case 0x4d: // m
1930 case 0x4e: // n
1931 case 0x4f: // o
1932 case 0x50: // p
1933 case 0x51: // q
1934 case 0x52: // r
1935 case 0x53: // s
1936 case 0x54: // t
1937 case 0x55: // u
1938 case 0x56: // v
1939 case 0x57: // w
1940 case 0x58: // x
1941 case 0x59: // y
1942 case 0x5a: // z
1943 {
1944 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1945 control_key_state);
1946
1947 // If Alt is pressed, then prefix with escape.
1948 if (_is_alt_pressed(control_key_state)) {
1949 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1950 }
1951 }
1952 break;
1953
1954 // These virtual key codes are generated by the keys on the
1955 // keypad *when NumLock is on* and *Shift is up*.
1956 MATCH(VK_NUMPAD0, "0");
1957 MATCH(VK_NUMPAD1, "1");
1958 MATCH(VK_NUMPAD2, "2");
1959 MATCH(VK_NUMPAD3, "3");
1960 MATCH(VK_NUMPAD4, "4");
1961 MATCH(VK_NUMPAD5, "5");
1962 MATCH(VK_NUMPAD6, "6");
1963 MATCH(VK_NUMPAD7, "7");
1964 MATCH(VK_NUMPAD8, "8");
1965 MATCH(VK_NUMPAD9, "9");
1966
1967 MATCH(VK_MULTIPLY, "*");
1968 MATCH(VK_ADD, "+");
1969 MATCH(VK_SUBTRACT, "-");
1970 // VK_DECIMAL is generated by the . key on the keypad *when
1971 // NumLock is on* and *Shift is up* and the sequence is not
1972 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1973 // Windows Security screen to come up).
1974 case VK_DECIMAL:
1975 // U.S. English uses '.', Germany German uses ','.
1976 seqbuflen = _get_non_control_char(seqbuf, key_event,
1977 control_key_state);
1978 break;
1979
1980 MATCH_MODIFIER(VK_F1, SS3 "P");
1981 MATCH_MODIFIER(VK_F2, SS3 "Q");
1982 MATCH_MODIFIER(VK_F3, SS3 "R");
1983 MATCH_MODIFIER(VK_F4, SS3 "S");
1984 MATCH_MODIFIER(VK_F5, CSI "15~");
1985 MATCH_MODIFIER(VK_F6, CSI "17~");
1986 MATCH_MODIFIER(VK_F7, CSI "18~");
1987 MATCH_MODIFIER(VK_F8, CSI "19~");
1988 MATCH_MODIFIER(VK_F9, CSI "20~");
1989 MATCH_MODIFIER(VK_F10, CSI "21~");
1990 MATCH_MODIFIER(VK_F11, CSI "23~");
1991 MATCH_MODIFIER(VK_F12, CSI "24~");
1992
1993 MATCH_MODIFIER(VK_F13, CSI "25~");
1994 MATCH_MODIFIER(VK_F14, CSI "26~");
1995 MATCH_MODIFIER(VK_F15, CSI "28~");
1996 MATCH_MODIFIER(VK_F16, CSI "29~");
1997 MATCH_MODIFIER(VK_F17, CSI "31~");
1998 MATCH_MODIFIER(VK_F18, CSI "32~");
1999 MATCH_MODIFIER(VK_F19, CSI "33~");
2000 MATCH_MODIFIER(VK_F20, CSI "34~");
2001
2002 // MATCH_MODIFIER(VK_F21, ???);
2003 // MATCH_MODIFIER(VK_F22, ???);
2004 // MATCH_MODIFIER(VK_F23, ???);
2005 // MATCH_MODIFIER(VK_F24, ???);
2006 }
2007 }
2008
2009#undef MATCH
2010#undef MATCH_MODIFIER
2011#undef MATCH_KEYPAD
2012#undef MATCH_MODIFIER_KEYPAD
2013#undef ESC
2014#undef CSI
2015#undef SS3
2016
2017 const char* out;
2018 size_t outlen;
2019
2020 // Check for output in any of:
2021 // * seqstr is set (and strlen can be used to determine the length).
2022 // * seqbuf and seqbuflen are set
2023 // Fallback to ch from Windows.
2024 if (seqstr != NULL) {
2025 out = seqstr;
2026 outlen = strlen(seqstr);
2027 } else if (seqbuflen > 0) {
2028 out = seqbuf;
2029 outlen = seqbuflen;
2030 } else if (ch != '\0') {
2031 // Use whatever Windows told us it is.
2032 seqbuf[0] = ch;
2033 seqbuflen = 1;
2034 out = seqbuf;
2035 outlen = seqbuflen;
2036 } else {
2037 // No special handling for the virtual key code and Windows isn't
2038 // telling us a character code, then we don't know how to translate
2039 // the key press.
2040 //
2041 // Consume the input and 'continue' to cause us to get a new key
2042 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002043 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002044 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002045 continue;
2046 }
2047
Spencer Low32762f42015-11-10 19:17:16 -08002048 // put output wRepeatCount times into g_console_input_buffer
2049 while (key_event->wRepeatCount-- > 0) {
2050 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002051 }
2052
Spencer Low32762f42015-11-10 19:17:16 -08002053 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002054 }
2055}
2056
2057static DWORD _old_console_mode; // previous GetConsoleMode() result
2058static HANDLE _console_handle; // when set, console mode should be restored
2059
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002060void stdin_raw_init() {
2061 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002062 if (in == nullptr) {
2063 return;
2064 }
Spencer Low50184062015-03-01 15:06:21 -08002065
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002066 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2067 // calling the process Ctrl-C routine (configured by
2068 // SetConsoleCtrlHandler()).
2069 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2070 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2071 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002072 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2073 ENABLE_LINE_INPUT |
2074 ENABLE_ECHO_INPUT);
2075 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2076 new_console_mode |= ENABLE_WINDOW_INPUT;
2077
2078 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002079 // This really should not fail.
2080 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002081 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002082 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002083
2084 // Once this is set, it means that stdin has been configured for
2085 // reading from and that the old console mode should be restored later.
2086 _console_handle = in;
2087
2088 // Note that we don't need to configure C Runtime line-ending
2089 // translation because _console_read() does not call the C Runtime to
2090 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002091}
2092
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002093void stdin_raw_restore() {
2094 if (_console_handle != NULL) {
2095 const HANDLE in = _console_handle;
2096 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002097
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002098 if (!SetConsoleMode(in, _old_console_mode)) {
2099 // This really should not fail.
2100 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002101 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002102 }
2103 }
2104}
2105
Spencer Low2e02dc62015-11-07 17:34:39 -08002106// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2107int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08002108 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2109 // If it is a request to read from stdin, and stdin_raw_init() has been
2110 // called, and it successfully configured the console, then read from
2111 // the console using Win32 console APIs and partially emulate a unix
2112 // terminal.
2113 return _console_read(_console_handle, buf, len);
2114 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002115 // On older versions of Windows (definitely 7, definitely not 10),
2116 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002117 // we need to limit the read size.
2118 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002119 len = 4096;
2120 }
Spencer Low50184062015-03-01 15:06:21 -08002121 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002122 // can do LF/CR translation (which is overridable with _setmode()).
2123 // Undefine the macro that is set in sysdeps.h which bans calls to
2124 // plain read() in favor of unix_read() or adb_read().
2125#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002126#undef read
2127 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002128#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002129 }
2130}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002131
2132/**************************************************************************/
2133/**************************************************************************/
2134/***** *****/
2135/***** Unicode support *****/
2136/***** *****/
2137/**************************************************************************/
2138/**************************************************************************/
2139
2140// This implements support for using files with Unicode filenames and for
2141// outputting Unicode text to a Win32 console window. This is inspired from
2142// http://utf8everywhere.org/.
2143//
2144// Background
2145// ----------
2146//
2147// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2148// filenames to APIs such as open(). This works because filenames are largely
2149// opaque 'cookies' (perhaps excluding path separators).
2150//
2151// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2152// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2153// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2154// CreateFile() API is really just a macro that adds the W/A based on whether
2155// the UNICODE preprocessor symbol is defined).
2156//
2157// Options
2158// -------
2159//
2160// Thus, to write a portable program, there are a few options:
2161//
2162// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2163// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2164// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2165// open() API.
2166//
2167// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2168// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2169// potentially touching a lot of code.
2170//
2171// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2172// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2173// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2174// or C Runtime API.
2175//
2176// The Choice
2177// ----------
2178//
Spencer Lowd21dc822015-11-12 15:20:15 -08002179// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2180// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002181// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002182// args that are passed to main() at the beginning of program startup. We also use
2183// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002184// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2185//
2186// Unicode console output
2187// ----------------------
2188//
2189// The way to output Unicode to a Win32 console window is to call
2190// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002191// such as Lucida Console or Consolas, and in the case of East Asian languages
2192// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2193// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2194// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002195//
2196// The problem is getting the C Runtime to make fprintf and related APIs call
2197// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2198// promising, but the various modes have issues:
2199//
2200// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2201// UTF-16 do not display properly.
2202// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2203// totally wrong.
2204// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2205// handler to be called (upon a later I/O call), aborting the process.
2206// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2207// to output nothing.
2208//
2209// So the only solution is to write our own adb_fprintf() that converts UTF-8
2210// to UTF-16 and then calls WriteConsoleW().
2211
2212
Spencer Lowcf4ff642015-05-11 01:08:48 -07002213// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2214// be passed to main().
2215NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2216 narrow_args = new char*[argc + 1];
2217
2218 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002219 std::string arg_narrow;
2220 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2221 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2222 }
2223 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002224 }
2225 narrow_args[argc] = nullptr; // terminate
2226}
2227
2228NarrowArgs::~NarrowArgs() {
2229 if (narrow_args != nullptr) {
2230 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2231 free(*argp);
2232 }
2233 delete[] narrow_args;
2234 narrow_args = nullptr;
2235 }
2236}
2237
2238int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002239 std::wstring path_wide;
2240 if (!android::base::UTF8ToWide(path, &path_wide)) {
2241 return -1;
2242 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002243 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002244 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002245 } else {
2246 int mode;
2247 va_list args;
2248 va_start(args, options);
2249 mode = va_arg(args, int);
2250 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002251 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002252 }
2253}
2254
Spencer Lowcf4ff642015-05-11 01:08:48 -07002255// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002256DIR* adb_opendir(const char* path) {
2257 std::wstring path_wide;
2258 if (!android::base::UTF8ToWide(path, &path_wide)) {
2259 return nullptr;
2260 }
2261
Spencer Lowcf4ff642015-05-11 01:08:48 -07002262 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2263 // the fields, but right now all the callers treat the structure as
2264 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002265 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002266}
2267
2268// Version of readdir() that returns UTF-8 paths.
2269struct dirent* adb_readdir(DIR* dir) {
2270 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2271 struct _wdirent* const went = _wreaddir(wdir);
2272 if (went == nullptr) {
2273 return nullptr;
2274 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002275
Spencer Lowcf4ff642015-05-11 01:08:48 -07002276 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002277 std::string name_utf8;
2278 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2279 return nullptr;
2280 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002281
2282 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2283 // space for UTF-16 wchar_t's) with UTF-8 char's.
2284 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2285
2286 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2287 // Name too big to fit in existing buffer.
2288 errno = ENOMEM;
2289 return nullptr;
2290 }
2291
2292 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2293 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2294 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2295 // bigger than the caller expects because they expect a dirent structure
2296 // which has a smaller d_name field. Ignore this since the caller should be
2297 // resilient.
2298
2299 // Rewrite the UTF-16 d_name field to UTF-8.
2300 strcpy(ent->d_name, name_utf8.c_str());
2301
2302 return ent;
2303}
2304
2305// Version of closedir() to go with our version of adb_opendir().
2306int adb_closedir(DIR* dir) {
2307 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2308}
2309
2310// Version of unlink() that takes a UTF-8 path.
2311int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002312 std::wstring wpath;
2313 if (!android::base::UTF8ToWide(path, &wpath)) {
2314 return -1;
2315 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002316
2317 int rc = _wunlink(wpath.c_str());
2318
2319 if (rc == -1 && errno == EACCES) {
2320 /* unlink returns EACCES when the file is read-only, so we first */
2321 /* try to make it writable, then unlink again... */
2322 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2323 if (rc == 0)
2324 rc = _wunlink(wpath.c_str());
2325 }
2326 return rc;
2327}
2328
2329// Version of mkdir() that takes a UTF-8 path.
2330int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002331 std::wstring path_wide;
2332 if (!android::base::UTF8ToWide(path, &path_wide)) {
2333 return -1;
2334 }
2335
2336 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002337}
2338
2339// Version of utime() that takes a UTF-8 path.
2340int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002341 std::wstring path_wide;
2342 if (!android::base::UTF8ToWide(path, &path_wide)) {
2343 return -1;
2344 }
2345
Spencer Lowcf4ff642015-05-11 01:08:48 -07002346 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2347 "utimbuf and _utimbuf should be the same size because they both "
2348 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002349 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002350}
2351
2352// Version of chmod() that takes a UTF-8 path.
2353int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002354 std::wstring path_wide;
2355 if (!android::base::UTF8ToWide(path, &path_wide)) {
2356 return -1;
2357 }
2358
2359 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002360}
2361
Spencer Lowa30b79a2015-11-15 16:29:36 -08002362// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2363static inline size_t utf8_codepoint_len(uint8_t ch) {
2364 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2365}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002366
Spencer Lowa30b79a2015-11-15 16:29:36 -08002367namespace internal {
2368
2369// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2370// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2371// remaining_bytes.
2372size_t ParseCompleteUTF8(const char* const first, const char* const last,
2373 std::vector<char>* const remaining_bytes) {
2374 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2375 // Current_after points one byte past the current byte to be examined.
2376 for (const char* current_after = last; current_after != first; --current_after) {
2377 const char* const current = current_after - 1;
2378 const char ch = *current;
2379 const char kHighBit = 0x80u;
2380 const char kTwoHighestBits = 0xC0u;
2381 if ((ch & kHighBit) == 0) { // high bit not set
2382 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2383 // bytes with no leading byte, so return the entire buffer.
2384 break;
2385 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2386 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2387 const size_t bytes_available = last - current;
2388 if (bytes_available < utf8_codepoint_len(ch)) {
2389 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2390 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2391 // to remaining_bytes.
2392 remaining_bytes->insert(remaining_bytes->end(), current, last);
2393 return current - first;
2394 } else {
2395 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2396 // trailing bytes with no lead byte, so return the entire buffer.
2397 break;
2398 }
2399 } else {
2400 // Trailing byte, so keep going backwards looking for the lead byte.
2401 }
2402 }
2403
2404 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2405 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2406 // so that they can be processed.
2407 return last - first;
2408}
2409
2410}
2411
2412// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2413// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2414// This matches the behavior of Linux.
2415// Protected by g_console_output_buffer_lock.
2416static auto& g_console_output_buffer = *new std::vector<char>();
2417
2418// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2419static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2420 HANDLE console) {
2421 const int saved_errno = errno;
2422 std::vector<char> combined_buffer;
2423
2424 // Complete UTF-8 sequences that should be immediately written to the console.
2425 const char* utf8;
2426 size_t utf8_size;
2427
2428 adb_mutex_lock(&g_console_output_buffer_lock);
2429 if (g_console_output_buffer.empty()) {
2430 // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2431 // common case with plain ASCII), parse buf directly.
2432 utf8 = buf;
2433 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
2434 } else {
2435 // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2436 // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
2437 // combined_buffer, then parse it all together.
2438 combined_buffer.swap(g_console_output_buffer);
2439 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
2440
2441 utf8 = combined_buffer.data();
2442 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2443 &g_console_output_buffer);
2444 }
2445 adb_mutex_unlock(&g_console_output_buffer_lock);
2446
2447 std::wstring utf16;
2448
2449 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2450 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2451 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002452 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002453 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002454
2455 // Note that this does not do \n => \r\n translation because that
2456 // doesn't seem necessary for the Windows console. For the Windows
2457 // console \r moves to the beginning of the line and \n moves to a new
2458 // line.
2459
2460 // Flush any stream buffering so that our output is afterwards which
2461 // makes sense because our call is afterwards.
2462 (void)fflush(stream);
2463
2464 // Write UTF-16 to the console.
2465 DWORD written = 0;
Spencer Lowa30b79a2015-11-15 16:29:36 -08002466 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002467 errno = EIO;
2468 return -1;
2469 }
2470
Spencer Lowa30b79a2015-11-15 16:29:36 -08002471 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2472 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2473 // matches the Linux behavior.
2474 errno = saved_errno;
2475 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002476}
2477
2478// Function prototype because attributes cannot be placed on func definitions.
2479static int _console_vfprintf(const HANDLE console, FILE* stream,
2480 const char *format, va_list ap)
2481 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2482
2483// Internal function to format a UTF-8 string and write it to a Win32 console.
2484// Returns -1 on error.
2485static int _console_vfprintf(const HANDLE console, FILE* stream,
2486 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002487 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002488 std::string output_utf8;
2489
2490 // Format the string.
2491 // This could throw std::bad_alloc.
2492 android::base::StringAppendV(&output_utf8, format, ap);
2493
Spencer Lowa30b79a2015-11-15 16:29:36 -08002494 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2495 console);
2496 if (result != -1) {
2497 errno = saved_errno;
2498 } else {
2499 // If -1 was returned, errno has been set.
2500 }
2501 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002502}
2503
2504// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2505// Windows console.
2506int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2507 const HANDLE console = _get_console_handle(stream);
2508
2509 // If there is an associated Win32 console, write to it specially,
2510 // otherwise defer to the regular C Runtime, passing it UTF-8.
2511 if (console != NULL) {
2512 return _console_vfprintf(console, stream, format, ap);
2513 } else {
2514 // If vfprintf is a macro, undefine it, so we can call the real
2515 // C Runtime API.
2516#pragma push_macro("vfprintf")
2517#undef vfprintf
2518 return vfprintf(stream, format, ap);
2519#pragma pop_macro("vfprintf")
2520 }
2521}
2522
Spencer Lowa30b79a2015-11-15 16:29:36 -08002523// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2524int adb_vprintf(const char *format, va_list ap) {
2525 return adb_vfprintf(stdout, format, ap);
2526}
2527
Spencer Lowcf4ff642015-05-11 01:08:48 -07002528// Version of fprintf() that takes UTF-8 and can write Unicode to a
2529// Windows console.
2530int adb_fprintf(FILE *stream, const char *format, ...) {
2531 va_list ap;
2532 va_start(ap, format);
2533 const int result = adb_vfprintf(stream, format, ap);
2534 va_end(ap);
2535
2536 return result;
2537}
2538
2539// Version of printf() that takes UTF-8 and can write Unicode to a
2540// Windows console.
2541int adb_printf(const char *format, ...) {
2542 va_list ap;
2543 va_start(ap, format);
2544 const int result = adb_vfprintf(stdout, format, ap);
2545 va_end(ap);
2546
2547 return result;
2548}
2549
2550// Version of fputs() that takes UTF-8 and can write Unicode to a
2551// Windows console.
2552int adb_fputs(const char* buf, FILE* stream) {
2553 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2554 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002555 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002556 return adb_fprintf(stream, "%s", buf);
2557}
2558
2559// Version of fputc() that takes UTF-8 and can write Unicode to a
2560// Windows console.
2561int adb_fputc(int ch, FILE* stream) {
2562 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002563 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002564 return EOF;
2565 }
2566 // For success, fputc returns the char, cast to unsigned char, then to int.
2567 return static_cast<unsigned char>(ch);
2568}
2569
Spencer Lowa30b79a2015-11-15 16:29:36 -08002570// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2571int adb_putchar(int ch) {
2572 return adb_fputc(ch, stdout);
2573}
2574
2575// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2576int adb_puts(const char* buf) {
2577 // adb_printf returns -1 on error, which is conveniently the same as EOF
2578 // which puts (and hence adb_puts) should return on error.
2579 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2580 return adb_printf("%s\n", buf);
2581}
2582
Spencer Lowcf4ff642015-05-11 01:08:48 -07002583// Internal function to write UTF-8 to a Win32 console. Returns the number of
2584// items (of length size) written. On error, returns a short item count or 0.
2585static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2586 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002587 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2588 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002589 if (result == -1) {
2590 return 0;
2591 }
2592 return result / size;
2593}
2594
2595// Version of fwrite() that takes UTF-8 and can write Unicode to a
2596// Windows console.
2597size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2598 const HANDLE console = _get_console_handle(stream);
2599
2600 // If there is an associated Win32 console, write to it specially,
2601 // otherwise defer to the regular C Runtime, passing it UTF-8.
2602 if (console != NULL) {
2603 return _console_fwrite(ptr, size, nmemb, stream, console);
2604 } else {
2605 // If fwrite is a macro, undefine it, so we can call the real
2606 // C Runtime API.
2607#pragma push_macro("fwrite")
2608#undef fwrite
2609 return fwrite(ptr, size, nmemb, stream);
2610#pragma pop_macro("fwrite")
2611 }
2612}
2613
2614// Version of fopen() that takes a UTF-8 filename and can access a file with
2615// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002616FILE* adb_fopen(const char* path, const char* mode) {
2617 std::wstring path_wide;
2618 if (!android::base::UTF8ToWide(path, &path_wide)) {
2619 return nullptr;
2620 }
2621
2622 std::wstring mode_wide;
2623 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2624 return nullptr;
2625 }
2626
2627 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002628}
2629
Spencer Lowe6ae5732015-09-08 17:13:04 -07002630// Return a lowercase version of the argument. Uses C Runtime tolower() on
2631// each byte which is not UTF-8 aware, and theoretically uses the current C
2632// Runtime locale (which in practice is not changed, so this becomes a ASCII
2633// conversion).
2634static std::string ToLower(const std::string& anycase) {
2635 // copy string
2636 std::string str(anycase);
2637 // transform the copy
2638 std::transform(str.begin(), str.end(), str.begin(), tolower);
2639 return str;
2640}
2641
2642extern "C" int main(int argc, char** argv);
2643
2644// Link with -municode to cause this wmain() to be used as the program
2645// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2646// regular main() with UTF-8 args.
2647extern "C" int wmain(int argc, wchar_t **argv) {
2648 // Convert args from UTF-16 to UTF-8 and pass that to main().
2649 NarrowArgs narrow_args(argc, argv);
2650 return main(argc, narrow_args.data());
2651}
2652
Spencer Lowcf4ff642015-05-11 01:08:48 -07002653// Shadow UTF-8 environment variable name/value pairs that are created from
2654// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002655// currently updated if putenv, setenv, unsetenv are called. Note that no
2656// thread synchronization is done, but we're called early enough in
2657// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002658static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002659
2660// Make sure that shadow UTF-8 environment variables are setup.
2661static void _ensure_env_setup() {
2662 // If some name/value pairs exist, then we've already done the setup below.
2663 if (g_environ_utf8.size() != 0) {
2664 return;
2665 }
2666
Spencer Lowe6ae5732015-09-08 17:13:04 -07002667 if (_wenviron == nullptr) {
2668 // If _wenviron is null, then -municode probably wasn't used. That
2669 // linker flag will cause the entry point to setup _wenviron. It will
2670 // also require an implementation of wmain() (which we provide above).
2671 fatal("_wenviron is not set, did you link with -municode?");
2672 }
2673
Spencer Lowcf4ff642015-05-11 01:08:48 -07002674 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2675 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2676 // to use the D() macro here because that tracing only works if the
2677 // ADB_TRACE environment variable is setup, but that env var can't be read
2678 // until this code completes.
2679 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2680 wchar_t* const equal = wcschr(*env, L'=');
2681 if (equal == nullptr) {
2682 // Malformed environment variable with no equal sign. Shouldn't
2683 // really happen, but we should be resilient to this.
2684 continue;
2685 }
2686
Spencer Lowd21dc822015-11-12 15:20:15 -08002687 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2688 // var because the program might never even read this particular variable.
2689 std::string name_utf8;
2690 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2691 continue;
2692 }
2693
Spencer Lowe6ae5732015-09-08 17:13:04 -07002694 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002695 name_utf8 = ToLower(name_utf8);
2696
2697 std::string value_utf8;
2698 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2699 continue;
2700 }
2701
2702 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002703
Spencer Lowe6ae5732015-09-08 17:13:04 -07002704 // Don't overwrite a previus env var with the same name. In reality,
2705 // the system probably won't let two env vars with the same name exist
2706 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002707 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002708 }
2709}
2710
2711// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002712// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002713char* adb_getenv(const char* name) {
2714 _ensure_env_setup();
2715
Spencer Lowe6ae5732015-09-08 17:13:04 -07002716 // Case-insensitive search by searching for lowercase name in a map of
2717 // lowercase names.
2718 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002719 if (it == g_environ_utf8.end()) {
2720 return nullptr;
2721 }
2722
2723 return it->second;
2724}
2725
2726// Version of getcwd() that returns the current working directory in UTF-8.
2727char* adb_getcwd(char* buf, int size) {
2728 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2729 if (wbuf == nullptr) {
2730 return nullptr;
2731 }
2732
Spencer Lowd21dc822015-11-12 15:20:15 -08002733 std::string buf_utf8;
2734 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002735 free(wbuf);
2736 wbuf = nullptr;
2737
Spencer Lowd21dc822015-11-12 15:20:15 -08002738 if (!narrow_result) {
2739 return nullptr;
2740 }
2741
Spencer Lowcf4ff642015-05-11 01:08:48 -07002742 // If size was specified, make sure all the chars will fit.
2743 if (size != 0) {
2744 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2745 errno = ERANGE;
2746 return nullptr;
2747 }
2748 }
2749
2750 // If buf was not specified, allocate storage.
2751 if (buf == nullptr) {
2752 if (size == 0) {
2753 size = buf_utf8.length() + 1;
2754 }
2755 buf = reinterpret_cast<char*>(malloc(size));
2756 if (buf == nullptr) {
2757 return nullptr;
2758 }
2759 }
2760
2761 // Destination buffer was allocated with enough space, or we've already
2762 // checked an existing buffer size for enough space.
2763 strcpy(buf, buf_utf8.c_str());
2764
2765 return buf;
2766}