blob: a4b5e6978c89301e952f08db4fb2075ae7e81088 [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
480/**************************************************************************/
481/**************************************************************************/
482/***** *****/
483/***** socket-based file descriptors *****/
484/***** *****/
485/**************************************************************************/
486/**************************************************************************/
487
Spencer Low31aafa62015-01-25 14:40:16 -0800488#undef setsockopt
489
Spencer Low753d4852015-07-30 23:07:55 -0700490static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700491 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
492 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gao75e96bb2016-12-05 13:24:48 -0800493 // are mapped to strings by adb_strerror().
Spencer Low753d4852015-07-30 23:07:55 -0700494 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800495 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700496 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
497 // case WSAEINTR: errno = EINTR; break;
498 case WSAEFAULT: errno = EFAULT; break;
499 case WSAEINVAL: errno = EINVAL; break;
500 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700501 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
502 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
503 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800504 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700505 case WSAENOTSOCK: errno = ENOTSOCK; break;
506 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
507 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
508 case WSAENETDOWN: errno = ENETDOWN; break;
509 case WSAENETRESET: errno = ENETRESET; break;
510 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
511 // to use EPIPE for these situations and there are some callers that look
512 // for EPIPE.
513 case WSAECONNABORTED: errno = EPIPE; break;
514 case WSAECONNRESET: errno = ECONNRESET; break;
515 case WSAENOBUFS: errno = ENOBUFS; break;
516 case WSAENOTCONN: errno = ENOTCONN; break;
517 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
518 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
519 // considerations: Reportedly send() can return zero on timeout, and POSIX
520 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
521 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
522 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800523 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800524 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700525 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700526 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800527 }
528}
529
Josh Gaoe7388122016-02-16 17:34:53 -0800530extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
531 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
532 int skipped = 0;
533 std::vector<WSAPOLLFD> sockets;
534 std::vector<adb_pollfd*> original;
535 for (size_t i = 0; i < nfds; ++i) {
536 FH fh = _fh_from_int(fds[i].fd, __func__);
537 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
538 D("adb_poll received bad FD %d", fds[i].fd);
539 fds[i].revents = POLLNVAL;
540 ++skipped;
541 } else {
542 WSAPOLLFD wsapollfd = {
543 .fd = fh->u.socket,
544 .events = static_cast<short>(fds[i].events)
545 };
546 sockets.push_back(wsapollfd);
547 original.push_back(&fds[i]);
548 }
Spencer Low753d4852015-07-30 23:07:55 -0700549 }
Josh Gaoe7388122016-02-16 17:34:53 -0800550
551 if (sockets.empty()) {
552 return skipped;
553 }
554
555 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
556 if (result == SOCKET_ERROR) {
557 _socket_set_errno(WSAGetLastError());
558 return -1;
559 }
560
561 // Map the results back onto the original set.
562 for (size_t i = 0; i < sockets.size(); ++i) {
563 original[i]->revents = sockets[i].revents;
564 }
565
566 // WSAPoll appears to return the number of unique FDs with avaiable events, instead of how many
567 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
568 // to do. Ignore its result and calculate the proper return value.
569 result = 0;
570 for (size_t i = 0; i < nfds; ++i) {
571 if (fds[i].revents != 0) {
572 ++result;
573 }
574 }
575 return result;
576}
577
578static void _fh_socket_init(FH f) {
579 f->fh_socket = INVALID_SOCKET;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800580 f->mask = 0;
581}
582
Elliott Hughes6a096932015-04-16 16:47:02 -0700583static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700584 if (f->fh_socket != INVALID_SOCKET) {
585 /* gently tell any peer that we're closing the socket */
586 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
587 // If the socket is not connected, this returns an error. We want to
588 // minimize logging spam, so don't log these errors for now.
589#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700590 D("socket shutdown failed: %s",
David Pursellc573d522016-01-27 08:52:53 -0800591 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700592#endif
593 }
594 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800595 // Don't set errno here, since adb_close will ignore it.
596 const DWORD err = WSAGetLastError();
597 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700598 }
599 f->fh_socket = INVALID_SOCKET;
600 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800601 f->mask = 0;
602 return 0;
603}
604
Elliott Hughes6a096932015-04-16 16:47:02 -0700605static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800606 errno = EPIPE;
607 return -1;
608}
609
Elliott Hughes6a096932015-04-16 16:47:02 -0700610static int _fh_socket_read(FH f, void* buf, int len) {
611 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800612 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700613 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700614 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
615 // that to reduce spam and confusion.
616 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700617 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800618 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low32625852015-08-11 16:45:32 -0700619 }
Spencer Low753d4852015-07-30 23:07:55 -0700620 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800621 result = -1;
622 }
623 return result;
624}
625
Elliott Hughes6a096932015-04-16 16:47:02 -0700626static int _fh_socket_write(FH f, const void* buf, int len) {
627 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800628 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700629 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700630 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
631 // that to reduce spam and confusion.
632 if (err != WSAEWOULDBLOCK) {
633 D("send fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800634 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low028e1592015-10-18 16:45:09 -0700635 }
Spencer Low753d4852015-07-30 23:07:55 -0700636 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800637 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700638 } else {
639 // According to https://code.google.com/p/chromium/issues/detail?id=27870
640 // Winsock Layered Service Providers may cause this.
641 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
642 << f->name << ", but " << result
643 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800644 }
645 return result;
646}
647
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800648/**************************************************************************/
649/**************************************************************************/
650/***** *****/
651/***** replacement for libs/cutils/socket_xxxx.c *****/
652/***** *****/
653/**************************************************************************/
654/**************************************************************************/
655
656#include <winsock2.h>
657
658static int _winsock_init;
659
660static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800661_init_winsock( void )
662{
Spencer Low753d4852015-07-30 23:07:55 -0700663 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700664 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800665 if (!_winsock_init) {
666 WSADATA wsaData;
667 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
668 if (rc != 0) {
David Pursellc573d522016-01-27 08:52:53 -0800669 fatal("adb: could not initialize Winsock: %s",
670 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800671 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800672 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700673
674 // Note that we do not call atexit() to register WSACleanup to be called
675 // at normal process termination because:
676 // 1) When exit() is called, there are still threads actively using
677 // Winsock because we don't cleanly shutdown all threads, so it
678 // doesn't make sense to call WSACleanup() and may cause problems
679 // with those threads.
680 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
681 // calls WSACleanup() which tries to unload a DLL, which tries to
682 // grab the LoaderLock. This conflicts with the device_poll_thread
683 // which holds the LoaderLock because AdbWinApi.dll calls
684 // setupapi.dll which tries to load wintrust.dll which tries to load
685 // crypt32.dll which calls atexit() which tries to acquire the C
686 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800687 }
688}
689
Spencer Lowc7c45612015-09-29 15:05:29 -0700690// Map a socket type to an explicit socket protocol instead of using the socket
691// protocol of 0. Explicit socket protocols are used by most apps and we should
692// do the same to reduce the chance of exercising uncommon code-paths that might
693// have problems or that might load different Winsock service providers that
694// have problems.
695static int GetSocketProtocolFromSocketType(int type) {
696 switch (type) {
697 case SOCK_STREAM:
698 return IPPROTO_TCP;
699 case SOCK_DGRAM:
700 return IPPROTO_UDP;
701 default:
702 LOG(FATAL) << "Unknown socket type: " << type;
703 return 0;
704 }
705}
706
Spencer Low753d4852015-07-30 23:07:55 -0700707int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800708 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800709 SOCKET s;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800710
Josh Gao61eda8d2016-02-18 13:43:55 -0800711 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low753d4852015-07-30 23:07:55 -0700712 if (!f) {
713 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800714 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700715 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800716
Josh Gao61eda8d2016-02-18 13:43:55 -0800717 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800718
719 memset(&addr, 0, sizeof(addr));
720 addr.sin_family = AF_INET;
721 addr.sin_port = htons(port);
722 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
723
Spencer Lowc7c45612015-09-29 15:05:29 -0700724 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao61eda8d2016-02-18 13:43:55 -0800725 if (s == INVALID_SOCKET) {
726 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700727 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800728 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700729 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800730 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700731 return -1;
732 }
733 f->fh_socket = s;
734
Josh Gao61eda8d2016-02-18 13:43:55 -0800735 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700736 // Save err just in case inet_ntoa() or ntohs() changes the last error.
737 const DWORD err = WSAGetLastError();
738 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800739 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
740 android::base::SystemErrorCodeToString(err).c_str());
741 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
742 error->c_str());
743 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800744 return -1;
745 }
746
Spencer Low753d4852015-07-30 23:07:55 -0700747 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800748 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
749 port);
750 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700751 f.release();
752 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800753}
754
755#define LISTEN_BACKLOG 4
756
Spencer Low753d4852015-07-30 23:07:55 -0700757// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao61eda8d2016-02-18 13:43:55 -0800758static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800759 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800760 SOCKET s;
761 int n;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800762
Josh Gao61eda8d2016-02-18 13:43:55 -0800763 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800764 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700765 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800766 return -1;
767 }
768
Josh Gao61eda8d2016-02-18 13:43:55 -0800769 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800770
771 memset(&addr, 0, sizeof(addr));
772 addr.sin_family = AF_INET;
773 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700774 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800775
Spencer Low753d4852015-07-30 23:07:55 -0700776 // TODO: Consider using dual-stack socket that can simultaneously listen on
777 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700778 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700779 if (s == INVALID_SOCKET) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800780 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700781 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800782 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700783 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800784 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700785 return -1;
786 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800787
788 f->fh_socket = s;
789
Spencer Low32625852015-08-11 16:45:32 -0700790 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
791 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800792 n = 1;
Josh Gao61eda8d2016-02-18 13:43:55 -0800793 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
794 const DWORD err = WSAGetLastError();
795 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
796 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700797 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800798 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700799 return -1;
800 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800801
Josh Gao61eda8d2016-02-18 13:43:55 -0800802 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700803 // Save err just in case inet_ntoa() or ntohs() changes the last error.
804 const DWORD err = WSAGetLastError();
Josh Gao61eda8d2016-02-18 13:43:55 -0800805 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
806 ntohs(addr.sin_port),
807 android::base::SystemErrorCodeToString(err).c_str());
808 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
809 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800810 return -1;
811 }
812 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700813 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800814 const DWORD err = WSAGetLastError();
815 *error = android::base::StringPrintf(
816 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
817 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
818 error->c_str());
819 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800820 return -1;
821 }
822 }
Spencer Low753d4852015-07-30 23:07:55 -0700823 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800824 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
825 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
826 port);
827 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700828 f.release();
829 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800830}
831
Spencer Low753d4852015-07-30 23:07:55 -0700832int network_loopback_server(int port, int type, std::string* error) {
833 return _network_server(port, type, INADDR_LOOPBACK, error);
834}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800835
Spencer Low753d4852015-07-30 23:07:55 -0700836int network_inaddr_any_server(int port, int type, std::string* error) {
837 return _network_server(port, type, INADDR_ANY, error);
838}
839
840int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
841 unique_fh f(_fh_alloc(&_fh_socket_class));
842 if (!f) {
843 *error = strerror(errno);
844 return -1;
845 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800846
Elliott Hughes43df1092015-07-23 17:12:58 -0700847 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800848
Spencer Low753d4852015-07-30 23:07:55 -0700849 struct addrinfo hints;
850 memset(&hints, 0, sizeof(hints));
851 hints.ai_family = AF_UNSPEC;
852 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700853 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700854
855 char port_str[16];
856 snprintf(port_str, sizeof(port_str), "%d", port);
857
858 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700859
860#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao61eda8d2016-02-18 13:43:55 -0800861// TODO: When the Android SDK tools increases the Windows system
862// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700863#else
Josh Gao61eda8d2016-02-18 13:43:55 -0800864// Otherwise, keep using getaddrinfo(), or do runtime API detection
865// with GetProcAddress("GetAddrInfoW").
Spencer Lowcc467f12015-08-02 18:13:54 -0700866#endif
Spencer Low753d4852015-07-30 23:07:55 -0700867 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800868 const DWORD err = WSAGetLastError();
869 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
870 host.c_str(), port_str,
871 android::base::SystemErrorCodeToString(err).c_str());
872
Yabin Cui815ad882015-09-02 17:44:28 -0700873 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800874 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800875 return -1;
876 }
Elliott Hughes8ac45992016-08-08 12:52:37 -0700877 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low753d4852015-07-30 23:07:55 -0700878 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800879
Spencer Low753d4852015-07-30 23:07:55 -0700880 // TODO: Try all the addresses if there's more than one? This just uses
881 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
882 // which tries all addresses, takes a timeout and more.
Josh Gao61eda8d2016-02-18 13:43:55 -0800883 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
884 if (s == INVALID_SOCKET) {
885 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700886 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800887 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700888 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800889 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800890 return -1;
891 }
892 f->fh_socket = s;
893
Spencer Low753d4852015-07-30 23:07:55 -0700894 // TODO: Implement timeouts for Windows. Seems like the default in theory
895 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao61eda8d2016-02-18 13:43:55 -0800896 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700897 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao61eda8d2016-02-18 13:43:55 -0800898 const DWORD err = WSAGetLastError();
899 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
900 android::base::SystemErrorCodeToString(err).c_str());
901 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
902 port_str, error->c_str());
903 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800904 return -1;
905 }
906
Spencer Low753d4852015-07-30 23:07:55 -0700907 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800908 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
909 port);
910 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
911 fd);
Spencer Low753d4852015-07-30 23:07:55 -0700912 f.release();
913 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800914}
915
916#undef accept
917int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
918{
Spencer Low3a2421b2015-05-22 20:09:06 -0700919 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200920
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800921 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700922 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -0700923 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800924 return -1;
925 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200926
Spencer Low753d4852015-07-30 23:07:55 -0700927 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800928 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700929 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
930 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800931 return -1;
932 }
933
934 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
935 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700936 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700937 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursellc573d522016-01-27 08:52:53 -0800938 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low753d4852015-07-30 23:07:55 -0700939 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800940 return -1;
941 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200942
Spencer Low753d4852015-07-30 23:07:55 -0700943 const int fd = _fh_to_int(fh.get());
944 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -0700945 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -0700946 fh.release();
947 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800948}
949
950
Spencer Low31aafa62015-01-25 14:40:16 -0800951int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800952{
Spencer Low3a2421b2015-05-22 20:09:06 -0700953 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200954
Spencer Low31aafa62015-01-25 14:40:16 -0800955 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700956 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700957 errno = EBADF;
958 return -1;
959 }
Spencer Lowc7c45612015-09-29 15:05:29 -0700960
961 // TODO: Once we can assume Windows Vista or later, if the caller is trying
962 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
963 // auto-tuning.
964
Spencer Low753d4852015-07-30 23:07:55 -0700965 int result = setsockopt( fh->fh_socket, level, optname,
966 reinterpret_cast<const char*>(optval), optlen );
967 if ( result == SOCKET_ERROR ) {
968 const DWORD err = WSAGetLastError();
David Pursellc573d522016-01-27 08:52:53 -0800969 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
970 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700971 _socket_set_errno( err );
972 result = -1;
973 }
974 return result;
975}
976
Josh Gaoe7388122016-02-16 17:34:53 -0800977int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
978 FH fh = _fh_from_int(fd, __func__);
979
980 if (!fh || fh->clazz != &_fh_socket_class) {
981 D("adb_getsockname: invalid fd %d", fd);
982 errno = EBADF;
983 return -1;
984 }
985
Josh Gaod6001b52016-08-23 15:28:43 -0700986 int result = (getsockname)(fh->fh_socket, sockaddr, optlen);
Josh Gaoe7388122016-02-16 17:34:53 -0800987 if (result == SOCKET_ERROR) {
988 const DWORD err = WSAGetLastError();
989 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
990 android::base::SystemErrorCodeToString(err).c_str());
991 _socket_set_errno(err);
992 result = -1;
993 }
994 return result;
995}
Spencer Low753d4852015-07-30 23:07:55 -0700996
David Pursell19d0c232016-04-07 11:25:48 -0700997int adb_socket_get_local_port(int fd) {
998 sockaddr_storage addr_storage;
999 socklen_t addr_len = sizeof(addr_storage);
1000
1001 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1002 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1003 return -1;
1004 }
1005
1006 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1007 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1008 errno = ECONNABORTED;
1009 return -1;
1010 }
1011
1012 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1013}
1014
Spencer Low753d4852015-07-30 23:07:55 -07001015int adb_shutdown(int fd)
1016{
1017 FH f = _fh_from_int(fd, __func__);
1018
1019 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001020 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001021 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001022 return -1;
1023 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001024
Yabin Cui815ad882015-09-02 17:44:28 -07001025 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001026 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1027 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001028 D("socket shutdown fd %d failed: %s", fd,
David Pursellc573d522016-01-27 08:52:53 -08001029 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001030 _socket_set_errno(err);
1031 return -1;
1032 }
1033 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001034}
1035
Josh Gaoe7388122016-02-16 17:34:53 -08001036// Emulate socketpair(2) by binding and connecting to a socket.
1037int adb_socketpair(int sv[2]) {
1038 int server = -1;
1039 int client = -1;
1040 int accepted = -1;
David Pursell19d0c232016-04-07 11:25:48 -07001041 int local_port = -1;
Josh Gaoe7388122016-02-16 17:34:53 -08001042 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001043
Josh Gaod6001b52016-08-23 15:28:43 -07001044 struct sockaddr_storage peer_addr = {};
1045 struct sockaddr_storage client_addr = {};
1046 socklen_t peer_socklen = sizeof(peer_addr);
1047 socklen_t client_socklen = sizeof(client_addr);
1048
Josh Gaoe7388122016-02-16 17:34:53 -08001049 server = network_loopback_server(0, SOCK_STREAM, &error);
1050 if (server < 0) {
1051 D("adb_socketpair: failed to create server: %s", error.c_str());
1052 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001053 }
1054
David Pursell19d0c232016-04-07 11:25:48 -07001055 local_port = adb_socket_get_local_port(server);
1056 if (local_port < 0) {
1057 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gaoe7388122016-02-16 17:34:53 -08001058 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001059 }
David Pursell19d0c232016-04-07 11:25:48 -07001060 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001061
David Pursell19d0c232016-04-07 11:25:48 -07001062 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gaoe7388122016-02-16 17:34:53 -08001063 if (client < 0) {
1064 D("adb_socketpair: failed to connect client: %s", error.c_str());
1065 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001066 }
1067
Josh Gaod6001b52016-08-23 15:28:43 -07001068 // Make sure that the peer that connected to us and the client are the same.
1069 accepted = adb_socket_accept(server, reinterpret_cast<sockaddr*>(&peer_addr), &peer_socklen);
Josh Gaoe7388122016-02-16 17:34:53 -08001070 if (accepted < 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -08001071 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoe7388122016-02-16 17:34:53 -08001072 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001073 }
Josh Gaod6001b52016-08-23 15:28:43 -07001074
1075 if (adb_getsockname(client, reinterpret_cast<sockaddr*>(&client_addr), &client_socklen) != 0) {
1076 D("adb_socketpair: failed to getpeername: %s", strerror(errno));
1077 goto fail;
1078 }
1079
1080 if (peer_socklen != client_socklen) {
1081 D("adb_socketpair: client and peer sockaddrs have different lengths");
1082 errno = EIO;
1083 goto fail;
1084 }
1085
1086 if (memcmp(&peer_addr, &client_addr, peer_socklen) != 0) {
1087 D("adb_socketpair: client and peer sockaddrs don't match");
1088 errno = EIO;
1089 goto fail;
1090 }
1091
Josh Gaoe7388122016-02-16 17:34:53 -08001092 adb_close(server);
Josh Gaod6001b52016-08-23 15:28:43 -07001093
Josh Gaoe7388122016-02-16 17:34:53 -08001094 sv[0] = client;
1095 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001096 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001097
Josh Gaoe7388122016-02-16 17:34:53 -08001098fail:
1099 if (server >= 0) {
1100 adb_close(server);
1101 }
1102 if (client >= 0) {
1103 adb_close(client);
1104 }
1105 if (accepted >= 0) {
1106 adb_close(accepted);
1107 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001108 return -1;
1109}
1110
Josh Gaoe7388122016-02-16 17:34:53 -08001111bool set_file_block_mode(int fd, bool block) {
1112 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001113
Josh Gaoe7388122016-02-16 17:34:53 -08001114 if (!fh || !fh->used) {
1115 errno = EBADF;
1116 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001117 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001118
Josh Gaoe7388122016-02-16 17:34:53 -08001119 if (fh->clazz == &_fh_socket_class) {
1120 u_long x = !block;
1121 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
1122 _socket_set_errno(WSAGetLastError());
1123 return false;
1124 }
1125 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001126 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001127 errno = ENOTSOCK;
1128 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001129 }
1130}
1131
David Pursellc25a34e2016-02-22 14:27:23 -08001132bool set_tcp_keepalive(int fd, int interval_sec) {
1133 FH fh = _fh_from_int(fd, __func__);
1134
1135 if (!fh || fh->clazz != &_fh_socket_class) {
1136 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1137 errno = EBADF;
1138 return false;
1139 }
1140
1141 tcp_keepalive keepalive;
1142 keepalive.onoff = (interval_sec > 0);
1143 keepalive.keepalivetime = interval_sec * 1000;
1144 keepalive.keepaliveinterval = interval_sec * 1000;
1145
1146 DWORD bytes_returned = 0;
1147 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1148 &bytes_returned, nullptr, nullptr) != 0) {
1149 const DWORD err = WSAGetLastError();
1150 D("set_tcp_keepalive(%d) failed: %s", fd,
1151 android::base::SystemErrorCodeToString(err).c_str());
1152 _socket_set_errno(err);
1153 return false;
1154 }
1155
1156 return true;
1157}
1158
Spencer Lowbeb61982015-03-01 15:06:21 -08001159/**************************************************************************/
1160/**************************************************************************/
1161/***** *****/
1162/***** Console Window Terminal Emulation *****/
1163/***** *****/
1164/**************************************************************************/
1165/**************************************************************************/
1166
1167// This reads input from a Win32 console window and translates it into Unix
1168// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1169// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1170// is emulated instead of xterm because it is probably more popular than xterm:
1171// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1172// supports modern fonts, etc. It seems best to emulate the terminal that most
1173// Android developers use because they'll fix apps (the shell, etc.) to keep
1174// working with that terminal's emulation.
1175//
1176// The point of this emulation is not to be perfect or to solve all issues with
1177// console windows on Windows, but to be better than the original code which
1178// just called read() (which called ReadFile(), which called ReadConsoleA())
1179// which did not support Ctrl-C, tab completion, shell input line editing
1180// keys, server echo, and more.
1181//
1182// This implementation reconfigures the console with SetConsoleMode(), then
1183// calls ReadConsoleInput() to get raw input which it remaps to Unix
1184// terminal-style sequences which is returned via unix_read() which is used
1185// by the 'adb shell' command.
1186//
1187// Code organization:
1188//
David Pursell58805362015-10-28 14:29:51 -07001189// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001190// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1191// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1192// * _console_read() is the main code of the emulation.
1193
David Pursell58805362015-10-28 14:29:51 -07001194// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1195// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1196// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1197static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1198 // First check isatty(); this is very fast and eliminates most non-console
1199 // FDs, but returns 1 for both consoles and character devices like NUL.
1200#pragma push_macro("isatty")
1201#undef isatty
1202 if (!isatty(fd)) {
1203 return nullptr;
1204 }
1205#pragma pop_macro("isatty")
1206
1207 // To differentiate between character devices and consoles we need to get
1208 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1209 // GENERIC_READ permissions.
1210 const intptr_t intptr_handle = _get_osfhandle(fd);
1211 if (intptr_handle == -1) {
1212 return nullptr;
1213 }
1214 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1215 DWORD temp_mode = 0;
1216 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1217 return nullptr;
1218 }
1219
1220 return handle;
1221}
1222
1223// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1224static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001225 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1226 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001227 const int fd = fileno(stream);
1228 if (fd < 0) {
1229 return nullptr;
1230 }
1231 return _get_console_handle(fd);
1232}
1233
1234int unix_isatty(int fd) {
1235 return _get_console_handle(fd) ? 1 : 0;
1236}
Spencer Lowbeb61982015-03-01 15:06:21 -08001237
Spencer Low9c8f7462015-11-10 19:17:16 -08001238// Get the next KEY_EVENT_RECORD that should be processed.
1239static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001240 for (;;) {
1241 DWORD read_count = 0;
1242 memset(input_record, 0, sizeof(*input_record));
1243 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001244 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001245 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001246 errno = EIO;
1247 return false;
1248 }
1249
1250 if (read_count == 0) { // should be impossible
1251 fatal("ReadConsoleInputA returned 0");
1252 }
1253
1254 if (read_count != 1) { // should be impossible
1255 fatal("ReadConsoleInputA did not return one input record");
1256 }
1257
Spencer Low55441402015-11-07 17:34:39 -08001258 // If the console window is resized, emulate SIGWINCH by breaking out
1259 // of read() with errno == EINTR. Note that there is no event on
1260 // vertical resize because we don't give the console our own custom
1261 // screen buffer (with CreateConsoleScreenBuffer() +
1262 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1263 // supports scrollback, but doesn't seem to raise an event for vertical
1264 // window resize.
1265 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1266 errno = EINTR;
1267 return false;
1268 }
1269
Spencer Lowbeb61982015-03-01 15:06:21 -08001270 if ((input_record->EventType == KEY_EVENT) &&
1271 (input_record->Event.KeyEvent.bKeyDown)) {
1272 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1273 fatal("ReadConsoleInputA returned a key event with zero repeat"
1274 " count");
1275 }
1276
1277 // Got an interesting INPUT_RECORD, so return
1278 return true;
1279 }
1280 }
1281}
1282
Spencer Lowbeb61982015-03-01 15:06:21 -08001283static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1284 return (control_key_state & SHIFT_PRESSED) != 0;
1285}
1286
1287static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1288 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1289}
1290
1291static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1292 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1293}
1294
1295static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1296 return (control_key_state & NUMLOCK_ON) != 0;
1297}
1298
1299static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1300 return (control_key_state & CAPSLOCK_ON) != 0;
1301}
1302
1303static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1304 return (control_key_state & ENHANCED_KEY) != 0;
1305}
1306
1307// Constants from MSDN for ToAscii().
1308static const BYTE TOASCII_KEY_OFF = 0x00;
1309static const BYTE TOASCII_KEY_DOWN = 0x80;
1310static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1311
1312// Given a key event, ignore a modifier key and return the character that was
1313// entered without the modifier. Writes to *ch and returns the number of bytes
1314// written.
1315static size_t _get_char_ignoring_modifier(char* const ch,
1316 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1317 const WORD modifier) {
1318 // If there is no character from Windows, try ignoring the specified
1319 // modifier and look for a character. Note that if AltGr is being used,
1320 // there will be a character from Windows.
1321 if (key_event->uChar.AsciiChar == '\0') {
1322 // Note that we read the control key state from the passed in argument
1323 // instead of from key_event since the argument has been normalized.
1324 if (((modifier == VK_SHIFT) &&
1325 _is_shift_pressed(control_key_state)) ||
1326 ((modifier == VK_CONTROL) &&
1327 _is_ctrl_pressed(control_key_state)) ||
1328 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1329
1330 BYTE key_state[256] = {0};
1331 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1332 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1333 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1334 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1335 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1336 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1337 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1338 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1339
1340 // cause this modifier to be ignored
1341 key_state[modifier] = TOASCII_KEY_OFF;
1342
1343 WORD translated = 0;
1344 if (ToAscii(key_event->wVirtualKeyCode,
1345 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1346 // Ignoring the modifier, we found a character.
1347 *ch = (CHAR)translated;
1348 return 1;
1349 }
1350 }
1351 }
1352
1353 // Just use whatever Windows told us originally.
1354 *ch = key_event->uChar.AsciiChar;
1355
1356 // If the character from Windows is NULL, return a size of zero.
1357 return (*ch == '\0') ? 0 : 1;
1358}
1359
1360// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1361// but taking into account the shift key. This is because for a sequence like
1362// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1363// we want to find the character ')'.
1364//
1365// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1366// because it is the default key-sequence to switch the input language.
1367// This is configurable in the Region and Language control panel.
1368static __inline__ size_t _get_non_control_char(char* const ch,
1369 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1370 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1371 VK_CONTROL);
1372}
1373
1374// Get without Alt.
1375static __inline__ size_t _get_non_alt_char(char* const ch,
1376 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1377 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1378 VK_MENU);
1379}
1380
1381// Ignore the control key, find the character from Windows, and apply any
1382// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1383// *pch and returns number of bytes written.
1384static size_t _get_control_character(char* const pch,
1385 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1386 const size_t len = _get_non_control_char(pch, key_event,
1387 control_key_state);
1388
1389 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1390 char ch = *pch;
1391 switch (ch) {
1392 case '2':
1393 case '@':
1394 case '`':
1395 ch = '\0';
1396 break;
1397 case '3':
1398 case '[':
1399 case '{':
1400 ch = '\x1b';
1401 break;
1402 case '4':
1403 case '\\':
1404 case '|':
1405 ch = '\x1c';
1406 break;
1407 case '5':
1408 case ']':
1409 case '}':
1410 ch = '\x1d';
1411 break;
1412 case '6':
1413 case '^':
1414 case '~':
1415 ch = '\x1e';
1416 break;
1417 case '7':
1418 case '-':
1419 case '_':
1420 ch = '\x1f';
1421 break;
1422 case '8':
1423 ch = '\x7f';
1424 break;
1425 case '/':
1426 if (!_is_alt_pressed(control_key_state)) {
1427 ch = '\x1f';
1428 }
1429 break;
1430 case '?':
1431 if (!_is_alt_pressed(control_key_state)) {
1432 ch = '\x7f';
1433 }
1434 break;
1435 }
1436 *pch = ch;
1437 }
1438
1439 return len;
1440}
1441
1442static DWORD _normalize_altgr_control_key_state(
1443 const KEY_EVENT_RECORD* const key_event) {
1444 DWORD control_key_state = key_event->dwControlKeyState;
1445
1446 // If we're in an AltGr situation where the AltGr key is down (depending on
1447 // the keyboard layout, that might be the physical right alt key which
1448 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1449 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1450 // a character (which indicates that there was an AltGr mapping), then act
1451 // as if alt and control are not really down for the purposes of modifiers.
1452 // This makes it so that if the user with, say, a German keyboard layout
1453 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1454 // output the key and we don't see the Alt and Ctrl keys.
1455 if (_is_ctrl_pressed(control_key_state) &&
1456 _is_alt_pressed(control_key_state)
1457 && (key_event->uChar.AsciiChar != '\0')) {
1458 // Try to remove as few bits as possible to improve our chances of
1459 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1460 // Left-Alt + Right-Ctrl + AltGr.
1461 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1462 // Remove Right-Alt.
1463 control_key_state &= ~RIGHT_ALT_PRESSED;
1464 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1465 // pressed, Left-Ctrl is almost always set, except if the user
1466 // presses Right-Ctrl, then AltGr (in that specific order) for
1467 // whatever reason. At any rate, make sure the bit is not set.
1468 control_key_state &= ~LEFT_CTRL_PRESSED;
1469 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1470 // Remove Left-Alt.
1471 control_key_state &= ~LEFT_ALT_PRESSED;
1472 // Whichever Ctrl key is down, remove it from the state. We only
1473 // remove one key, to improve our chances of detecting the
1474 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1475 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1476 // Remove Left-Ctrl.
1477 control_key_state &= ~LEFT_CTRL_PRESSED;
1478 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1479 // Remove Right-Ctrl.
1480 control_key_state &= ~RIGHT_CTRL_PRESSED;
1481 }
1482 }
1483
1484 // Note that this logic isn't 100% perfect because Windows doesn't
1485 // allow us to detect all combinations because a physical AltGr key
1486 // press shows up as two bits, plus some combinations are ambiguous
1487 // about what is actually physically pressed.
1488 }
1489
1490 return control_key_state;
1491}
1492
1493// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1494// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1495// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1496// appropriately.
1497static DWORD _normalize_keypad_control_key_state(const WORD vk,
1498 const DWORD control_key_state) {
1499 if (!_is_numlock_on(control_key_state)) {
1500 return control_key_state;
1501 }
1502 if (!_is_enhanced_key(control_key_state)) {
1503 switch (vk) {
1504 case VK_INSERT: // 0
1505 case VK_DELETE: // .
1506 case VK_END: // 1
1507 case VK_DOWN: // 2
1508 case VK_NEXT: // 3
1509 case VK_LEFT: // 4
1510 case VK_CLEAR: // 5
1511 case VK_RIGHT: // 6
1512 case VK_HOME: // 7
1513 case VK_UP: // 8
1514 case VK_PRIOR: // 9
1515 return control_key_state | SHIFT_PRESSED;
1516 }
1517 }
1518
1519 return control_key_state;
1520}
1521
1522static const char* _get_keypad_sequence(const DWORD control_key_state,
1523 const char* const normal, const char* const shifted) {
1524 if (_is_shift_pressed(control_key_state)) {
1525 // Shift is pressed and NumLock is off
1526 return shifted;
1527 } else {
1528 // Shift is not pressed and NumLock is off, or,
1529 // Shift is pressed and NumLock is on, in which case we want the
1530 // NumLock and Shift to neutralize each other, thus, we want the normal
1531 // sequence.
1532 return normal;
1533 }
1534 // If Shift is not pressed and NumLock is on, a different virtual key code
1535 // is returned by Windows, which can be taken care of by a different case
1536 // statement in _console_read().
1537}
1538
1539// Write sequence to buf and return the number of bytes written.
1540static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1541 DWORD control_key_state, const char* const normal) {
1542 // Copy the base sequence into buf.
1543 const size_t len = strlen(normal);
1544 memcpy(buf, normal, len);
1545
1546 int code = 0;
1547
1548 control_key_state = _normalize_keypad_control_key_state(vk,
1549 control_key_state);
1550
1551 if (_is_shift_pressed(control_key_state)) {
1552 code |= 0x1;
1553 }
1554 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1555 code |= 0x2;
1556 }
1557 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1558 code |= 0x4;
1559 }
1560 // If some modifier was held down, then we need to insert the modifier code
1561 if (code != 0) {
1562 if (len == 0) {
1563 // Should be impossible because caller should pass a string of
1564 // non-zero length.
1565 return 0;
1566 }
1567 size_t index = len - 1;
1568 const char lastChar = buf[index];
1569 if (lastChar != '~') {
1570 buf[index++] = '1';
1571 }
1572 buf[index++] = ';'; // modifier separator
1573 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1574 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1575 buf[index++] = '1' + code;
1576 buf[index++] = lastChar; // move ~ (or other last char) to the end
1577 return index;
1578 }
1579 return len;
1580}
1581
1582// Write sequence to buf and return the number of bytes written.
1583static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1584 const DWORD control_key_state, const char* const normal,
1585 const char shifted) {
1586 if (_is_shift_pressed(control_key_state)) {
1587 // Shift is pressed and NumLock is off
1588 if (shifted != '\0') {
1589 buf[0] = shifted;
1590 return sizeof(buf[0]);
1591 } else {
1592 return 0;
1593 }
1594 } else {
1595 // Shift is not pressed and NumLock is off, or,
1596 // Shift is pressed and NumLock is on, in which case we want the
1597 // NumLock and Shift to neutralize each other, thus, we want the normal
1598 // sequence.
1599 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1600 }
1601 // If Shift is not pressed and NumLock is on, a different virtual key code
1602 // is returned by Windows, which can be taken care of by a different case
1603 // statement in _console_read().
1604}
1605
1606// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1607// Standard German. Figure this out at runtime so we know what to output for
1608// Shift-VK_DELETE.
1609static char _get_decimal_char() {
1610 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1611}
1612
1613// Prefix the len bytes in buf with the escape character, and then return the
1614// new buffer length.
1615size_t _escape_prefix(char* const buf, const size_t len) {
1616 // If nothing to prefix, don't do anything. We might be called with
1617 // len == 0, if alt was held down with a dead key which produced nothing.
1618 if (len == 0) {
1619 return 0;
1620 }
1621
1622 memmove(&buf[1], buf, len);
1623 buf[0] = '\x1b';
1624 return len + 1;
1625}
1626
Spencer Low9c8f7462015-11-10 19:17:16 -08001627// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001628static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001629
1630// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1631// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001632static int _console_read(const HANDLE console, void* buf, size_t len) {
1633 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001634 // Read of zero bytes should not block waiting for something from the console.
1635 if (len == 0) {
1636 return 0;
1637 }
1638
1639 // Flush as much as possible from input buffer.
1640 if (!g_console_input_buffer.empty()) {
1641 const int bytes_read = std::min(len, g_console_input_buffer.size());
1642 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1643 const auto begin = g_console_input_buffer.begin();
1644 g_console_input_buffer.erase(begin, begin + bytes_read);
1645 return bytes_read;
1646 }
1647
1648 // Read from the actual console. This may block until input.
1649 INPUT_RECORD input_record;
1650 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001651 return -1;
1652 }
1653
Spencer Low9c8f7462015-11-10 19:17:16 -08001654 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001655 const WORD vk = key_event->wVirtualKeyCode;
1656 const CHAR ch = key_event->uChar.AsciiChar;
1657 const DWORD control_key_state = _normalize_altgr_control_key_state(
1658 key_event);
1659
1660 // The following emulation code should write the output sequence to
1661 // either seqstr or to seqbuf and seqbuflen.
1662 const char* seqstr = NULL; // NULL terminated C-string
1663 // Enough space for max sequence string below, plus modifiers and/or
1664 // escape prefix.
1665 char seqbuf[16];
1666 size_t seqbuflen = 0; // Space used in seqbuf.
1667
1668#define MATCH(vk, normal) \
1669 case (vk): \
1670 { \
1671 seqstr = (normal); \
1672 } \
1673 break;
1674
1675 // Modifier keys should affect the output sequence.
1676#define MATCH_MODIFIER(vk, normal) \
1677 case (vk): \
1678 { \
1679 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1680 control_key_state, (normal)); \
1681 } \
1682 break;
1683
1684 // The shift key should affect the output sequence.
1685#define MATCH_KEYPAD(vk, normal, shifted) \
1686 case (vk): \
1687 { \
1688 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1689 (shifted)); \
1690 } \
1691 break;
1692
1693 // The shift key and other modifier keys should affect the output
1694 // sequence.
1695#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1696 case (vk): \
1697 { \
1698 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1699 control_key_state, (normal), (shifted)); \
1700 } \
1701 break;
1702
1703#define ESC "\x1b"
1704#define CSI ESC "["
1705#define SS3 ESC "O"
1706
1707 // Only support normal mode, not application mode.
1708
1709 // Enhanced keys:
1710 // * 6-pack: insert, delete, home, end, page up, page down
1711 // * cursor keys: up, down, right, left
1712 // * keypad: divide, enter
1713 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1714 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1715 if (_is_enhanced_key(control_key_state)) {
1716 switch (vk) {
1717 case VK_RETURN: // Enter key on keypad
1718 if (_is_ctrl_pressed(control_key_state)) {
1719 seqstr = "\n";
1720 } else {
1721 seqstr = "\r";
1722 }
1723 break;
1724
1725 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1726 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1727
1728 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1729 // will be fixed soon to match xterm which sends CSI "F" and
1730 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1731 MATCH(VK_END, CSI "F");
1732 MATCH(VK_HOME, CSI "H");
1733
1734 MATCH_MODIFIER(VK_LEFT, CSI "D");
1735 MATCH_MODIFIER(VK_UP, CSI "A");
1736 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1737 MATCH_MODIFIER(VK_DOWN, CSI "B");
1738
1739 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1740 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1741
1742 MATCH(VK_DIVIDE, "/");
1743 }
1744 } else { // Non-enhanced keys:
1745 switch (vk) {
1746 case VK_BACK: // backspace
1747 if (_is_alt_pressed(control_key_state)) {
1748 seqstr = ESC "\x7f";
1749 } else {
1750 seqstr = "\x7f";
1751 }
1752 break;
1753
1754 case VK_TAB:
1755 if (_is_shift_pressed(control_key_state)) {
1756 seqstr = CSI "Z";
1757 } else {
1758 seqstr = "\t";
1759 }
1760 break;
1761
1762 // Number 5 key in keypad when NumLock is off, or if NumLock is
1763 // on and Shift is down.
1764 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1765
1766 case VK_RETURN: // Enter key on main keyboard
1767 if (_is_alt_pressed(control_key_state)) {
1768 seqstr = ESC "\n";
1769 } else if (_is_ctrl_pressed(control_key_state)) {
1770 seqstr = "\n";
1771 } else {
1772 seqstr = "\r";
1773 }
1774 break;
1775
1776 // VK_ESCAPE: Don't do any special handling. The OS uses many
1777 // of the sequences with Escape and many of the remaining
1778 // sequences don't produce bKeyDown messages, only !bKeyDown
1779 // for whatever reason.
1780
1781 case VK_SPACE:
1782 if (_is_alt_pressed(control_key_state)) {
1783 seqstr = ESC " ";
1784 } else if (_is_ctrl_pressed(control_key_state)) {
1785 seqbuf[0] = '\0'; // NULL char
1786 seqbuflen = 1;
1787 } else {
1788 seqstr = " ";
1789 }
1790 break;
1791
1792 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1793 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1794
1795 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1796 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1797
1798 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1799 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1800 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1801 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1802
1803 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1804 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1805 _get_decimal_char());
1806
1807 case 0x30: // 0
1808 case 0x31: // 1
1809 case 0x39: // 9
1810 case VK_OEM_1: // ;:
1811 case VK_OEM_PLUS: // =+
1812 case VK_OEM_COMMA: // ,<
1813 case VK_OEM_PERIOD: // .>
1814 case VK_OEM_7: // '"
1815 case VK_OEM_102: // depends on keyboard, could be <> or \|
1816 case VK_OEM_2: // /?
1817 case VK_OEM_3: // `~
1818 case VK_OEM_4: // [{
1819 case VK_OEM_5: // \|
1820 case VK_OEM_6: // ]}
1821 {
1822 seqbuflen = _get_control_character(seqbuf, key_event,
1823 control_key_state);
1824
1825 if (_is_alt_pressed(control_key_state)) {
1826 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1827 }
1828 }
1829 break;
1830
1831 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001832 case 0x33: // 3
1833 case 0x34: // 4
1834 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001835 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001836 case 0x37: // 7
1837 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001838 case VK_OEM_MINUS: // -_
1839 {
1840 seqbuflen = _get_control_character(seqbuf, key_event,
1841 control_key_state);
1842
1843 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1844 // prefix with escape.
1845 if (_is_alt_pressed(control_key_state) &&
1846 !(_is_ctrl_pressed(control_key_state) &&
1847 !_is_shift_pressed(control_key_state))) {
1848 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1849 }
1850 }
1851 break;
1852
Spencer Lowbeb61982015-03-01 15:06:21 -08001853 case 0x41: // a
1854 case 0x42: // b
1855 case 0x43: // c
1856 case 0x44: // d
1857 case 0x45: // e
1858 case 0x46: // f
1859 case 0x47: // g
1860 case 0x48: // h
1861 case 0x49: // i
1862 case 0x4a: // j
1863 case 0x4b: // k
1864 case 0x4c: // l
1865 case 0x4d: // m
1866 case 0x4e: // n
1867 case 0x4f: // o
1868 case 0x50: // p
1869 case 0x51: // q
1870 case 0x52: // r
1871 case 0x53: // s
1872 case 0x54: // t
1873 case 0x55: // u
1874 case 0x56: // v
1875 case 0x57: // w
1876 case 0x58: // x
1877 case 0x59: // y
1878 case 0x5a: // z
1879 {
1880 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1881 control_key_state);
1882
1883 // If Alt is pressed, then prefix with escape.
1884 if (_is_alt_pressed(control_key_state)) {
1885 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1886 }
1887 }
1888 break;
1889
1890 // These virtual key codes are generated by the keys on the
1891 // keypad *when NumLock is on* and *Shift is up*.
1892 MATCH(VK_NUMPAD0, "0");
1893 MATCH(VK_NUMPAD1, "1");
1894 MATCH(VK_NUMPAD2, "2");
1895 MATCH(VK_NUMPAD3, "3");
1896 MATCH(VK_NUMPAD4, "4");
1897 MATCH(VK_NUMPAD5, "5");
1898 MATCH(VK_NUMPAD6, "6");
1899 MATCH(VK_NUMPAD7, "7");
1900 MATCH(VK_NUMPAD8, "8");
1901 MATCH(VK_NUMPAD9, "9");
1902
1903 MATCH(VK_MULTIPLY, "*");
1904 MATCH(VK_ADD, "+");
1905 MATCH(VK_SUBTRACT, "-");
1906 // VK_DECIMAL is generated by the . key on the keypad *when
1907 // NumLock is on* and *Shift is up* and the sequence is not
1908 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1909 // Windows Security screen to come up).
1910 case VK_DECIMAL:
1911 // U.S. English uses '.', Germany German uses ','.
1912 seqbuflen = _get_non_control_char(seqbuf, key_event,
1913 control_key_state);
1914 break;
1915
1916 MATCH_MODIFIER(VK_F1, SS3 "P");
1917 MATCH_MODIFIER(VK_F2, SS3 "Q");
1918 MATCH_MODIFIER(VK_F3, SS3 "R");
1919 MATCH_MODIFIER(VK_F4, SS3 "S");
1920 MATCH_MODIFIER(VK_F5, CSI "15~");
1921 MATCH_MODIFIER(VK_F6, CSI "17~");
1922 MATCH_MODIFIER(VK_F7, CSI "18~");
1923 MATCH_MODIFIER(VK_F8, CSI "19~");
1924 MATCH_MODIFIER(VK_F9, CSI "20~");
1925 MATCH_MODIFIER(VK_F10, CSI "21~");
1926 MATCH_MODIFIER(VK_F11, CSI "23~");
1927 MATCH_MODIFIER(VK_F12, CSI "24~");
1928
1929 MATCH_MODIFIER(VK_F13, CSI "25~");
1930 MATCH_MODIFIER(VK_F14, CSI "26~");
1931 MATCH_MODIFIER(VK_F15, CSI "28~");
1932 MATCH_MODIFIER(VK_F16, CSI "29~");
1933 MATCH_MODIFIER(VK_F17, CSI "31~");
1934 MATCH_MODIFIER(VK_F18, CSI "32~");
1935 MATCH_MODIFIER(VK_F19, CSI "33~");
1936 MATCH_MODIFIER(VK_F20, CSI "34~");
1937
1938 // MATCH_MODIFIER(VK_F21, ???);
1939 // MATCH_MODIFIER(VK_F22, ???);
1940 // MATCH_MODIFIER(VK_F23, ???);
1941 // MATCH_MODIFIER(VK_F24, ???);
1942 }
1943 }
1944
1945#undef MATCH
1946#undef MATCH_MODIFIER
1947#undef MATCH_KEYPAD
1948#undef MATCH_MODIFIER_KEYPAD
1949#undef ESC
1950#undef CSI
1951#undef SS3
1952
1953 const char* out;
1954 size_t outlen;
1955
1956 // Check for output in any of:
1957 // * seqstr is set (and strlen can be used to determine the length).
1958 // * seqbuf and seqbuflen are set
1959 // Fallback to ch from Windows.
1960 if (seqstr != NULL) {
1961 out = seqstr;
1962 outlen = strlen(seqstr);
1963 } else if (seqbuflen > 0) {
1964 out = seqbuf;
1965 outlen = seqbuflen;
1966 } else if (ch != '\0') {
1967 // Use whatever Windows told us it is.
1968 seqbuf[0] = ch;
1969 seqbuflen = 1;
1970 out = seqbuf;
1971 outlen = seqbuflen;
1972 } else {
1973 // No special handling for the virtual key code and Windows isn't
1974 // telling us a character code, then we don't know how to translate
1975 // the key press.
1976 //
1977 // Consume the input and 'continue' to cause us to get a new key
1978 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07001979 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08001980 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08001981 continue;
1982 }
1983
Spencer Low9c8f7462015-11-10 19:17:16 -08001984 // put output wRepeatCount times into g_console_input_buffer
1985 while (key_event->wRepeatCount-- > 0) {
1986 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08001987 }
1988
Spencer Low9c8f7462015-11-10 19:17:16 -08001989 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08001990 }
1991}
1992
1993static DWORD _old_console_mode; // previous GetConsoleMode() result
1994static HANDLE _console_handle; // when set, console mode should be restored
1995
Elliott Hughesa8265792015-11-03 11:18:40 -08001996void stdin_raw_init() {
1997 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08001998 if (in == nullptr) {
1999 return;
2000 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002001
Elliott Hughesa8265792015-11-03 11:18:40 -08002002 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2003 // calling the process Ctrl-C routine (configured by
2004 // SetConsoleCtrlHandler()).
2005 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2006 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2007 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08002008 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2009 ENABLE_LINE_INPUT |
2010 ENABLE_ECHO_INPUT);
2011 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2012 new_console_mode |= ENABLE_WINDOW_INPUT;
2013
2014 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002015 // This really should not fail.
2016 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002017 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002018 }
Elliott Hughesa8265792015-11-03 11:18:40 -08002019
2020 // Once this is set, it means that stdin has been configured for
2021 // reading from and that the old console mode should be restored later.
2022 _console_handle = in;
2023
2024 // Note that we don't need to configure C Runtime line-ending
2025 // translation because _console_read() does not call the C Runtime to
2026 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002027}
2028
Elliott Hughesa8265792015-11-03 11:18:40 -08002029void stdin_raw_restore() {
2030 if (_console_handle != NULL) {
2031 const HANDLE in = _console_handle;
2032 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002033
Elliott Hughesa8265792015-11-03 11:18:40 -08002034 if (!SetConsoleMode(in, _old_console_mode)) {
2035 // This really should not fail.
2036 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002037 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002038 }
2039 }
2040}
2041
Spencer Low55441402015-11-07 17:34:39 -08002042// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2043int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002044 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2045 // If it is a request to read from stdin, and stdin_raw_init() has been
2046 // called, and it successfully configured the console, then read from
2047 // the console using Win32 console APIs and partially emulate a unix
2048 // terminal.
2049 return _console_read(_console_handle, buf, len);
2050 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002051 // On older versions of Windows (definitely 7, definitely not 10),
2052 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002053 // we need to limit the read size.
2054 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002055 len = 4096;
2056 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002057 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002058 // can do LF/CR translation (which is overridable with _setmode()).
2059 // Undefine the macro that is set in sysdeps.h which bans calls to
2060 // plain read() in favor of unix_read() or adb_read().
2061#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002062#undef read
2063 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002064#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002065 }
2066}
Spencer Low6815c072015-05-11 01:08:48 -07002067
2068/**************************************************************************/
2069/**************************************************************************/
2070/***** *****/
2071/***** Unicode support *****/
2072/***** *****/
2073/**************************************************************************/
2074/**************************************************************************/
2075
2076// This implements support for using files with Unicode filenames and for
2077// outputting Unicode text to a Win32 console window. This is inspired from
2078// http://utf8everywhere.org/.
2079//
2080// Background
2081// ----------
2082//
2083// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2084// filenames to APIs such as open(). This works because filenames are largely
2085// opaque 'cookies' (perhaps excluding path separators).
2086//
2087// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2088// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2089// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2090// CreateFile() API is really just a macro that adds the W/A based on whether
2091// the UNICODE preprocessor symbol is defined).
2092//
2093// Options
2094// -------
2095//
2096// Thus, to write a portable program, there are a few options:
2097//
2098// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2099// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2100// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2101// open() API.
2102//
2103// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2104// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2105// potentially touching a lot of code.
2106//
2107// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2108// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2109// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2110// or C Runtime API.
2111//
2112// The Choice
2113// ----------
2114//
Spencer Low50f5bf12015-11-12 15:20:15 -08002115// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2116// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002117// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002118// args that are passed to main() at the beginning of program startup. We also use
2119// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002120// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2121//
2122// Unicode console output
2123// ----------------------
2124//
2125// The way to output Unicode to a Win32 console window is to call
2126// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002127// such as Lucida Console or Consolas, and in the case of East Asian languages
2128// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2129// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2130// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002131//
2132// The problem is getting the C Runtime to make fprintf and related APIs call
2133// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2134// promising, but the various modes have issues:
2135//
2136// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2137// UTF-16 do not display properly.
2138// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2139// totally wrong.
2140// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2141// handler to be called (upon a later I/O call), aborting the process.
2142// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2143// to output nothing.
2144//
2145// So the only solution is to write our own adb_fprintf() that converts UTF-8
2146// to UTF-16 and then calls WriteConsoleW().
2147
2148
Spencer Low6815c072015-05-11 01:08:48 -07002149// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2150// be passed to main().
2151NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2152 narrow_args = new char*[argc + 1];
2153
2154 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002155 std::string arg_narrow;
2156 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2157 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2158 }
2159 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002160 }
2161 narrow_args[argc] = nullptr; // terminate
2162}
2163
2164NarrowArgs::~NarrowArgs() {
2165 if (narrow_args != nullptr) {
2166 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2167 free(*argp);
2168 }
2169 delete[] narrow_args;
2170 narrow_args = nullptr;
2171 }
2172}
2173
2174int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002175 std::wstring path_wide;
2176 if (!android::base::UTF8ToWide(path, &path_wide)) {
2177 return -1;
2178 }
Spencer Low6815c072015-05-11 01:08:48 -07002179 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002180 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002181 } else {
2182 int mode;
2183 va_list args;
2184 va_start(args, options);
2185 mode = va_arg(args, int);
2186 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002187 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002188 }
2189}
2190
Spencer Low6815c072015-05-11 01:08:48 -07002191// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002192DIR* adb_opendir(const char* path) {
2193 std::wstring path_wide;
2194 if (!android::base::UTF8ToWide(path, &path_wide)) {
2195 return nullptr;
2196 }
2197
Spencer Low6815c072015-05-11 01:08:48 -07002198 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2199 // the fields, but right now all the callers treat the structure as
2200 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002201 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002202}
2203
2204// Version of readdir() that returns UTF-8 paths.
2205struct dirent* adb_readdir(DIR* dir) {
2206 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2207 struct _wdirent* const went = _wreaddir(wdir);
2208 if (went == nullptr) {
2209 return nullptr;
2210 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002211
Spencer Low6815c072015-05-11 01:08:48 -07002212 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002213 std::string name_utf8;
2214 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2215 return nullptr;
2216 }
Spencer Low6815c072015-05-11 01:08:48 -07002217
2218 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2219 // space for UTF-16 wchar_t's) with UTF-8 char's.
2220 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2221
2222 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2223 // Name too big to fit in existing buffer.
2224 errno = ENOMEM;
2225 return nullptr;
2226 }
2227
2228 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2229 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2230 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2231 // bigger than the caller expects because they expect a dirent structure
2232 // which has a smaller d_name field. Ignore this since the caller should be
2233 // resilient.
2234
2235 // Rewrite the UTF-16 d_name field to UTF-8.
2236 strcpy(ent->d_name, name_utf8.c_str());
2237
2238 return ent;
2239}
2240
2241// Version of closedir() to go with our version of adb_opendir().
2242int adb_closedir(DIR* dir) {
2243 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2244}
2245
2246// Version of unlink() that takes a UTF-8 path.
2247int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002248 std::wstring wpath;
2249 if (!android::base::UTF8ToWide(path, &wpath)) {
2250 return -1;
2251 }
Spencer Low6815c072015-05-11 01:08:48 -07002252
2253 int rc = _wunlink(wpath.c_str());
2254
2255 if (rc == -1 && errno == EACCES) {
2256 /* unlink returns EACCES when the file is read-only, so we first */
2257 /* try to make it writable, then unlink again... */
2258 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2259 if (rc == 0)
2260 rc = _wunlink(wpath.c_str());
2261 }
2262 return rc;
2263}
2264
2265// Version of mkdir() that takes a UTF-8 path.
2266int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002267 std::wstring path_wide;
2268 if (!android::base::UTF8ToWide(path, &path_wide)) {
2269 return -1;
2270 }
2271
2272 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002273}
2274
2275// Version of utime() that takes a UTF-8 path.
2276int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002277 std::wstring path_wide;
2278 if (!android::base::UTF8ToWide(path, &path_wide)) {
2279 return -1;
2280 }
2281
Spencer Low6815c072015-05-11 01:08:48 -07002282 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2283 "utimbuf and _utimbuf should be the same size because they both "
2284 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002285 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002286}
2287
2288// Version of chmod() that takes a UTF-8 path.
2289int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002290 std::wstring path_wide;
2291 if (!android::base::UTF8ToWide(path, &path_wide)) {
2292 return -1;
2293 }
2294
2295 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002296}
2297
Spencer Lowf373c352015-11-15 16:29:36 -08002298// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2299static inline size_t utf8_codepoint_len(uint8_t ch) {
2300 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2301}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002302
Spencer Lowf373c352015-11-15 16:29:36 -08002303namespace internal {
2304
2305// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2306// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2307// remaining_bytes.
2308size_t ParseCompleteUTF8(const char* const first, const char* const last,
2309 std::vector<char>* const remaining_bytes) {
2310 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2311 // Current_after points one byte past the current byte to be examined.
2312 for (const char* current_after = last; current_after != first; --current_after) {
2313 const char* const current = current_after - 1;
2314 const char ch = *current;
2315 const char kHighBit = 0x80u;
2316 const char kTwoHighestBits = 0xC0u;
2317 if ((ch & kHighBit) == 0) { // high bit not set
2318 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2319 // bytes with no leading byte, so return the entire buffer.
2320 break;
2321 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2322 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2323 const size_t bytes_available = last - current;
2324 if (bytes_available < utf8_codepoint_len(ch)) {
2325 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2326 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2327 // to remaining_bytes.
2328 remaining_bytes->insert(remaining_bytes->end(), current, last);
2329 return current - first;
2330 } else {
2331 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2332 // trailing bytes with no lead byte, so return the entire buffer.
2333 break;
2334 }
2335 } else {
2336 // Trailing byte, so keep going backwards looking for the lead byte.
2337 }
2338 }
2339
2340 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2341 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2342 // so that they can be processed.
2343 return last - first;
2344}
2345
2346}
2347
2348// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2349// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2350// This matches the behavior of Linux.
Spencer Lowf373c352015-11-15 16:29:36 -08002351
2352// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2353static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2354 HANDLE console) {
Josh Gaoe7daf572016-09-21 12:37:10 -07002355 static std::mutex& console_output_buffer_lock = *new std::mutex();
2356 static auto& console_output_buffer = *new std::vector<char>();
2357
Spencer Lowf373c352015-11-15 16:29:36 -08002358 const int saved_errno = errno;
2359 std::vector<char> combined_buffer;
2360
2361 // Complete UTF-8 sequences that should be immediately written to the console.
2362 const char* utf8;
2363 size_t utf8_size;
2364
Josh Gaoe7daf572016-09-21 12:37:10 -07002365 {
2366 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2367 if (console_output_buffer.empty()) {
2368 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2369 // common case with plain ASCII), parse buf directly.
2370 utf8 = buf;
2371 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2372 } else {
2373 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2374 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2375 // combined_buffer, then parse it all together.
2376 combined_buffer.swap(console_output_buffer);
2377 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowf373c352015-11-15 16:29:36 -08002378
Josh Gaoe7daf572016-09-21 12:37:10 -07002379 utf8 = combined_buffer.data();
2380 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2381 &console_output_buffer);
2382 }
Spencer Lowf373c352015-11-15 16:29:36 -08002383 }
Spencer Lowf373c352015-11-15 16:29:36 -08002384
2385 std::wstring utf16;
2386
2387 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2388 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2389 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002390 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002391 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002392
2393 // Note that this does not do \n => \r\n translation because that
2394 // doesn't seem necessary for the Windows console. For the Windows
2395 // console \r moves to the beginning of the line and \n moves to a new
2396 // line.
2397
2398 // Flush any stream buffering so that our output is afterwards which
2399 // makes sense because our call is afterwards.
2400 (void)fflush(stream);
2401
2402 // Write UTF-16 to the console.
2403 DWORD written = 0;
Spencer Lowf373c352015-11-15 16:29:36 -08002404 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Low6815c072015-05-11 01:08:48 -07002405 errno = EIO;
2406 return -1;
2407 }
2408
Spencer Lowf373c352015-11-15 16:29:36 -08002409 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2410 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2411 // matches the Linux behavior.
2412 errno = saved_errno;
2413 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002414}
2415
2416// Function prototype because attributes cannot be placed on func definitions.
2417static int _console_vfprintf(const HANDLE console, FILE* stream,
2418 const char *format, va_list ap)
2419 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2420
2421// Internal function to format a UTF-8 string and write it to a Win32 console.
2422// Returns -1 on error.
2423static int _console_vfprintf(const HANDLE console, FILE* stream,
2424 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002425 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002426 std::string output_utf8;
2427
2428 // Format the string.
2429 // This could throw std::bad_alloc.
2430 android::base::StringAppendV(&output_utf8, format, ap);
2431
Spencer Lowf373c352015-11-15 16:29:36 -08002432 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2433 console);
2434 if (result != -1) {
2435 errno = saved_errno;
2436 } else {
2437 // If -1 was returned, errno has been set.
2438 }
2439 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002440}
2441
2442// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2443// Windows console.
2444int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2445 const HANDLE console = _get_console_handle(stream);
2446
2447 // If there is an associated Win32 console, write to it specially,
2448 // otherwise defer to the regular C Runtime, passing it UTF-8.
2449 if (console != NULL) {
2450 return _console_vfprintf(console, stream, format, ap);
2451 } else {
2452 // If vfprintf is a macro, undefine it, so we can call the real
2453 // C Runtime API.
2454#pragma push_macro("vfprintf")
2455#undef vfprintf
2456 return vfprintf(stream, format, ap);
2457#pragma pop_macro("vfprintf")
2458 }
2459}
2460
Spencer Lowf373c352015-11-15 16:29:36 -08002461// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2462int adb_vprintf(const char *format, va_list ap) {
2463 return adb_vfprintf(stdout, format, ap);
2464}
2465
Spencer Low6815c072015-05-11 01:08:48 -07002466// Version of fprintf() that takes UTF-8 and can write Unicode to a
2467// Windows console.
2468int adb_fprintf(FILE *stream, const char *format, ...) {
2469 va_list ap;
2470 va_start(ap, format);
2471 const int result = adb_vfprintf(stream, format, ap);
2472 va_end(ap);
2473
2474 return result;
2475}
2476
2477// Version of printf() that takes UTF-8 and can write Unicode to a
2478// Windows console.
2479int adb_printf(const char *format, ...) {
2480 va_list ap;
2481 va_start(ap, format);
2482 const int result = adb_vfprintf(stdout, format, ap);
2483 va_end(ap);
2484
2485 return result;
2486}
2487
2488// Version of fputs() that takes UTF-8 and can write Unicode to a
2489// Windows console.
2490int adb_fputs(const char* buf, FILE* stream) {
2491 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2492 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002493 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002494 return adb_fprintf(stream, "%s", buf);
2495}
2496
2497// Version of fputc() that takes UTF-8 and can write Unicode to a
2498// Windows console.
2499int adb_fputc(int ch, FILE* stream) {
2500 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002501 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002502 return EOF;
2503 }
2504 // For success, fputc returns the char, cast to unsigned char, then to int.
2505 return static_cast<unsigned char>(ch);
2506}
2507
Spencer Lowf373c352015-11-15 16:29:36 -08002508// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2509int adb_putchar(int ch) {
2510 return adb_fputc(ch, stdout);
2511}
2512
2513// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2514int adb_puts(const char* buf) {
2515 // adb_printf returns -1 on error, which is conveniently the same as EOF
2516 // which puts (and hence adb_puts) should return on error.
2517 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2518 return adb_printf("%s\n", buf);
2519}
2520
Spencer Low6815c072015-05-11 01:08:48 -07002521// Internal function to write UTF-8 to a Win32 console. Returns the number of
2522// items (of length size) written. On error, returns a short item count or 0.
2523static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2524 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002525 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2526 console);
Spencer Low6815c072015-05-11 01:08:48 -07002527 if (result == -1) {
2528 return 0;
2529 }
2530 return result / size;
2531}
2532
2533// Version of fwrite() that takes UTF-8 and can write Unicode to a
2534// Windows console.
2535size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2536 const HANDLE console = _get_console_handle(stream);
2537
2538 // If there is an associated Win32 console, write to it specially,
2539 // otherwise defer to the regular C Runtime, passing it UTF-8.
2540 if (console != NULL) {
2541 return _console_fwrite(ptr, size, nmemb, stream, console);
2542 } else {
2543 // If fwrite is a macro, undefine it, so we can call the real
2544 // C Runtime API.
2545#pragma push_macro("fwrite")
2546#undef fwrite
2547 return fwrite(ptr, size, nmemb, stream);
2548#pragma pop_macro("fwrite")
2549 }
2550}
2551
2552// Version of fopen() that takes a UTF-8 filename and can access a file with
2553// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002554FILE* adb_fopen(const char* path, const char* mode) {
2555 std::wstring path_wide;
2556 if (!android::base::UTF8ToWide(path, &path_wide)) {
2557 return nullptr;
2558 }
2559
2560 std::wstring mode_wide;
2561 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2562 return nullptr;
2563 }
2564
2565 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002566}
2567
Spencer Low50740f52015-09-08 17:13:04 -07002568// Return a lowercase version of the argument. Uses C Runtime tolower() on
2569// each byte which is not UTF-8 aware, and theoretically uses the current C
2570// Runtime locale (which in practice is not changed, so this becomes a ASCII
2571// conversion).
2572static std::string ToLower(const std::string& anycase) {
2573 // copy string
2574 std::string str(anycase);
2575 // transform the copy
2576 std::transform(str.begin(), str.end(), str.begin(), tolower);
2577 return str;
2578}
2579
2580extern "C" int main(int argc, char** argv);
2581
2582// Link with -municode to cause this wmain() to be used as the program
2583// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2584// regular main() with UTF-8 args.
2585extern "C" int wmain(int argc, wchar_t **argv) {
2586 // Convert args from UTF-16 to UTF-8 and pass that to main().
2587 NarrowArgs narrow_args(argc, argv);
2588 return main(argc, narrow_args.data());
2589}
2590
Spencer Low6815c072015-05-11 01:08:48 -07002591// Shadow UTF-8 environment variable name/value pairs that are created from
2592// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07002593// currently updated if putenv, setenv, unsetenv are called. Note that no
2594// thread synchronization is done, but we're called early enough in
2595// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002596static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002597
2598// Make sure that shadow UTF-8 environment variables are setup.
2599static void _ensure_env_setup() {
2600 // If some name/value pairs exist, then we've already done the setup below.
2601 if (g_environ_utf8.size() != 0) {
2602 return;
2603 }
2604
Spencer Low50740f52015-09-08 17:13:04 -07002605 if (_wenviron == nullptr) {
2606 // If _wenviron is null, then -municode probably wasn't used. That
2607 // linker flag will cause the entry point to setup _wenviron. It will
2608 // also require an implementation of wmain() (which we provide above).
2609 fatal("_wenviron is not set, did you link with -municode?");
2610 }
2611
Spencer Low6815c072015-05-11 01:08:48 -07002612 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2613 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2614 // to use the D() macro here because that tracing only works if the
2615 // ADB_TRACE environment variable is setup, but that env var can't be read
2616 // until this code completes.
2617 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2618 wchar_t* const equal = wcschr(*env, L'=');
2619 if (equal == nullptr) {
2620 // Malformed environment variable with no equal sign. Shouldn't
2621 // really happen, but we should be resilient to this.
2622 continue;
2623 }
2624
Spencer Low50f5bf12015-11-12 15:20:15 -08002625 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2626 // var because the program might never even read this particular variable.
2627 std::string name_utf8;
2628 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2629 continue;
2630 }
2631
Spencer Low50740f52015-09-08 17:13:04 -07002632 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002633 name_utf8 = ToLower(name_utf8);
2634
2635 std::string value_utf8;
2636 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2637 continue;
2638 }
2639
2640 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002641
Spencer Low50740f52015-09-08 17:13:04 -07002642 // Don't overwrite a previus env var with the same name. In reality,
2643 // the system probably won't let two env vars with the same name exist
2644 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002645 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002646 }
2647}
2648
2649// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002650// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002651char* adb_getenv(const char* name) {
2652 _ensure_env_setup();
2653
Spencer Low50740f52015-09-08 17:13:04 -07002654 // Case-insensitive search by searching for lowercase name in a map of
2655 // lowercase names.
2656 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002657 if (it == g_environ_utf8.end()) {
2658 return nullptr;
2659 }
2660
2661 return it->second;
2662}
2663
2664// Version of getcwd() that returns the current working directory in UTF-8.
2665char* adb_getcwd(char* buf, int size) {
2666 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2667 if (wbuf == nullptr) {
2668 return nullptr;
2669 }
2670
Spencer Low50f5bf12015-11-12 15:20:15 -08002671 std::string buf_utf8;
2672 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002673 free(wbuf);
2674 wbuf = nullptr;
2675
Spencer Low50f5bf12015-11-12 15:20:15 -08002676 if (!narrow_result) {
2677 return nullptr;
2678 }
2679
Spencer Low6815c072015-05-11 01:08:48 -07002680 // If size was specified, make sure all the chars will fit.
2681 if (size != 0) {
2682 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2683 errno = ERANGE;
2684 return nullptr;
2685 }
2686 }
2687
2688 // If buf was not specified, allocate storage.
2689 if (buf == nullptr) {
2690 if (size == 0) {
2691 size = buf_utf8.length() + 1;
2692 }
2693 buf = reinterpret_cast<char*>(malloc(size));
2694 if (buf == nullptr) {
2695 return nullptr;
2696 }
2697 }
2698
2699 // Destination buffer was allocated with enough space, or we've already
2700 // checked an existing buffer size for enough space.
2701 strcpy(buf, buf_utf8.c_str());
2702
2703 return buf;
2704}