blob: 4dd549dbd8729fc660b01564a2f73c006254bede [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albertdb6fe642015-03-19 15:21:08 -070018
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
Spencer Low50740f52015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low753d4852015-07-30 23:07:55 -070029#include <memory>
Josh Gaoe7daf572016-09-21 12:37:10 -070030#include <mutex>
Spencer Low753d4852015-07-30 23:07:55 -070031#include <string>
Spencer Low6815c072015-05-11 01:08:48 -070032#include <unordered_map>
Josh Gaoe7388122016-02-16 17:34:53 -080033#include <vector>
Spencer Low753d4852015-07-30 23:07:55 -070034
Elliott Hughesfe447512015-07-24 11:35:40 -070035#include <cutils/sockets.h>
36
David Pursellc573d522016-01-27 08:52:53 -080037#include <android-base/errors.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080038#include <android-base/logging.h>
39#include <android-base/stringprintf.h>
40#include <android-base/strings.h>
41#include <android-base/utf8.h>
Spencer Low753d4852015-07-30 23:07:55 -070042
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080043#include "adb.h"
Josh Gaoe7388122016-02-16 17:34:53 -080044#include "adb_utils.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080045
46extern void fatal(const char *fmt, ...);
47
Elliott Hughes6a096932015-04-16 16:47:02 -070048/* forward declarations */
49
50typedef const struct FHClassRec_* FHClass;
51typedef struct FHRec_* FH;
52typedef struct EventHookRec_* EventHook;
53
54typedef struct FHClassRec_ {
55 void (*_fh_init)(FH);
56 int (*_fh_close)(FH);
57 int (*_fh_lseek)(FH, int, int);
58 int (*_fh_read)(FH, void*, int);
59 int (*_fh_write)(FH, const void*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070060} FHClassRec;
61
62static void _fh_file_init(FH);
63static int _fh_file_close(FH);
64static int _fh_file_lseek(FH, int, int);
65static int _fh_file_read(FH, void*, int);
66static int _fh_file_write(FH, const void*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070067
68static const FHClassRec _fh_file_class = {
69 _fh_file_init,
70 _fh_file_close,
71 _fh_file_lseek,
72 _fh_file_read,
73 _fh_file_write,
Elliott Hughes6a096932015-04-16 16:47:02 -070074};
75
76static void _fh_socket_init(FH);
77static int _fh_socket_close(FH);
78static int _fh_socket_lseek(FH, int, int);
79static int _fh_socket_read(FH, void*, int);
80static int _fh_socket_write(FH, const void*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070081
82static const FHClassRec _fh_socket_class = {
83 _fh_socket_init,
84 _fh_socket_close,
85 _fh_socket_lseek,
86 _fh_socket_read,
87 _fh_socket_write,
Elliott Hughes6a096932015-04-16 16:47:02 -070088};
89
Josh Gao2930cdc2016-01-15 15:17:37 -080090#define assert(cond) \
91 do { \
92 if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \
93 } while (0)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080094
Spencer Low2bbb3a92015-08-26 18:46:09 -070095void handle_deleter::operator()(HANDLE h) {
96 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
97 // implying that NULL is a valid handle, but this is probably impossible.
98 // Other APIs like CreateEvent() are documented to return NULL on error,
99 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
100 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
101 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
102 // only need to check for INVALID_HANDLE_VALUE.
103 if (h != INVALID_HANDLE_VALUE) {
104 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700105 D("CloseHandle(%p) failed: %s", h,
David Pursellc573d522016-01-27 08:52:53 -0800106 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2bbb3a92015-08-26 18:46:09 -0700107 }
108 }
109}
110
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800111/**************************************************************************/
112/**************************************************************************/
113/***** *****/
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800114/***** common file descriptor handling *****/
115/***** *****/
116/**************************************************************************/
117/**************************************************************************/
118
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800119typedef struct FHRec_
120{
121 FHClass clazz;
122 int used;
123 int eof;
124 union {
125 HANDLE handle;
126 SOCKET socket;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800127 } u;
128
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800129 int mask;
130
131 char name[32];
132
133} FHRec;
134
135#define fh_handle u.handle
136#define fh_socket u.socket
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800137
Josh Gao4f657a72016-02-17 16:45:39 -0800138#define WIN32_FH_BASE 2048
Josh Gao7c9e5fb2016-04-18 11:09:28 -0700139#define WIN32_MAX_FHS 2048
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800140
Josh Gaoe7daf572016-09-21 12:37:10 -0700141static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800142static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700143static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800144
145static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700146_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800147{
148 FH f;
149
150 fd -= WIN32_FH_BASE;
151
Spencer Lowb732a372015-07-24 15:38:19 -0700152 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui815ad882015-09-02 17:44:28 -0700153 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700154 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800155 errno = EBADF;
156 return NULL;
157 }
158
159 f = &_win32_fhs[fd];
160
161 if (f->used == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700162 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700163 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800164 errno = EBADF;
165 return NULL;
166 }
167
168 return f;
169}
170
171
172static int
173_fh_to_int( FH f )
174{
175 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
176 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
177
178 return -1;
179}
180
181static FH
182_fh_alloc( FHClass clazz )
183{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800184 FH f = NULL;
185
Josh Gaoe7daf572016-09-21 12:37:10 -0700186 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800187
Josh Gao4f657a72016-02-17 16:45:39 -0800188 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
189 if (_win32_fhs[i].clazz == NULL) {
190 f = &_win32_fhs[i];
191 _win32_fh_next = i + 1;
Josh Gaoe7daf572016-09-21 12:37:10 -0700192 f->clazz = clazz;
193 f->used = 1;
194 f->eof = 0;
195 f->name[0] = '\0';
196 clazz->_fh_init(f);
197 return f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800198 }
199 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700200
201 D("_fh_alloc: no more free file descriptors");
202 errno = EMFILE; // Too many open files
203 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800204}
205
206
207static int
208_fh_close( FH f )
209{
Spencer Lowb732a372015-07-24 15:38:19 -0700210 // Use lock so that closing only happens once and so that _fh_alloc can't
211 // allocate a FH that we're in the middle of closing.
Josh Gaoe7daf572016-09-21 12:37:10 -0700212 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gao4f657a72016-02-17 16:45:39 -0800213
214 int offset = f - _win32_fhs;
215 if (_win32_fh_next > offset) {
216 _win32_fh_next = offset;
217 }
218
Spencer Lowb732a372015-07-24 15:38:19 -0700219 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800220 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700221 f->name[0] = '\0';
222 f->eof = 0;
223 f->used = 0;
224 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800225 }
226 return 0;
227}
228
Spencer Low753d4852015-07-30 23:07:55 -0700229// Deleter for unique_fh.
230class fh_deleter {
231 public:
232 void operator()(struct FHRec_* fh) {
233 // We're called from a destructor and destructors should not overwrite
234 // errno because callers may do:
235 // errno = EBLAH;
236 // return -1; // calls destructor, which should not overwrite errno
237 const int saved_errno = errno;
238 _fh_close(fh);
239 errno = saved_errno;
240 }
241};
242
243// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
244typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
245
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800246/**************************************************************************/
247/**************************************************************************/
248/***** *****/
249/***** file-based descriptor handling *****/
250/***** *****/
251/**************************************************************************/
252/**************************************************************************/
253
Elliott Hughes6a096932015-04-16 16:47:02 -0700254static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800255 f->fh_handle = INVALID_HANDLE_VALUE;
256}
257
Elliott Hughes6a096932015-04-16 16:47:02 -0700258static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800259 CloseHandle( f->fh_handle );
260 f->fh_handle = INVALID_HANDLE_VALUE;
261 return 0;
262}
263
Elliott Hughes6a096932015-04-16 16:47:02 -0700264static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800265 DWORD read_bytes;
266
267 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700268 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800269 errno = EIO;
270 return -1;
271 } else if (read_bytes < (DWORD)len) {
272 f->eof = 1;
273 }
274 return (int)read_bytes;
275}
276
Elliott Hughes6a096932015-04-16 16:47:02 -0700277static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800278 DWORD wrote_bytes;
279
280 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700281 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800282 errno = EIO;
283 return -1;
284 } else if (wrote_bytes < (DWORD)len) {
285 f->eof = 1;
286 }
287 return (int)wrote_bytes;
288}
289
Elliott Hughes6a096932015-04-16 16:47:02 -0700290static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800291 DWORD method;
292 DWORD result;
293
294 switch (origin)
295 {
296 case SEEK_SET: method = FILE_BEGIN; break;
297 case SEEK_CUR: method = FILE_CURRENT; break;
298 case SEEK_END: method = FILE_END; break;
299 default:
300 errno = EINVAL;
301 return -1;
302 }
303
304 result = SetFilePointer( f->fh_handle, pos, NULL, method );
305 if (result == INVALID_SET_FILE_POINTER) {
306 errno = EIO;
307 return -1;
308 } else {
309 f->eof = 0;
310 }
311 return (int)result;
312}
313
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800314
315/**************************************************************************/
316/**************************************************************************/
317/***** *****/
318/***** file-based descriptor handling *****/
319/***** *****/
320/**************************************************************************/
321/**************************************************************************/
322
323int adb_open(const char* path, int options)
324{
325 FH f;
326
327 DWORD desiredAccess = 0;
328 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
329
330 switch (options) {
331 case O_RDONLY:
332 desiredAccess = GENERIC_READ;
333 break;
334 case O_WRONLY:
335 desiredAccess = GENERIC_WRITE;
336 break;
337 case O_RDWR:
338 desiredAccess = GENERIC_READ | GENERIC_WRITE;
339 break;
340 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700341 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800342 errno = EINVAL;
343 return -1;
344 }
345
346 f = _fh_alloc( &_fh_file_class );
347 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800348 return -1;
349 }
350
Spencer Low50f5bf12015-11-12 15:20:15 -0800351 std::wstring path_wide;
352 if (!android::base::UTF8ToWide(path, &path_wide)) {
353 return -1;
354 }
355 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Low6815c072015-05-11 01:08:48 -0700356 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800357
358 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700359 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800360 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700361 D( "adb_open: could not open '%s': ", path );
362 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800363 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700364 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800365 errno = ENOENT;
366 return -1;
367
368 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700369 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800370 errno = ENOTDIR;
371 return -1;
372
373 default:
David Pursellc573d522016-01-27 08:52:53 -0800374 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800375 errno = ENOENT;
376 return -1;
377 }
378 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800379
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800380 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700381 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800382 return _fh_to_int(f);
383}
384
385/* ignore mode on Win32 */
386int adb_creat(const char* path, int mode)
387{
388 FH f;
389
390 f = _fh_alloc( &_fh_file_class );
391 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800392 return -1;
393 }
394
Spencer Low50f5bf12015-11-12 15:20:15 -0800395 std::wstring path_wide;
396 if (!android::base::UTF8ToWide(path, &path_wide)) {
397 return -1;
398 }
399 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Low6815c072015-05-11 01:08:48 -0700400 FILE_SHARE_READ | FILE_SHARE_WRITE,
401 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
402 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800403
404 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700405 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800406 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700407 D( "adb_creat: could not open '%s': ", path );
408 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800409 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700410 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800411 errno = ENOENT;
412 return -1;
413
414 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700415 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800416 errno = ENOTDIR;
417 return -1;
418
419 default:
David Pursellc573d522016-01-27 08:52:53 -0800420 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800421 errno = ENOENT;
422 return -1;
423 }
424 }
425 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700426 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800427 return _fh_to_int(f);
428}
429
430
431int adb_read(int fd, void* buf, int len)
432{
Spencer Low3a2421b2015-05-22 20:09:06 -0700433 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800434
435 if (f == NULL) {
436 return -1;
437 }
438
439 return f->clazz->_fh_read( f, buf, len );
440}
441
442
443int adb_write(int fd, const void* buf, int len)
444{
Spencer Low3a2421b2015-05-22 20:09:06 -0700445 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800446
447 if (f == NULL) {
448 return -1;
449 }
450
451 return f->clazz->_fh_write(f, buf, len);
452}
453
454
455int adb_lseek(int fd, int pos, int where)
456{
Spencer Low3a2421b2015-05-22 20:09:06 -0700457 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800458
459 if (!f) {
460 return -1;
461 }
462
463 return f->clazz->_fh_lseek(f, pos, where);
464}
465
466
467int adb_close(int fd)
468{
Spencer Low3a2421b2015-05-22 20:09:06 -0700469 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800470
471 if (!f) {
472 return -1;
473 }
474
Yabin Cui815ad882015-09-02 17:44:28 -0700475 D( "adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800476 _fh_close(f);
477 return 0;
478}
479
Spencer Low028e1592015-10-18 16:45:09 -0700480// Overrides strerror() to handle error codes not supported by the Windows C
481// Runtime (MSVCRT.DLL).
482char* adb_strerror(int err) {
483 // sysdeps.h defines strerror to adb_strerror, but in this function, we
484 // want to call the real C Runtime strerror().
485#pragma push_macro("strerror")
486#undef strerror
487 const int saved_err = errno; // Save because we overwrite it later.
488
489 // Lookup the string for an unknown error.
490 char* errmsg = strerror(-1);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700491 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low028e1592015-10-18 16:45:09 -0700492
493 // Lookup the string for this error to see if the C Runtime has it.
494 errmsg = strerror(err);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700495 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low028e1592015-10-18 16:45:09 -0700496 // The CRT returned an error message and it is different than the error
497 // message for an unknown error, so it is probably valid, so use it.
498 } else {
499 // Check if we have a string for this error code.
500 const char* custom_msg = nullptr;
501 switch (err) {
502#pragma push_macro("ERR")
503#undef ERR
504#define ERR(errnum, desc) case errnum: custom_msg = desc; break
505 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
506 // Note that these cannot be longer than 94 characters because we
507 // pass this to _strerror() which has that requirement.
508 ERR(ECONNRESET, "Connection reset by peer");
509 ERR(EHOSTUNREACH, "No route to host");
510 ERR(ENETDOWN, "Network is down");
511 ERR(ENETRESET, "Network dropped connection because of reset");
512 ERR(ENOBUFS, "No buffer space available");
513 ERR(ENOPROTOOPT, "Protocol not available");
514 ERR(ENOTCONN, "Transport endpoint is not connected");
515 ERR(ENOTSOCK, "Socket operation on non-socket");
516 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
517#pragma pop_macro("ERR")
518 }
519
520 if (custom_msg != nullptr) {
521 // Use _strerror() to write our string into the writable per-thread
522 // buffer used by strerror()/_strerror(). _strerror() appends the
523 // msg for the current value of errno, so set errno to a consistent
524 // value for every call so that our code-path is always the same.
525 errno = 0;
526 errmsg = _strerror(custom_msg);
527 const size_t custom_msg_len = strlen(custom_msg);
528 // Just in case _strerror() returned a read-only string, check if
529 // the returned string starts with our custom message because that
530 // implies that the string is not read-only.
531 if ((errmsg != nullptr) &&
532 !strncmp(custom_msg, errmsg, custom_msg_len)) {
533 // _strerror() puts other text after our custom message, so
534 // remove that by terminating after our message.
535 errmsg[custom_msg_len] = '\0';
536 } else {
537 // For some reason nullptr was returned or a pointer to a
538 // read-only string was returned, so fallback to whatever
539 // strerror() can muster (probably "Unknown error" or some
540 // generic CRT error string).
541 errmsg = strerror(err);
542 }
543 } else {
544 // We don't have a custom message, so use whatever strerror(err)
545 // returned earlier.
546 }
547 }
548
549 errno = saved_err; // restore
550
551 return errmsg;
552#pragma pop_macro("strerror")
553}
554
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800555/**************************************************************************/
556/**************************************************************************/
557/***** *****/
558/***** socket-based file descriptors *****/
559/***** *****/
560/**************************************************************************/
561/**************************************************************************/
562
Spencer Low31aafa62015-01-25 14:40:16 -0800563#undef setsockopt
564
Spencer Low753d4852015-07-30 23:07:55 -0700565static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700566 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
567 // lot of POSIX and socket error codes, some of the resulting error codes
568 // are mapped to strings by adb_strerror() above.
Spencer Low753d4852015-07-30 23:07:55 -0700569 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800570 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700571 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
572 // case WSAEINTR: errno = EINTR; break;
573 case WSAEFAULT: errno = EFAULT; break;
574 case WSAEINVAL: errno = EINVAL; break;
575 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700576 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
577 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
578 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800579 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700580 case WSAENOTSOCK: errno = ENOTSOCK; break;
581 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
582 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
583 case WSAENETDOWN: errno = ENETDOWN; break;
584 case WSAENETRESET: errno = ENETRESET; break;
585 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
586 // to use EPIPE for these situations and there are some callers that look
587 // for EPIPE.
588 case WSAECONNABORTED: errno = EPIPE; break;
589 case WSAECONNRESET: errno = ECONNRESET; break;
590 case WSAENOBUFS: errno = ENOBUFS; break;
591 case WSAENOTCONN: errno = ENOTCONN; break;
592 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
593 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
594 // considerations: Reportedly send() can return zero on timeout, and POSIX
595 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
596 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
597 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800598 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800599 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700600 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700601 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800602 }
603}
604
Josh Gaoe7388122016-02-16 17:34:53 -0800605extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
606 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
607 int skipped = 0;
608 std::vector<WSAPOLLFD> sockets;
609 std::vector<adb_pollfd*> original;
610 for (size_t i = 0; i < nfds; ++i) {
611 FH fh = _fh_from_int(fds[i].fd, __func__);
612 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
613 D("adb_poll received bad FD %d", fds[i].fd);
614 fds[i].revents = POLLNVAL;
615 ++skipped;
616 } else {
617 WSAPOLLFD wsapollfd = {
618 .fd = fh->u.socket,
619 .events = static_cast<short>(fds[i].events)
620 };
621 sockets.push_back(wsapollfd);
622 original.push_back(&fds[i]);
623 }
Spencer Low753d4852015-07-30 23:07:55 -0700624 }
Josh Gaoe7388122016-02-16 17:34:53 -0800625
626 if (sockets.empty()) {
627 return skipped;
628 }
629
630 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
631 if (result == SOCKET_ERROR) {
632 _socket_set_errno(WSAGetLastError());
633 return -1;
634 }
635
636 // Map the results back onto the original set.
637 for (size_t i = 0; i < sockets.size(); ++i) {
638 original[i]->revents = sockets[i].revents;
639 }
640
641 // WSAPoll appears to return the number of unique FDs with avaiable events, instead of how many
642 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
643 // to do. Ignore its result and calculate the proper return value.
644 result = 0;
645 for (size_t i = 0; i < nfds; ++i) {
646 if (fds[i].revents != 0) {
647 ++result;
648 }
649 }
650 return result;
651}
652
653static void _fh_socket_init(FH f) {
654 f->fh_socket = INVALID_SOCKET;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800655 f->mask = 0;
656}
657
Elliott Hughes6a096932015-04-16 16:47:02 -0700658static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700659 if (f->fh_socket != INVALID_SOCKET) {
660 /* gently tell any peer that we're closing the socket */
661 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
662 // If the socket is not connected, this returns an error. We want to
663 // minimize logging spam, so don't log these errors for now.
664#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700665 D("socket shutdown failed: %s",
David Pursellc573d522016-01-27 08:52:53 -0800666 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700667#endif
668 }
669 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800670 // Don't set errno here, since adb_close will ignore it.
671 const DWORD err = WSAGetLastError();
672 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700673 }
674 f->fh_socket = INVALID_SOCKET;
675 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800676 f->mask = 0;
677 return 0;
678}
679
Elliott Hughes6a096932015-04-16 16:47:02 -0700680static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800681 errno = EPIPE;
682 return -1;
683}
684
Elliott Hughes6a096932015-04-16 16:47:02 -0700685static int _fh_socket_read(FH f, void* buf, int len) {
686 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800687 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700688 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700689 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
690 // that to reduce spam and confusion.
691 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700692 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800693 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low32625852015-08-11 16:45:32 -0700694 }
Spencer Low753d4852015-07-30 23:07:55 -0700695 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800696 result = -1;
697 }
698 return result;
699}
700
Elliott Hughes6a096932015-04-16 16:47:02 -0700701static int _fh_socket_write(FH f, const void* buf, int len) {
702 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800703 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700704 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700705 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
706 // that to reduce spam and confusion.
707 if (err != WSAEWOULDBLOCK) {
708 D("send fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800709 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low028e1592015-10-18 16:45:09 -0700710 }
Spencer Low753d4852015-07-30 23:07:55 -0700711 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800712 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700713 } else {
714 // According to https://code.google.com/p/chromium/issues/detail?id=27870
715 // Winsock Layered Service Providers may cause this.
716 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
717 << f->name << ", but " << result
718 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800719 }
720 return result;
721}
722
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800723/**************************************************************************/
724/**************************************************************************/
725/***** *****/
726/***** replacement for libs/cutils/socket_xxxx.c *****/
727/***** *****/
728/**************************************************************************/
729/**************************************************************************/
730
731#include <winsock2.h>
732
733static int _winsock_init;
734
735static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800736_init_winsock( void )
737{
Spencer Low753d4852015-07-30 23:07:55 -0700738 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700739 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800740 if (!_winsock_init) {
741 WSADATA wsaData;
742 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
743 if (rc != 0) {
David Pursellc573d522016-01-27 08:52:53 -0800744 fatal("adb: could not initialize Winsock: %s",
745 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800746 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800747 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700748
749 // Note that we do not call atexit() to register WSACleanup to be called
750 // at normal process termination because:
751 // 1) When exit() is called, there are still threads actively using
752 // Winsock because we don't cleanly shutdown all threads, so it
753 // doesn't make sense to call WSACleanup() and may cause problems
754 // with those threads.
755 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
756 // calls WSACleanup() which tries to unload a DLL, which tries to
757 // grab the LoaderLock. This conflicts with the device_poll_thread
758 // which holds the LoaderLock because AdbWinApi.dll calls
759 // setupapi.dll which tries to load wintrust.dll which tries to load
760 // crypt32.dll which calls atexit() which tries to acquire the C
761 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800762 }
763}
764
Spencer Lowc7c45612015-09-29 15:05:29 -0700765// Map a socket type to an explicit socket protocol instead of using the socket
766// protocol of 0. Explicit socket protocols are used by most apps and we should
767// do the same to reduce the chance of exercising uncommon code-paths that might
768// have problems or that might load different Winsock service providers that
769// have problems.
770static int GetSocketProtocolFromSocketType(int type) {
771 switch (type) {
772 case SOCK_STREAM:
773 return IPPROTO_TCP;
774 case SOCK_DGRAM:
775 return IPPROTO_UDP;
776 default:
777 LOG(FATAL) << "Unknown socket type: " << type;
778 return 0;
779 }
780}
781
Spencer Low753d4852015-07-30 23:07:55 -0700782int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800783 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800784 SOCKET s;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800785
Josh Gao61eda8d2016-02-18 13:43:55 -0800786 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low753d4852015-07-30 23:07:55 -0700787 if (!f) {
788 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800789 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700790 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800791
Josh Gao61eda8d2016-02-18 13:43:55 -0800792 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800793
794 memset(&addr, 0, sizeof(addr));
795 addr.sin_family = AF_INET;
796 addr.sin_port = htons(port);
797 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
798
Spencer Lowc7c45612015-09-29 15:05:29 -0700799 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao61eda8d2016-02-18 13:43:55 -0800800 if (s == INVALID_SOCKET) {
801 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700802 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800803 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700804 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800805 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700806 return -1;
807 }
808 f->fh_socket = s;
809
Josh Gao61eda8d2016-02-18 13:43:55 -0800810 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700811 // Save err just in case inet_ntoa() or ntohs() changes the last error.
812 const DWORD err = WSAGetLastError();
813 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800814 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
815 android::base::SystemErrorCodeToString(err).c_str());
816 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
817 error->c_str());
818 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800819 return -1;
820 }
821
Spencer Low753d4852015-07-30 23:07:55 -0700822 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800823 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
824 port);
825 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700826 f.release();
827 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800828}
829
830#define LISTEN_BACKLOG 4
831
Spencer Low753d4852015-07-30 23:07:55 -0700832// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao61eda8d2016-02-18 13:43:55 -0800833static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800834 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800835 SOCKET s;
836 int n;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800837
Josh Gao61eda8d2016-02-18 13:43:55 -0800838 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800839 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700840 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800841 return -1;
842 }
843
Josh Gao61eda8d2016-02-18 13:43:55 -0800844 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800845
846 memset(&addr, 0, sizeof(addr));
847 addr.sin_family = AF_INET;
848 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700849 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800850
Spencer Low753d4852015-07-30 23:07:55 -0700851 // TODO: Consider using dual-stack socket that can simultaneously listen on
852 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700853 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700854 if (s == INVALID_SOCKET) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800855 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700856 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800857 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700858 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800859 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700860 return -1;
861 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800862
863 f->fh_socket = s;
864
Spencer Low32625852015-08-11 16:45:32 -0700865 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
866 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800867 n = 1;
Josh Gao61eda8d2016-02-18 13:43:55 -0800868 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
869 const DWORD err = WSAGetLastError();
870 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
871 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700872 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800873 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700874 return -1;
875 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800876
Josh Gao61eda8d2016-02-18 13:43:55 -0800877 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700878 // Save err just in case inet_ntoa() or ntohs() changes the last error.
879 const DWORD err = WSAGetLastError();
Josh Gao61eda8d2016-02-18 13:43:55 -0800880 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
881 ntohs(addr.sin_port),
882 android::base::SystemErrorCodeToString(err).c_str());
883 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
884 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800885 return -1;
886 }
887 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700888 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800889 const DWORD err = WSAGetLastError();
890 *error = android::base::StringPrintf(
891 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
892 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
893 error->c_str());
894 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800895 return -1;
896 }
897 }
Spencer Low753d4852015-07-30 23:07:55 -0700898 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800899 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
900 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
901 port);
902 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700903 f.release();
904 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800905}
906
Spencer Low753d4852015-07-30 23:07:55 -0700907int network_loopback_server(int port, int type, std::string* error) {
908 return _network_server(port, type, INADDR_LOOPBACK, error);
909}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800910
Spencer Low753d4852015-07-30 23:07:55 -0700911int network_inaddr_any_server(int port, int type, std::string* error) {
912 return _network_server(port, type, INADDR_ANY, error);
913}
914
915int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
916 unique_fh f(_fh_alloc(&_fh_socket_class));
917 if (!f) {
918 *error = strerror(errno);
919 return -1;
920 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800921
Elliott Hughes43df1092015-07-23 17:12:58 -0700922 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800923
Spencer Low753d4852015-07-30 23:07:55 -0700924 struct addrinfo hints;
925 memset(&hints, 0, sizeof(hints));
926 hints.ai_family = AF_UNSPEC;
927 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700928 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700929
930 char port_str[16];
931 snprintf(port_str, sizeof(port_str), "%d", port);
932
933 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700934
935#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao61eda8d2016-02-18 13:43:55 -0800936// TODO: When the Android SDK tools increases the Windows system
937// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700938#else
Josh Gao61eda8d2016-02-18 13:43:55 -0800939// Otherwise, keep using getaddrinfo(), or do runtime API detection
940// with GetProcAddress("GetAddrInfoW").
Spencer Lowcc467f12015-08-02 18:13:54 -0700941#endif
Spencer Low753d4852015-07-30 23:07:55 -0700942 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800943 const DWORD err = WSAGetLastError();
944 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
945 host.c_str(), port_str,
946 android::base::SystemErrorCodeToString(err).c_str());
947
Yabin Cui815ad882015-09-02 17:44:28 -0700948 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800949 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800950 return -1;
951 }
Elliott Hughes8ac45992016-08-08 12:52:37 -0700952 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low753d4852015-07-30 23:07:55 -0700953 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800954
Spencer Low753d4852015-07-30 23:07:55 -0700955 // TODO: Try all the addresses if there's more than one? This just uses
956 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
957 // which tries all addresses, takes a timeout and more.
Josh Gao61eda8d2016-02-18 13:43:55 -0800958 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
959 if (s == INVALID_SOCKET) {
960 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700961 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800962 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700963 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800964 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800965 return -1;
966 }
967 f->fh_socket = s;
968
Spencer Low753d4852015-07-30 23:07:55 -0700969 // TODO: Implement timeouts for Windows. Seems like the default in theory
970 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao61eda8d2016-02-18 13:43:55 -0800971 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700972 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao61eda8d2016-02-18 13:43:55 -0800973 const DWORD err = WSAGetLastError();
974 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
975 android::base::SystemErrorCodeToString(err).c_str());
976 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
977 port_str, error->c_str());
978 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800979 return -1;
980 }
981
Spencer Low753d4852015-07-30 23:07:55 -0700982 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800983 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
984 port);
985 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
986 fd);
Spencer Low753d4852015-07-30 23:07:55 -0700987 f.release();
988 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800989}
990
991#undef accept
992int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
993{
Spencer Low3a2421b2015-05-22 20:09:06 -0700994 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200995
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800996 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700997 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -0700998 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800999 return -1;
1000 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001001
Spencer Low753d4852015-07-30 23:07:55 -07001002 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001003 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -07001004 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1005 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001006 return -1;
1007 }
1008
1009 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1010 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001011 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -07001012 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursellc573d522016-01-27 08:52:53 -08001013 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low753d4852015-07-30 23:07:55 -07001014 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001015 return -1;
1016 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001017
Spencer Low753d4852015-07-30 23:07:55 -07001018 const int fd = _fh_to_int(fh.get());
1019 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -07001020 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -07001021 fh.release();
1022 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001023}
1024
1025
Spencer Low31aafa62015-01-25 14:40:16 -08001026int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001027{
Spencer Low3a2421b2015-05-22 20:09:06 -07001028 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001029
Spencer Low31aafa62015-01-25 14:40:16 -08001030 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001031 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001032 errno = EBADF;
1033 return -1;
1034 }
Spencer Lowc7c45612015-09-29 15:05:29 -07001035
1036 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1037 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1038 // auto-tuning.
1039
Spencer Low753d4852015-07-30 23:07:55 -07001040 int result = setsockopt( fh->fh_socket, level, optname,
1041 reinterpret_cast<const char*>(optval), optlen );
1042 if ( result == SOCKET_ERROR ) {
1043 const DWORD err = WSAGetLastError();
David Pursellc573d522016-01-27 08:52:53 -08001044 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1045 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001046 _socket_set_errno( err );
1047 result = -1;
1048 }
1049 return result;
1050}
1051
Josh Gaoe7388122016-02-16 17:34:53 -08001052int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1053 FH fh = _fh_from_int(fd, __func__);
1054
1055 if (!fh || fh->clazz != &_fh_socket_class) {
1056 D("adb_getsockname: invalid fd %d", fd);
1057 errno = EBADF;
1058 return -1;
1059 }
1060
Josh Gaod6001b52016-08-23 15:28:43 -07001061 int result = (getsockname)(fh->fh_socket, sockaddr, optlen);
Josh Gaoe7388122016-02-16 17:34:53 -08001062 if (result == SOCKET_ERROR) {
1063 const DWORD err = WSAGetLastError();
1064 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1065 android::base::SystemErrorCodeToString(err).c_str());
1066 _socket_set_errno(err);
1067 result = -1;
1068 }
1069 return result;
1070}
Spencer Low753d4852015-07-30 23:07:55 -07001071
David Pursell19d0c232016-04-07 11:25:48 -07001072int adb_socket_get_local_port(int fd) {
1073 sockaddr_storage addr_storage;
1074 socklen_t addr_len = sizeof(addr_storage);
1075
1076 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1077 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1078 return -1;
1079 }
1080
1081 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1082 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1083 errno = ECONNABORTED;
1084 return -1;
1085 }
1086
1087 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1088}
1089
Spencer Low753d4852015-07-30 23:07:55 -07001090int adb_shutdown(int fd)
1091{
1092 FH f = _fh_from_int(fd, __func__);
1093
1094 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001095 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001096 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001097 return -1;
1098 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001099
Yabin Cui815ad882015-09-02 17:44:28 -07001100 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001101 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1102 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001103 D("socket shutdown fd %d failed: %s", fd,
David Pursellc573d522016-01-27 08:52:53 -08001104 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001105 _socket_set_errno(err);
1106 return -1;
1107 }
1108 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001109}
1110
Josh Gaoe7388122016-02-16 17:34:53 -08001111// Emulate socketpair(2) by binding and connecting to a socket.
1112int adb_socketpair(int sv[2]) {
1113 int server = -1;
1114 int client = -1;
1115 int accepted = -1;
David Pursell19d0c232016-04-07 11:25:48 -07001116 int local_port = -1;
Josh Gaoe7388122016-02-16 17:34:53 -08001117 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001118
Josh Gaod6001b52016-08-23 15:28:43 -07001119 struct sockaddr_storage peer_addr = {};
1120 struct sockaddr_storage client_addr = {};
1121 socklen_t peer_socklen = sizeof(peer_addr);
1122 socklen_t client_socklen = sizeof(client_addr);
1123
Josh Gaoe7388122016-02-16 17:34:53 -08001124 server = network_loopback_server(0, SOCK_STREAM, &error);
1125 if (server < 0) {
1126 D("adb_socketpair: failed to create server: %s", error.c_str());
1127 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001128 }
1129
David Pursell19d0c232016-04-07 11:25:48 -07001130 local_port = adb_socket_get_local_port(server);
1131 if (local_port < 0) {
1132 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gaoe7388122016-02-16 17:34:53 -08001133 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001134 }
David Pursell19d0c232016-04-07 11:25:48 -07001135 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001136
David Pursell19d0c232016-04-07 11:25:48 -07001137 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gaoe7388122016-02-16 17:34:53 -08001138 if (client < 0) {
1139 D("adb_socketpair: failed to connect client: %s", error.c_str());
1140 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001141 }
1142
Josh Gaod6001b52016-08-23 15:28:43 -07001143 // Make sure that the peer that connected to us and the client are the same.
1144 accepted = adb_socket_accept(server, reinterpret_cast<sockaddr*>(&peer_addr), &peer_socklen);
Josh Gaoe7388122016-02-16 17:34:53 -08001145 if (accepted < 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -08001146 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoe7388122016-02-16 17:34:53 -08001147 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001148 }
Josh Gaod6001b52016-08-23 15:28:43 -07001149
1150 if (adb_getsockname(client, reinterpret_cast<sockaddr*>(&client_addr), &client_socklen) != 0) {
1151 D("adb_socketpair: failed to getpeername: %s", strerror(errno));
1152 goto fail;
1153 }
1154
1155 if (peer_socklen != client_socklen) {
1156 D("adb_socketpair: client and peer sockaddrs have different lengths");
1157 errno = EIO;
1158 goto fail;
1159 }
1160
1161 if (memcmp(&peer_addr, &client_addr, peer_socklen) != 0) {
1162 D("adb_socketpair: client and peer sockaddrs don't match");
1163 errno = EIO;
1164 goto fail;
1165 }
1166
Josh Gaoe7388122016-02-16 17:34:53 -08001167 adb_close(server);
Josh Gaod6001b52016-08-23 15:28:43 -07001168
Josh Gaoe7388122016-02-16 17:34:53 -08001169 sv[0] = client;
1170 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001171 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001172
Josh Gaoe7388122016-02-16 17:34:53 -08001173fail:
1174 if (server >= 0) {
1175 adb_close(server);
1176 }
1177 if (client >= 0) {
1178 adb_close(client);
1179 }
1180 if (accepted >= 0) {
1181 adb_close(accepted);
1182 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001183 return -1;
1184}
1185
Josh Gaoe7388122016-02-16 17:34:53 -08001186bool set_file_block_mode(int fd, bool block) {
1187 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001188
Josh Gaoe7388122016-02-16 17:34:53 -08001189 if (!fh || !fh->used) {
1190 errno = EBADF;
1191 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001192 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001193
Josh Gaoe7388122016-02-16 17:34:53 -08001194 if (fh->clazz == &_fh_socket_class) {
1195 u_long x = !block;
1196 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
1197 _socket_set_errno(WSAGetLastError());
1198 return false;
1199 }
1200 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001201 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001202 errno = ENOTSOCK;
1203 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001204 }
1205}
1206
David Pursellc25a34e2016-02-22 14:27:23 -08001207bool set_tcp_keepalive(int fd, int interval_sec) {
1208 FH fh = _fh_from_int(fd, __func__);
1209
1210 if (!fh || fh->clazz != &_fh_socket_class) {
1211 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1212 errno = EBADF;
1213 return false;
1214 }
1215
1216 tcp_keepalive keepalive;
1217 keepalive.onoff = (interval_sec > 0);
1218 keepalive.keepalivetime = interval_sec * 1000;
1219 keepalive.keepaliveinterval = interval_sec * 1000;
1220
1221 DWORD bytes_returned = 0;
1222 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1223 &bytes_returned, nullptr, nullptr) != 0) {
1224 const DWORD err = WSAGetLastError();
1225 D("set_tcp_keepalive(%d) failed: %s", fd,
1226 android::base::SystemErrorCodeToString(err).c_str());
1227 _socket_set_errno(err);
1228 return false;
1229 }
1230
1231 return true;
1232}
1233
Spencer Lowbeb61982015-03-01 15:06:21 -08001234/**************************************************************************/
1235/**************************************************************************/
1236/***** *****/
1237/***** Console Window Terminal Emulation *****/
1238/***** *****/
1239/**************************************************************************/
1240/**************************************************************************/
1241
1242// This reads input from a Win32 console window and translates it into Unix
1243// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1244// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1245// is emulated instead of xterm because it is probably more popular than xterm:
1246// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1247// supports modern fonts, etc. It seems best to emulate the terminal that most
1248// Android developers use because they'll fix apps (the shell, etc.) to keep
1249// working with that terminal's emulation.
1250//
1251// The point of this emulation is not to be perfect or to solve all issues with
1252// console windows on Windows, but to be better than the original code which
1253// just called read() (which called ReadFile(), which called ReadConsoleA())
1254// which did not support Ctrl-C, tab completion, shell input line editing
1255// keys, server echo, and more.
1256//
1257// This implementation reconfigures the console with SetConsoleMode(), then
1258// calls ReadConsoleInput() to get raw input which it remaps to Unix
1259// terminal-style sequences which is returned via unix_read() which is used
1260// by the 'adb shell' command.
1261//
1262// Code organization:
1263//
David Pursell58805362015-10-28 14:29:51 -07001264// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001265// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1266// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1267// * _console_read() is the main code of the emulation.
1268
David Pursell58805362015-10-28 14:29:51 -07001269// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1270// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1271// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1272static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1273 // First check isatty(); this is very fast and eliminates most non-console
1274 // FDs, but returns 1 for both consoles and character devices like NUL.
1275#pragma push_macro("isatty")
1276#undef isatty
1277 if (!isatty(fd)) {
1278 return nullptr;
1279 }
1280#pragma pop_macro("isatty")
1281
1282 // To differentiate between character devices and consoles we need to get
1283 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1284 // GENERIC_READ permissions.
1285 const intptr_t intptr_handle = _get_osfhandle(fd);
1286 if (intptr_handle == -1) {
1287 return nullptr;
1288 }
1289 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1290 DWORD temp_mode = 0;
1291 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1292 return nullptr;
1293 }
1294
1295 return handle;
1296}
1297
1298// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1299static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001300 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1301 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001302 const int fd = fileno(stream);
1303 if (fd < 0) {
1304 return nullptr;
1305 }
1306 return _get_console_handle(fd);
1307}
1308
1309int unix_isatty(int fd) {
1310 return _get_console_handle(fd) ? 1 : 0;
1311}
Spencer Lowbeb61982015-03-01 15:06:21 -08001312
Spencer Low9c8f7462015-11-10 19:17:16 -08001313// Get the next KEY_EVENT_RECORD that should be processed.
1314static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001315 for (;;) {
1316 DWORD read_count = 0;
1317 memset(input_record, 0, sizeof(*input_record));
1318 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001319 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001320 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001321 errno = EIO;
1322 return false;
1323 }
1324
1325 if (read_count == 0) { // should be impossible
1326 fatal("ReadConsoleInputA returned 0");
1327 }
1328
1329 if (read_count != 1) { // should be impossible
1330 fatal("ReadConsoleInputA did not return one input record");
1331 }
1332
Spencer Low55441402015-11-07 17:34:39 -08001333 // If the console window is resized, emulate SIGWINCH by breaking out
1334 // of read() with errno == EINTR. Note that there is no event on
1335 // vertical resize because we don't give the console our own custom
1336 // screen buffer (with CreateConsoleScreenBuffer() +
1337 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1338 // supports scrollback, but doesn't seem to raise an event for vertical
1339 // window resize.
1340 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1341 errno = EINTR;
1342 return false;
1343 }
1344
Spencer Lowbeb61982015-03-01 15:06:21 -08001345 if ((input_record->EventType == KEY_EVENT) &&
1346 (input_record->Event.KeyEvent.bKeyDown)) {
1347 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1348 fatal("ReadConsoleInputA returned a key event with zero repeat"
1349 " count");
1350 }
1351
1352 // Got an interesting INPUT_RECORD, so return
1353 return true;
1354 }
1355 }
1356}
1357
Spencer Lowbeb61982015-03-01 15:06:21 -08001358static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1359 return (control_key_state & SHIFT_PRESSED) != 0;
1360}
1361
1362static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1363 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1364}
1365
1366static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1367 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1368}
1369
1370static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1371 return (control_key_state & NUMLOCK_ON) != 0;
1372}
1373
1374static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1375 return (control_key_state & CAPSLOCK_ON) != 0;
1376}
1377
1378static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1379 return (control_key_state & ENHANCED_KEY) != 0;
1380}
1381
1382// Constants from MSDN for ToAscii().
1383static const BYTE TOASCII_KEY_OFF = 0x00;
1384static const BYTE TOASCII_KEY_DOWN = 0x80;
1385static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1386
1387// Given a key event, ignore a modifier key and return the character that was
1388// entered without the modifier. Writes to *ch and returns the number of bytes
1389// written.
1390static size_t _get_char_ignoring_modifier(char* const ch,
1391 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1392 const WORD modifier) {
1393 // If there is no character from Windows, try ignoring the specified
1394 // modifier and look for a character. Note that if AltGr is being used,
1395 // there will be a character from Windows.
1396 if (key_event->uChar.AsciiChar == '\0') {
1397 // Note that we read the control key state from the passed in argument
1398 // instead of from key_event since the argument has been normalized.
1399 if (((modifier == VK_SHIFT) &&
1400 _is_shift_pressed(control_key_state)) ||
1401 ((modifier == VK_CONTROL) &&
1402 _is_ctrl_pressed(control_key_state)) ||
1403 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1404
1405 BYTE key_state[256] = {0};
1406 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1407 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1408 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1409 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1410 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1411 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1412 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1413 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1414
1415 // cause this modifier to be ignored
1416 key_state[modifier] = TOASCII_KEY_OFF;
1417
1418 WORD translated = 0;
1419 if (ToAscii(key_event->wVirtualKeyCode,
1420 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1421 // Ignoring the modifier, we found a character.
1422 *ch = (CHAR)translated;
1423 return 1;
1424 }
1425 }
1426 }
1427
1428 // Just use whatever Windows told us originally.
1429 *ch = key_event->uChar.AsciiChar;
1430
1431 // If the character from Windows is NULL, return a size of zero.
1432 return (*ch == '\0') ? 0 : 1;
1433}
1434
1435// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1436// but taking into account the shift key. This is because for a sequence like
1437// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1438// we want to find the character ')'.
1439//
1440// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1441// because it is the default key-sequence to switch the input language.
1442// This is configurable in the Region and Language control panel.
1443static __inline__ size_t _get_non_control_char(char* const ch,
1444 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1445 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1446 VK_CONTROL);
1447}
1448
1449// Get without Alt.
1450static __inline__ size_t _get_non_alt_char(char* const ch,
1451 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1452 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1453 VK_MENU);
1454}
1455
1456// Ignore the control key, find the character from Windows, and apply any
1457// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1458// *pch and returns number of bytes written.
1459static size_t _get_control_character(char* const pch,
1460 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1461 const size_t len = _get_non_control_char(pch, key_event,
1462 control_key_state);
1463
1464 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1465 char ch = *pch;
1466 switch (ch) {
1467 case '2':
1468 case '@':
1469 case '`':
1470 ch = '\0';
1471 break;
1472 case '3':
1473 case '[':
1474 case '{':
1475 ch = '\x1b';
1476 break;
1477 case '4':
1478 case '\\':
1479 case '|':
1480 ch = '\x1c';
1481 break;
1482 case '5':
1483 case ']':
1484 case '}':
1485 ch = '\x1d';
1486 break;
1487 case '6':
1488 case '^':
1489 case '~':
1490 ch = '\x1e';
1491 break;
1492 case '7':
1493 case '-':
1494 case '_':
1495 ch = '\x1f';
1496 break;
1497 case '8':
1498 ch = '\x7f';
1499 break;
1500 case '/':
1501 if (!_is_alt_pressed(control_key_state)) {
1502 ch = '\x1f';
1503 }
1504 break;
1505 case '?':
1506 if (!_is_alt_pressed(control_key_state)) {
1507 ch = '\x7f';
1508 }
1509 break;
1510 }
1511 *pch = ch;
1512 }
1513
1514 return len;
1515}
1516
1517static DWORD _normalize_altgr_control_key_state(
1518 const KEY_EVENT_RECORD* const key_event) {
1519 DWORD control_key_state = key_event->dwControlKeyState;
1520
1521 // If we're in an AltGr situation where the AltGr key is down (depending on
1522 // the keyboard layout, that might be the physical right alt key which
1523 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1524 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1525 // a character (which indicates that there was an AltGr mapping), then act
1526 // as if alt and control are not really down for the purposes of modifiers.
1527 // This makes it so that if the user with, say, a German keyboard layout
1528 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1529 // output the key and we don't see the Alt and Ctrl keys.
1530 if (_is_ctrl_pressed(control_key_state) &&
1531 _is_alt_pressed(control_key_state)
1532 && (key_event->uChar.AsciiChar != '\0')) {
1533 // Try to remove as few bits as possible to improve our chances of
1534 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1535 // Left-Alt + Right-Ctrl + AltGr.
1536 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1537 // Remove Right-Alt.
1538 control_key_state &= ~RIGHT_ALT_PRESSED;
1539 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1540 // pressed, Left-Ctrl is almost always set, except if the user
1541 // presses Right-Ctrl, then AltGr (in that specific order) for
1542 // whatever reason. At any rate, make sure the bit is not set.
1543 control_key_state &= ~LEFT_CTRL_PRESSED;
1544 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1545 // Remove Left-Alt.
1546 control_key_state &= ~LEFT_ALT_PRESSED;
1547 // Whichever Ctrl key is down, remove it from the state. We only
1548 // remove one key, to improve our chances of detecting the
1549 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1550 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1551 // Remove Left-Ctrl.
1552 control_key_state &= ~LEFT_CTRL_PRESSED;
1553 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1554 // Remove Right-Ctrl.
1555 control_key_state &= ~RIGHT_CTRL_PRESSED;
1556 }
1557 }
1558
1559 // Note that this logic isn't 100% perfect because Windows doesn't
1560 // allow us to detect all combinations because a physical AltGr key
1561 // press shows up as two bits, plus some combinations are ambiguous
1562 // about what is actually physically pressed.
1563 }
1564
1565 return control_key_state;
1566}
1567
1568// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1569// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1570// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1571// appropriately.
1572static DWORD _normalize_keypad_control_key_state(const WORD vk,
1573 const DWORD control_key_state) {
1574 if (!_is_numlock_on(control_key_state)) {
1575 return control_key_state;
1576 }
1577 if (!_is_enhanced_key(control_key_state)) {
1578 switch (vk) {
1579 case VK_INSERT: // 0
1580 case VK_DELETE: // .
1581 case VK_END: // 1
1582 case VK_DOWN: // 2
1583 case VK_NEXT: // 3
1584 case VK_LEFT: // 4
1585 case VK_CLEAR: // 5
1586 case VK_RIGHT: // 6
1587 case VK_HOME: // 7
1588 case VK_UP: // 8
1589 case VK_PRIOR: // 9
1590 return control_key_state | SHIFT_PRESSED;
1591 }
1592 }
1593
1594 return control_key_state;
1595}
1596
1597static const char* _get_keypad_sequence(const DWORD control_key_state,
1598 const char* const normal, const char* const shifted) {
1599 if (_is_shift_pressed(control_key_state)) {
1600 // Shift is pressed and NumLock is off
1601 return shifted;
1602 } else {
1603 // Shift is not pressed and NumLock is off, or,
1604 // Shift is pressed and NumLock is on, in which case we want the
1605 // NumLock and Shift to neutralize each other, thus, we want the normal
1606 // sequence.
1607 return normal;
1608 }
1609 // If Shift is not pressed and NumLock is on, a different virtual key code
1610 // is returned by Windows, which can be taken care of by a different case
1611 // statement in _console_read().
1612}
1613
1614// Write sequence to buf and return the number of bytes written.
1615static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1616 DWORD control_key_state, const char* const normal) {
1617 // Copy the base sequence into buf.
1618 const size_t len = strlen(normal);
1619 memcpy(buf, normal, len);
1620
1621 int code = 0;
1622
1623 control_key_state = _normalize_keypad_control_key_state(vk,
1624 control_key_state);
1625
1626 if (_is_shift_pressed(control_key_state)) {
1627 code |= 0x1;
1628 }
1629 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1630 code |= 0x2;
1631 }
1632 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1633 code |= 0x4;
1634 }
1635 // If some modifier was held down, then we need to insert the modifier code
1636 if (code != 0) {
1637 if (len == 0) {
1638 // Should be impossible because caller should pass a string of
1639 // non-zero length.
1640 return 0;
1641 }
1642 size_t index = len - 1;
1643 const char lastChar = buf[index];
1644 if (lastChar != '~') {
1645 buf[index++] = '1';
1646 }
1647 buf[index++] = ';'; // modifier separator
1648 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1649 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1650 buf[index++] = '1' + code;
1651 buf[index++] = lastChar; // move ~ (or other last char) to the end
1652 return index;
1653 }
1654 return len;
1655}
1656
1657// Write sequence to buf and return the number of bytes written.
1658static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1659 const DWORD control_key_state, const char* const normal,
1660 const char shifted) {
1661 if (_is_shift_pressed(control_key_state)) {
1662 // Shift is pressed and NumLock is off
1663 if (shifted != '\0') {
1664 buf[0] = shifted;
1665 return sizeof(buf[0]);
1666 } else {
1667 return 0;
1668 }
1669 } else {
1670 // Shift is not pressed and NumLock is off, or,
1671 // Shift is pressed and NumLock is on, in which case we want the
1672 // NumLock and Shift to neutralize each other, thus, we want the normal
1673 // sequence.
1674 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1675 }
1676 // If Shift is not pressed and NumLock is on, a different virtual key code
1677 // is returned by Windows, which can be taken care of by a different case
1678 // statement in _console_read().
1679}
1680
1681// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1682// Standard German. Figure this out at runtime so we know what to output for
1683// Shift-VK_DELETE.
1684static char _get_decimal_char() {
1685 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1686}
1687
1688// Prefix the len bytes in buf with the escape character, and then return the
1689// new buffer length.
1690size_t _escape_prefix(char* const buf, const size_t len) {
1691 // If nothing to prefix, don't do anything. We might be called with
1692 // len == 0, if alt was held down with a dead key which produced nothing.
1693 if (len == 0) {
1694 return 0;
1695 }
1696
1697 memmove(&buf[1], buf, len);
1698 buf[0] = '\x1b';
1699 return len + 1;
1700}
1701
Spencer Low9c8f7462015-11-10 19:17:16 -08001702// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001703static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001704
1705// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1706// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001707static int _console_read(const HANDLE console, void* buf, size_t len) {
1708 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001709 // Read of zero bytes should not block waiting for something from the console.
1710 if (len == 0) {
1711 return 0;
1712 }
1713
1714 // Flush as much as possible from input buffer.
1715 if (!g_console_input_buffer.empty()) {
1716 const int bytes_read = std::min(len, g_console_input_buffer.size());
1717 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1718 const auto begin = g_console_input_buffer.begin();
1719 g_console_input_buffer.erase(begin, begin + bytes_read);
1720 return bytes_read;
1721 }
1722
1723 // Read from the actual console. This may block until input.
1724 INPUT_RECORD input_record;
1725 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001726 return -1;
1727 }
1728
Spencer Low9c8f7462015-11-10 19:17:16 -08001729 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001730 const WORD vk = key_event->wVirtualKeyCode;
1731 const CHAR ch = key_event->uChar.AsciiChar;
1732 const DWORD control_key_state = _normalize_altgr_control_key_state(
1733 key_event);
1734
1735 // The following emulation code should write the output sequence to
1736 // either seqstr or to seqbuf and seqbuflen.
1737 const char* seqstr = NULL; // NULL terminated C-string
1738 // Enough space for max sequence string below, plus modifiers and/or
1739 // escape prefix.
1740 char seqbuf[16];
1741 size_t seqbuflen = 0; // Space used in seqbuf.
1742
1743#define MATCH(vk, normal) \
1744 case (vk): \
1745 { \
1746 seqstr = (normal); \
1747 } \
1748 break;
1749
1750 // Modifier keys should affect the output sequence.
1751#define MATCH_MODIFIER(vk, normal) \
1752 case (vk): \
1753 { \
1754 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1755 control_key_state, (normal)); \
1756 } \
1757 break;
1758
1759 // The shift key should affect the output sequence.
1760#define MATCH_KEYPAD(vk, normal, shifted) \
1761 case (vk): \
1762 { \
1763 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1764 (shifted)); \
1765 } \
1766 break;
1767
1768 // The shift key and other modifier keys should affect the output
1769 // sequence.
1770#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1771 case (vk): \
1772 { \
1773 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1774 control_key_state, (normal), (shifted)); \
1775 } \
1776 break;
1777
1778#define ESC "\x1b"
1779#define CSI ESC "["
1780#define SS3 ESC "O"
1781
1782 // Only support normal mode, not application mode.
1783
1784 // Enhanced keys:
1785 // * 6-pack: insert, delete, home, end, page up, page down
1786 // * cursor keys: up, down, right, left
1787 // * keypad: divide, enter
1788 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1789 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1790 if (_is_enhanced_key(control_key_state)) {
1791 switch (vk) {
1792 case VK_RETURN: // Enter key on keypad
1793 if (_is_ctrl_pressed(control_key_state)) {
1794 seqstr = "\n";
1795 } else {
1796 seqstr = "\r";
1797 }
1798 break;
1799
1800 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1801 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1802
1803 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1804 // will be fixed soon to match xterm which sends CSI "F" and
1805 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1806 MATCH(VK_END, CSI "F");
1807 MATCH(VK_HOME, CSI "H");
1808
1809 MATCH_MODIFIER(VK_LEFT, CSI "D");
1810 MATCH_MODIFIER(VK_UP, CSI "A");
1811 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1812 MATCH_MODIFIER(VK_DOWN, CSI "B");
1813
1814 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1815 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1816
1817 MATCH(VK_DIVIDE, "/");
1818 }
1819 } else { // Non-enhanced keys:
1820 switch (vk) {
1821 case VK_BACK: // backspace
1822 if (_is_alt_pressed(control_key_state)) {
1823 seqstr = ESC "\x7f";
1824 } else {
1825 seqstr = "\x7f";
1826 }
1827 break;
1828
1829 case VK_TAB:
1830 if (_is_shift_pressed(control_key_state)) {
1831 seqstr = CSI "Z";
1832 } else {
1833 seqstr = "\t";
1834 }
1835 break;
1836
1837 // Number 5 key in keypad when NumLock is off, or if NumLock is
1838 // on and Shift is down.
1839 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1840
1841 case VK_RETURN: // Enter key on main keyboard
1842 if (_is_alt_pressed(control_key_state)) {
1843 seqstr = ESC "\n";
1844 } else if (_is_ctrl_pressed(control_key_state)) {
1845 seqstr = "\n";
1846 } else {
1847 seqstr = "\r";
1848 }
1849 break;
1850
1851 // VK_ESCAPE: Don't do any special handling. The OS uses many
1852 // of the sequences with Escape and many of the remaining
1853 // sequences don't produce bKeyDown messages, only !bKeyDown
1854 // for whatever reason.
1855
1856 case VK_SPACE:
1857 if (_is_alt_pressed(control_key_state)) {
1858 seqstr = ESC " ";
1859 } else if (_is_ctrl_pressed(control_key_state)) {
1860 seqbuf[0] = '\0'; // NULL char
1861 seqbuflen = 1;
1862 } else {
1863 seqstr = " ";
1864 }
1865 break;
1866
1867 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1868 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1869
1870 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1871 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1872
1873 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1874 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1875 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1876 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1877
1878 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1879 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1880 _get_decimal_char());
1881
1882 case 0x30: // 0
1883 case 0x31: // 1
1884 case 0x39: // 9
1885 case VK_OEM_1: // ;:
1886 case VK_OEM_PLUS: // =+
1887 case VK_OEM_COMMA: // ,<
1888 case VK_OEM_PERIOD: // .>
1889 case VK_OEM_7: // '"
1890 case VK_OEM_102: // depends on keyboard, could be <> or \|
1891 case VK_OEM_2: // /?
1892 case VK_OEM_3: // `~
1893 case VK_OEM_4: // [{
1894 case VK_OEM_5: // \|
1895 case VK_OEM_6: // ]}
1896 {
1897 seqbuflen = _get_control_character(seqbuf, key_event,
1898 control_key_state);
1899
1900 if (_is_alt_pressed(control_key_state)) {
1901 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1902 }
1903 }
1904 break;
1905
1906 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001907 case 0x33: // 3
1908 case 0x34: // 4
1909 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001910 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001911 case 0x37: // 7
1912 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001913 case VK_OEM_MINUS: // -_
1914 {
1915 seqbuflen = _get_control_character(seqbuf, key_event,
1916 control_key_state);
1917
1918 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1919 // prefix with escape.
1920 if (_is_alt_pressed(control_key_state) &&
1921 !(_is_ctrl_pressed(control_key_state) &&
1922 !_is_shift_pressed(control_key_state))) {
1923 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1924 }
1925 }
1926 break;
1927
Spencer Lowbeb61982015-03-01 15:06:21 -08001928 case 0x41: // a
1929 case 0x42: // b
1930 case 0x43: // c
1931 case 0x44: // d
1932 case 0x45: // e
1933 case 0x46: // f
1934 case 0x47: // g
1935 case 0x48: // h
1936 case 0x49: // i
1937 case 0x4a: // j
1938 case 0x4b: // k
1939 case 0x4c: // l
1940 case 0x4d: // m
1941 case 0x4e: // n
1942 case 0x4f: // o
1943 case 0x50: // p
1944 case 0x51: // q
1945 case 0x52: // r
1946 case 0x53: // s
1947 case 0x54: // t
1948 case 0x55: // u
1949 case 0x56: // v
1950 case 0x57: // w
1951 case 0x58: // x
1952 case 0x59: // y
1953 case 0x5a: // z
1954 {
1955 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1956 control_key_state);
1957
1958 // If Alt is pressed, then prefix with escape.
1959 if (_is_alt_pressed(control_key_state)) {
1960 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1961 }
1962 }
1963 break;
1964
1965 // These virtual key codes are generated by the keys on the
1966 // keypad *when NumLock is on* and *Shift is up*.
1967 MATCH(VK_NUMPAD0, "0");
1968 MATCH(VK_NUMPAD1, "1");
1969 MATCH(VK_NUMPAD2, "2");
1970 MATCH(VK_NUMPAD3, "3");
1971 MATCH(VK_NUMPAD4, "4");
1972 MATCH(VK_NUMPAD5, "5");
1973 MATCH(VK_NUMPAD6, "6");
1974 MATCH(VK_NUMPAD7, "7");
1975 MATCH(VK_NUMPAD8, "8");
1976 MATCH(VK_NUMPAD9, "9");
1977
1978 MATCH(VK_MULTIPLY, "*");
1979 MATCH(VK_ADD, "+");
1980 MATCH(VK_SUBTRACT, "-");
1981 // VK_DECIMAL is generated by the . key on the keypad *when
1982 // NumLock is on* and *Shift is up* and the sequence is not
1983 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1984 // Windows Security screen to come up).
1985 case VK_DECIMAL:
1986 // U.S. English uses '.', Germany German uses ','.
1987 seqbuflen = _get_non_control_char(seqbuf, key_event,
1988 control_key_state);
1989 break;
1990
1991 MATCH_MODIFIER(VK_F1, SS3 "P");
1992 MATCH_MODIFIER(VK_F2, SS3 "Q");
1993 MATCH_MODIFIER(VK_F3, SS3 "R");
1994 MATCH_MODIFIER(VK_F4, SS3 "S");
1995 MATCH_MODIFIER(VK_F5, CSI "15~");
1996 MATCH_MODIFIER(VK_F6, CSI "17~");
1997 MATCH_MODIFIER(VK_F7, CSI "18~");
1998 MATCH_MODIFIER(VK_F8, CSI "19~");
1999 MATCH_MODIFIER(VK_F9, CSI "20~");
2000 MATCH_MODIFIER(VK_F10, CSI "21~");
2001 MATCH_MODIFIER(VK_F11, CSI "23~");
2002 MATCH_MODIFIER(VK_F12, CSI "24~");
2003
2004 MATCH_MODIFIER(VK_F13, CSI "25~");
2005 MATCH_MODIFIER(VK_F14, CSI "26~");
2006 MATCH_MODIFIER(VK_F15, CSI "28~");
2007 MATCH_MODIFIER(VK_F16, CSI "29~");
2008 MATCH_MODIFIER(VK_F17, CSI "31~");
2009 MATCH_MODIFIER(VK_F18, CSI "32~");
2010 MATCH_MODIFIER(VK_F19, CSI "33~");
2011 MATCH_MODIFIER(VK_F20, CSI "34~");
2012
2013 // MATCH_MODIFIER(VK_F21, ???);
2014 // MATCH_MODIFIER(VK_F22, ???);
2015 // MATCH_MODIFIER(VK_F23, ???);
2016 // MATCH_MODIFIER(VK_F24, ???);
2017 }
2018 }
2019
2020#undef MATCH
2021#undef MATCH_MODIFIER
2022#undef MATCH_KEYPAD
2023#undef MATCH_MODIFIER_KEYPAD
2024#undef ESC
2025#undef CSI
2026#undef SS3
2027
2028 const char* out;
2029 size_t outlen;
2030
2031 // Check for output in any of:
2032 // * seqstr is set (and strlen can be used to determine the length).
2033 // * seqbuf and seqbuflen are set
2034 // Fallback to ch from Windows.
2035 if (seqstr != NULL) {
2036 out = seqstr;
2037 outlen = strlen(seqstr);
2038 } else if (seqbuflen > 0) {
2039 out = seqbuf;
2040 outlen = seqbuflen;
2041 } else if (ch != '\0') {
2042 // Use whatever Windows told us it is.
2043 seqbuf[0] = ch;
2044 seqbuflen = 1;
2045 out = seqbuf;
2046 outlen = seqbuflen;
2047 } else {
2048 // No special handling for the virtual key code and Windows isn't
2049 // telling us a character code, then we don't know how to translate
2050 // the key press.
2051 //
2052 // Consume the input and 'continue' to cause us to get a new key
2053 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07002054 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08002055 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08002056 continue;
2057 }
2058
Spencer Low9c8f7462015-11-10 19:17:16 -08002059 // put output wRepeatCount times into g_console_input_buffer
2060 while (key_event->wRepeatCount-- > 0) {
2061 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08002062 }
2063
Spencer Low9c8f7462015-11-10 19:17:16 -08002064 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08002065 }
2066}
2067
2068static DWORD _old_console_mode; // previous GetConsoleMode() result
2069static HANDLE _console_handle; // when set, console mode should be restored
2070
Elliott Hughesa8265792015-11-03 11:18:40 -08002071void stdin_raw_init() {
2072 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08002073 if (in == nullptr) {
2074 return;
2075 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002076
Elliott Hughesa8265792015-11-03 11:18:40 -08002077 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2078 // calling the process Ctrl-C routine (configured by
2079 // SetConsoleCtrlHandler()).
2080 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2081 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2082 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08002083 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2084 ENABLE_LINE_INPUT |
2085 ENABLE_ECHO_INPUT);
2086 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2087 new_console_mode |= ENABLE_WINDOW_INPUT;
2088
2089 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002090 // This really should not fail.
2091 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002092 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002093 }
Elliott Hughesa8265792015-11-03 11:18:40 -08002094
2095 // Once this is set, it means that stdin has been configured for
2096 // reading from and that the old console mode should be restored later.
2097 _console_handle = in;
2098
2099 // Note that we don't need to configure C Runtime line-ending
2100 // translation because _console_read() does not call the C Runtime to
2101 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002102}
2103
Elliott Hughesa8265792015-11-03 11:18:40 -08002104void stdin_raw_restore() {
2105 if (_console_handle != NULL) {
2106 const HANDLE in = _console_handle;
2107 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002108
Elliott Hughesa8265792015-11-03 11:18:40 -08002109 if (!SetConsoleMode(in, _old_console_mode)) {
2110 // This really should not fail.
2111 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002112 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002113 }
2114 }
2115}
2116
Spencer Low55441402015-11-07 17:34:39 -08002117// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2118int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002119 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2120 // If it is a request to read from stdin, and stdin_raw_init() has been
2121 // called, and it successfully configured the console, then read from
2122 // the console using Win32 console APIs and partially emulate a unix
2123 // terminal.
2124 return _console_read(_console_handle, buf, len);
2125 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002126 // On older versions of Windows (definitely 7, definitely not 10),
2127 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002128 // we need to limit the read size.
2129 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002130 len = 4096;
2131 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002132 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002133 // can do LF/CR translation (which is overridable with _setmode()).
2134 // Undefine the macro that is set in sysdeps.h which bans calls to
2135 // plain read() in favor of unix_read() or adb_read().
2136#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002137#undef read
2138 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002139#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002140 }
2141}
Spencer Low6815c072015-05-11 01:08:48 -07002142
2143/**************************************************************************/
2144/**************************************************************************/
2145/***** *****/
2146/***** Unicode support *****/
2147/***** *****/
2148/**************************************************************************/
2149/**************************************************************************/
2150
2151// This implements support for using files with Unicode filenames and for
2152// outputting Unicode text to a Win32 console window. This is inspired from
2153// http://utf8everywhere.org/.
2154//
2155// Background
2156// ----------
2157//
2158// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2159// filenames to APIs such as open(). This works because filenames are largely
2160// opaque 'cookies' (perhaps excluding path separators).
2161//
2162// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2163// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2164// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2165// CreateFile() API is really just a macro that adds the W/A based on whether
2166// the UNICODE preprocessor symbol is defined).
2167//
2168// Options
2169// -------
2170//
2171// Thus, to write a portable program, there are a few options:
2172//
2173// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2174// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2175// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2176// open() API.
2177//
2178// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2179// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2180// potentially touching a lot of code.
2181//
2182// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2183// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2184// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2185// or C Runtime API.
2186//
2187// The Choice
2188// ----------
2189//
Spencer Low50f5bf12015-11-12 15:20:15 -08002190// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2191// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002192// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002193// args that are passed to main() at the beginning of program startup. We also use
2194// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002195// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2196//
2197// Unicode console output
2198// ----------------------
2199//
2200// The way to output Unicode to a Win32 console window is to call
2201// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002202// such as Lucida Console or Consolas, and in the case of East Asian languages
2203// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2204// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2205// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002206//
2207// The problem is getting the C Runtime to make fprintf and related APIs call
2208// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2209// promising, but the various modes have issues:
2210//
2211// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2212// UTF-16 do not display properly.
2213// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2214// totally wrong.
2215// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2216// handler to be called (upon a later I/O call), aborting the process.
2217// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2218// to output nothing.
2219//
2220// So the only solution is to write our own adb_fprintf() that converts UTF-8
2221// to UTF-16 and then calls WriteConsoleW().
2222
2223
Spencer Low6815c072015-05-11 01:08:48 -07002224// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2225// be passed to main().
2226NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2227 narrow_args = new char*[argc + 1];
2228
2229 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002230 std::string arg_narrow;
2231 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2232 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2233 }
2234 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002235 }
2236 narrow_args[argc] = nullptr; // terminate
2237}
2238
2239NarrowArgs::~NarrowArgs() {
2240 if (narrow_args != nullptr) {
2241 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2242 free(*argp);
2243 }
2244 delete[] narrow_args;
2245 narrow_args = nullptr;
2246 }
2247}
2248
2249int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002250 std::wstring path_wide;
2251 if (!android::base::UTF8ToWide(path, &path_wide)) {
2252 return -1;
2253 }
Spencer Low6815c072015-05-11 01:08:48 -07002254 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002255 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002256 } else {
2257 int mode;
2258 va_list args;
2259 va_start(args, options);
2260 mode = va_arg(args, int);
2261 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002262 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002263 }
2264}
2265
Spencer Low6815c072015-05-11 01:08:48 -07002266// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002267DIR* adb_opendir(const char* path) {
2268 std::wstring path_wide;
2269 if (!android::base::UTF8ToWide(path, &path_wide)) {
2270 return nullptr;
2271 }
2272
Spencer Low6815c072015-05-11 01:08:48 -07002273 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2274 // the fields, but right now all the callers treat the structure as
2275 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002276 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002277}
2278
2279// Version of readdir() that returns UTF-8 paths.
2280struct dirent* adb_readdir(DIR* dir) {
2281 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2282 struct _wdirent* const went = _wreaddir(wdir);
2283 if (went == nullptr) {
2284 return nullptr;
2285 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002286
Spencer Low6815c072015-05-11 01:08:48 -07002287 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002288 std::string name_utf8;
2289 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2290 return nullptr;
2291 }
Spencer Low6815c072015-05-11 01:08:48 -07002292
2293 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2294 // space for UTF-16 wchar_t's) with UTF-8 char's.
2295 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2296
2297 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2298 // Name too big to fit in existing buffer.
2299 errno = ENOMEM;
2300 return nullptr;
2301 }
2302
2303 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2304 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2305 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2306 // bigger than the caller expects because they expect a dirent structure
2307 // which has a smaller d_name field. Ignore this since the caller should be
2308 // resilient.
2309
2310 // Rewrite the UTF-16 d_name field to UTF-8.
2311 strcpy(ent->d_name, name_utf8.c_str());
2312
2313 return ent;
2314}
2315
2316// Version of closedir() to go with our version of adb_opendir().
2317int adb_closedir(DIR* dir) {
2318 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2319}
2320
2321// Version of unlink() that takes a UTF-8 path.
2322int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002323 std::wstring wpath;
2324 if (!android::base::UTF8ToWide(path, &wpath)) {
2325 return -1;
2326 }
Spencer Low6815c072015-05-11 01:08:48 -07002327
2328 int rc = _wunlink(wpath.c_str());
2329
2330 if (rc == -1 && errno == EACCES) {
2331 /* unlink returns EACCES when the file is read-only, so we first */
2332 /* try to make it writable, then unlink again... */
2333 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2334 if (rc == 0)
2335 rc = _wunlink(wpath.c_str());
2336 }
2337 return rc;
2338}
2339
2340// Version of mkdir() that takes a UTF-8 path.
2341int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002342 std::wstring path_wide;
2343 if (!android::base::UTF8ToWide(path, &path_wide)) {
2344 return -1;
2345 }
2346
2347 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002348}
2349
2350// Version of utime() that takes a UTF-8 path.
2351int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002352 std::wstring path_wide;
2353 if (!android::base::UTF8ToWide(path, &path_wide)) {
2354 return -1;
2355 }
2356
Spencer Low6815c072015-05-11 01:08:48 -07002357 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2358 "utimbuf and _utimbuf should be the same size because they both "
2359 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002360 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002361}
2362
2363// Version of chmod() that takes a UTF-8 path.
2364int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002365 std::wstring path_wide;
2366 if (!android::base::UTF8ToWide(path, &path_wide)) {
2367 return -1;
2368 }
2369
2370 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002371}
2372
Spencer Lowf373c352015-11-15 16:29:36 -08002373// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2374static inline size_t utf8_codepoint_len(uint8_t ch) {
2375 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2376}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002377
Spencer Lowf373c352015-11-15 16:29:36 -08002378namespace internal {
2379
2380// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2381// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2382// remaining_bytes.
2383size_t ParseCompleteUTF8(const char* const first, const char* const last,
2384 std::vector<char>* const remaining_bytes) {
2385 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2386 // Current_after points one byte past the current byte to be examined.
2387 for (const char* current_after = last; current_after != first; --current_after) {
2388 const char* const current = current_after - 1;
2389 const char ch = *current;
2390 const char kHighBit = 0x80u;
2391 const char kTwoHighestBits = 0xC0u;
2392 if ((ch & kHighBit) == 0) { // high bit not set
2393 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2394 // bytes with no leading byte, so return the entire buffer.
2395 break;
2396 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2397 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2398 const size_t bytes_available = last - current;
2399 if (bytes_available < utf8_codepoint_len(ch)) {
2400 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2401 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2402 // to remaining_bytes.
2403 remaining_bytes->insert(remaining_bytes->end(), current, last);
2404 return current - first;
2405 } else {
2406 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2407 // trailing bytes with no lead byte, so return the entire buffer.
2408 break;
2409 }
2410 } else {
2411 // Trailing byte, so keep going backwards looking for the lead byte.
2412 }
2413 }
2414
2415 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2416 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2417 // so that they can be processed.
2418 return last - first;
2419}
2420
2421}
2422
2423// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2424// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2425// This matches the behavior of Linux.
Spencer Lowf373c352015-11-15 16:29:36 -08002426
2427// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2428static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2429 HANDLE console) {
Josh Gaoe7daf572016-09-21 12:37:10 -07002430 static std::mutex& console_output_buffer_lock = *new std::mutex();
2431 static auto& console_output_buffer = *new std::vector<char>();
2432
Spencer Lowf373c352015-11-15 16:29:36 -08002433 const int saved_errno = errno;
2434 std::vector<char> combined_buffer;
2435
2436 // Complete UTF-8 sequences that should be immediately written to the console.
2437 const char* utf8;
2438 size_t utf8_size;
2439
Josh Gaoe7daf572016-09-21 12:37:10 -07002440 {
2441 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2442 if (console_output_buffer.empty()) {
2443 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2444 // common case with plain ASCII), parse buf directly.
2445 utf8 = buf;
2446 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2447 } else {
2448 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2449 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2450 // combined_buffer, then parse it all together.
2451 combined_buffer.swap(console_output_buffer);
2452 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowf373c352015-11-15 16:29:36 -08002453
Josh Gaoe7daf572016-09-21 12:37:10 -07002454 utf8 = combined_buffer.data();
2455 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2456 &console_output_buffer);
2457 }
Spencer Lowf373c352015-11-15 16:29:36 -08002458 }
Spencer Lowf373c352015-11-15 16:29:36 -08002459
2460 std::wstring utf16;
2461
2462 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2463 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2464 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002465 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002466 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002467
2468 // Note that this does not do \n => \r\n translation because that
2469 // doesn't seem necessary for the Windows console. For the Windows
2470 // console \r moves to the beginning of the line and \n moves to a new
2471 // line.
2472
2473 // Flush any stream buffering so that our output is afterwards which
2474 // makes sense because our call is afterwards.
2475 (void)fflush(stream);
2476
2477 // Write UTF-16 to the console.
2478 DWORD written = 0;
Spencer Lowf373c352015-11-15 16:29:36 -08002479 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Low6815c072015-05-11 01:08:48 -07002480 errno = EIO;
2481 return -1;
2482 }
2483
Spencer Lowf373c352015-11-15 16:29:36 -08002484 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2485 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2486 // matches the Linux behavior.
2487 errno = saved_errno;
2488 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002489}
2490
2491// Function prototype because attributes cannot be placed on func definitions.
2492static int _console_vfprintf(const HANDLE console, FILE* stream,
2493 const char *format, va_list ap)
2494 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2495
2496// Internal function to format a UTF-8 string and write it to a Win32 console.
2497// Returns -1 on error.
2498static int _console_vfprintf(const HANDLE console, FILE* stream,
2499 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002500 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002501 std::string output_utf8;
2502
2503 // Format the string.
2504 // This could throw std::bad_alloc.
2505 android::base::StringAppendV(&output_utf8, format, ap);
2506
Spencer Lowf373c352015-11-15 16:29:36 -08002507 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2508 console);
2509 if (result != -1) {
2510 errno = saved_errno;
2511 } else {
2512 // If -1 was returned, errno has been set.
2513 }
2514 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002515}
2516
2517// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2518// Windows console.
2519int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2520 const HANDLE console = _get_console_handle(stream);
2521
2522 // If there is an associated Win32 console, write to it specially,
2523 // otherwise defer to the regular C Runtime, passing it UTF-8.
2524 if (console != NULL) {
2525 return _console_vfprintf(console, stream, format, ap);
2526 } else {
2527 // If vfprintf is a macro, undefine it, so we can call the real
2528 // C Runtime API.
2529#pragma push_macro("vfprintf")
2530#undef vfprintf
2531 return vfprintf(stream, format, ap);
2532#pragma pop_macro("vfprintf")
2533 }
2534}
2535
Spencer Lowf373c352015-11-15 16:29:36 -08002536// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2537int adb_vprintf(const char *format, va_list ap) {
2538 return adb_vfprintf(stdout, format, ap);
2539}
2540
Spencer Low6815c072015-05-11 01:08:48 -07002541// Version of fprintf() that takes UTF-8 and can write Unicode to a
2542// Windows console.
2543int adb_fprintf(FILE *stream, const char *format, ...) {
2544 va_list ap;
2545 va_start(ap, format);
2546 const int result = adb_vfprintf(stream, format, ap);
2547 va_end(ap);
2548
2549 return result;
2550}
2551
2552// Version of printf() that takes UTF-8 and can write Unicode to a
2553// Windows console.
2554int adb_printf(const char *format, ...) {
2555 va_list ap;
2556 va_start(ap, format);
2557 const int result = adb_vfprintf(stdout, format, ap);
2558 va_end(ap);
2559
2560 return result;
2561}
2562
2563// Version of fputs() that takes UTF-8 and can write Unicode to a
2564// Windows console.
2565int adb_fputs(const char* buf, FILE* stream) {
2566 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2567 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002568 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002569 return adb_fprintf(stream, "%s", buf);
2570}
2571
2572// Version of fputc() that takes UTF-8 and can write Unicode to a
2573// Windows console.
2574int adb_fputc(int ch, FILE* stream) {
2575 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002576 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002577 return EOF;
2578 }
2579 // For success, fputc returns the char, cast to unsigned char, then to int.
2580 return static_cast<unsigned char>(ch);
2581}
2582
Spencer Lowf373c352015-11-15 16:29:36 -08002583// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2584int adb_putchar(int ch) {
2585 return adb_fputc(ch, stdout);
2586}
2587
2588// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2589int adb_puts(const char* buf) {
2590 // adb_printf returns -1 on error, which is conveniently the same as EOF
2591 // which puts (and hence adb_puts) should return on error.
2592 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2593 return adb_printf("%s\n", buf);
2594}
2595
Spencer Low6815c072015-05-11 01:08:48 -07002596// Internal function to write UTF-8 to a Win32 console. Returns the number of
2597// items (of length size) written. On error, returns a short item count or 0.
2598static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2599 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002600 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2601 console);
Spencer Low6815c072015-05-11 01:08:48 -07002602 if (result == -1) {
2603 return 0;
2604 }
2605 return result / size;
2606}
2607
2608// Version of fwrite() that takes UTF-8 and can write Unicode to a
2609// Windows console.
2610size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2611 const HANDLE console = _get_console_handle(stream);
2612
2613 // If there is an associated Win32 console, write to it specially,
2614 // otherwise defer to the regular C Runtime, passing it UTF-8.
2615 if (console != NULL) {
2616 return _console_fwrite(ptr, size, nmemb, stream, console);
2617 } else {
2618 // If fwrite is a macro, undefine it, so we can call the real
2619 // C Runtime API.
2620#pragma push_macro("fwrite")
2621#undef fwrite
2622 return fwrite(ptr, size, nmemb, stream);
2623#pragma pop_macro("fwrite")
2624 }
2625}
2626
2627// Version of fopen() that takes a UTF-8 filename and can access a file with
2628// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002629FILE* adb_fopen(const char* path, const char* mode) {
2630 std::wstring path_wide;
2631 if (!android::base::UTF8ToWide(path, &path_wide)) {
2632 return nullptr;
2633 }
2634
2635 std::wstring mode_wide;
2636 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2637 return nullptr;
2638 }
2639
2640 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002641}
2642
Spencer Low50740f52015-09-08 17:13:04 -07002643// Return a lowercase version of the argument. Uses C Runtime tolower() on
2644// each byte which is not UTF-8 aware, and theoretically uses the current C
2645// Runtime locale (which in practice is not changed, so this becomes a ASCII
2646// conversion).
2647static std::string ToLower(const std::string& anycase) {
2648 // copy string
2649 std::string str(anycase);
2650 // transform the copy
2651 std::transform(str.begin(), str.end(), str.begin(), tolower);
2652 return str;
2653}
2654
2655extern "C" int main(int argc, char** argv);
2656
2657// Link with -municode to cause this wmain() to be used as the program
2658// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2659// regular main() with UTF-8 args.
2660extern "C" int wmain(int argc, wchar_t **argv) {
2661 // Convert args from UTF-16 to UTF-8 and pass that to main().
2662 NarrowArgs narrow_args(argc, argv);
2663 return main(argc, narrow_args.data());
2664}
2665
Spencer Low6815c072015-05-11 01:08:48 -07002666// Shadow UTF-8 environment variable name/value pairs that are created from
2667// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07002668// currently updated if putenv, setenv, unsetenv are called. Note that no
2669// thread synchronization is done, but we're called early enough in
2670// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002671static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002672
2673// Make sure that shadow UTF-8 environment variables are setup.
2674static void _ensure_env_setup() {
2675 // If some name/value pairs exist, then we've already done the setup below.
2676 if (g_environ_utf8.size() != 0) {
2677 return;
2678 }
2679
Spencer Low50740f52015-09-08 17:13:04 -07002680 if (_wenviron == nullptr) {
2681 // If _wenviron is null, then -municode probably wasn't used. That
2682 // linker flag will cause the entry point to setup _wenviron. It will
2683 // also require an implementation of wmain() (which we provide above).
2684 fatal("_wenviron is not set, did you link with -municode?");
2685 }
2686
Spencer Low6815c072015-05-11 01:08:48 -07002687 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2688 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2689 // to use the D() macro here because that tracing only works if the
2690 // ADB_TRACE environment variable is setup, but that env var can't be read
2691 // until this code completes.
2692 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2693 wchar_t* const equal = wcschr(*env, L'=');
2694 if (equal == nullptr) {
2695 // Malformed environment variable with no equal sign. Shouldn't
2696 // really happen, but we should be resilient to this.
2697 continue;
2698 }
2699
Spencer Low50f5bf12015-11-12 15:20:15 -08002700 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2701 // var because the program might never even read this particular variable.
2702 std::string name_utf8;
2703 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2704 continue;
2705 }
2706
Spencer Low50740f52015-09-08 17:13:04 -07002707 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002708 name_utf8 = ToLower(name_utf8);
2709
2710 std::string value_utf8;
2711 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2712 continue;
2713 }
2714
2715 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002716
Spencer Low50740f52015-09-08 17:13:04 -07002717 // Don't overwrite a previus env var with the same name. In reality,
2718 // the system probably won't let two env vars with the same name exist
2719 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002720 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002721 }
2722}
2723
2724// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002725// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002726char* adb_getenv(const char* name) {
2727 _ensure_env_setup();
2728
Spencer Low50740f52015-09-08 17:13:04 -07002729 // Case-insensitive search by searching for lowercase name in a map of
2730 // lowercase names.
2731 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002732 if (it == g_environ_utf8.end()) {
2733 return nullptr;
2734 }
2735
2736 return it->second;
2737}
2738
2739// Version of getcwd() that returns the current working directory in UTF-8.
2740char* adb_getcwd(char* buf, int size) {
2741 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2742 if (wbuf == nullptr) {
2743 return nullptr;
2744 }
2745
Spencer Low50f5bf12015-11-12 15:20:15 -08002746 std::string buf_utf8;
2747 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002748 free(wbuf);
2749 wbuf = nullptr;
2750
Spencer Low50f5bf12015-11-12 15:20:15 -08002751 if (!narrow_result) {
2752 return nullptr;
2753 }
2754
Spencer Low6815c072015-05-11 01:08:48 -07002755 // If size was specified, make sure all the chars will fit.
2756 if (size != 0) {
2757 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2758 errno = ERANGE;
2759 return nullptr;
2760 }
2761 }
2762
2763 // If buf was not specified, allocate storage.
2764 if (buf == nullptr) {
2765 if (size == 0) {
2766 size = buf_utf8.length() + 1;
2767 }
2768 buf = reinterpret_cast<char*>(malloc(size));
2769 if (buf == nullptr) {
2770 return nullptr;
2771 }
2772 }
2773
2774 // Destination buffer was allocated with enough space, or we've already
2775 // checked an existing buffer size for enough space.
2776 strcpy(buf, buf_utf8.c_str());
2777
2778 return buf;
2779}