blob: 7d35fb67b5fa0ad085b68907cb685301f361dfda [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 char name[32];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800130} FHRec;
131
132#define fh_handle u.handle
133#define fh_socket u.socket
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800134
Josh Gao4f657a72016-02-17 16:45:39 -0800135#define WIN32_FH_BASE 2048
Josh Gao7c9e5fb2016-04-18 11:09:28 -0700136#define WIN32_MAX_FHS 2048
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800137
Josh Gaoe7daf572016-09-21 12:37:10 -0700138static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800139static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700140static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800141
142static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700143_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800144{
145 FH f;
146
147 fd -= WIN32_FH_BASE;
148
Spencer Lowb732a372015-07-24 15:38:19 -0700149 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui815ad882015-09-02 17:44:28 -0700150 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700151 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800152 errno = EBADF;
153 return NULL;
154 }
155
156 f = &_win32_fhs[fd];
157
158 if (f->used == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700159 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700160 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800161 errno = EBADF;
162 return NULL;
163 }
164
165 return f;
166}
167
168
169static int
170_fh_to_int( FH f )
171{
172 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
173 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
174
175 return -1;
176}
177
178static FH
179_fh_alloc( FHClass clazz )
180{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800181 FH f = NULL;
182
Josh Gaoe7daf572016-09-21 12:37:10 -0700183 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800184
Josh Gao4f657a72016-02-17 16:45:39 -0800185 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
186 if (_win32_fhs[i].clazz == NULL) {
187 f = &_win32_fhs[i];
188 _win32_fh_next = i + 1;
Josh Gaoe7daf572016-09-21 12:37:10 -0700189 f->clazz = clazz;
190 f->used = 1;
191 f->eof = 0;
192 f->name[0] = '\0';
193 clazz->_fh_init(f);
194 return f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800195 }
196 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700197
198 D("_fh_alloc: no more free file descriptors");
199 errno = EMFILE; // Too many open files
200 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800201}
202
203
204static int
205_fh_close( FH f )
206{
Spencer Lowb732a372015-07-24 15:38:19 -0700207 // Use lock so that closing only happens once and so that _fh_alloc can't
208 // allocate a FH that we're in the middle of closing.
Josh Gaoe7daf572016-09-21 12:37:10 -0700209 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gao4f657a72016-02-17 16:45:39 -0800210
211 int offset = f - _win32_fhs;
212 if (_win32_fh_next > offset) {
213 _win32_fh_next = offset;
214 }
215
Spencer Lowb732a372015-07-24 15:38:19 -0700216 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800217 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700218 f->name[0] = '\0';
219 f->eof = 0;
220 f->used = 0;
221 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800222 }
223 return 0;
224}
225
Spencer Low753d4852015-07-30 23:07:55 -0700226// Deleter for unique_fh.
227class fh_deleter {
228 public:
229 void operator()(struct FHRec_* fh) {
230 // We're called from a destructor and destructors should not overwrite
231 // errno because callers may do:
232 // errno = EBLAH;
233 // return -1; // calls destructor, which should not overwrite errno
234 const int saved_errno = errno;
235 _fh_close(fh);
236 errno = saved_errno;
237 }
238};
239
240// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
241typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
242
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800243/**************************************************************************/
244/**************************************************************************/
245/***** *****/
246/***** file-based descriptor handling *****/
247/***** *****/
248/**************************************************************************/
249/**************************************************************************/
250
Elliott Hughes6a096932015-04-16 16:47:02 -0700251static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800252 f->fh_handle = INVALID_HANDLE_VALUE;
253}
254
Elliott Hughes6a096932015-04-16 16:47:02 -0700255static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800256 CloseHandle( f->fh_handle );
257 f->fh_handle = INVALID_HANDLE_VALUE;
258 return 0;
259}
260
Elliott Hughes6a096932015-04-16 16:47:02 -0700261static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800262 DWORD read_bytes;
263
264 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700265 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800266 errno = EIO;
267 return -1;
268 } else if (read_bytes < (DWORD)len) {
269 f->eof = 1;
270 }
271 return (int)read_bytes;
272}
273
Elliott Hughes6a096932015-04-16 16:47:02 -0700274static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800275 DWORD wrote_bytes;
276
277 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700278 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800279 errno = EIO;
280 return -1;
281 } else if (wrote_bytes < (DWORD)len) {
282 f->eof = 1;
283 }
284 return (int)wrote_bytes;
285}
286
Elliott Hughes6a096932015-04-16 16:47:02 -0700287static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800288 DWORD method;
289 DWORD result;
290
291 switch (origin)
292 {
293 case SEEK_SET: method = FILE_BEGIN; break;
294 case SEEK_CUR: method = FILE_CURRENT; break;
295 case SEEK_END: method = FILE_END; break;
296 default:
297 errno = EINVAL;
298 return -1;
299 }
300
301 result = SetFilePointer( f->fh_handle, pos, NULL, method );
302 if (result == INVALID_SET_FILE_POINTER) {
303 errno = EIO;
304 return -1;
305 } else {
306 f->eof = 0;
307 }
308 return (int)result;
309}
310
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800311
312/**************************************************************************/
313/**************************************************************************/
314/***** *****/
315/***** file-based descriptor handling *****/
316/***** *****/
317/**************************************************************************/
318/**************************************************************************/
319
320int adb_open(const char* path, int options)
321{
322 FH f;
323
324 DWORD desiredAccess = 0;
325 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
326
327 switch (options) {
328 case O_RDONLY:
329 desiredAccess = GENERIC_READ;
330 break;
331 case O_WRONLY:
332 desiredAccess = GENERIC_WRITE;
333 break;
334 case O_RDWR:
335 desiredAccess = GENERIC_READ | GENERIC_WRITE;
336 break;
337 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700338 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800339 errno = EINVAL;
340 return -1;
341 }
342
343 f = _fh_alloc( &_fh_file_class );
344 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800345 return -1;
346 }
347
Spencer Low50f5bf12015-11-12 15:20:15 -0800348 std::wstring path_wide;
349 if (!android::base::UTF8ToWide(path, &path_wide)) {
350 return -1;
351 }
352 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Low6815c072015-05-11 01:08:48 -0700353 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800354
355 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700356 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800357 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700358 D( "adb_open: could not open '%s': ", path );
359 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800360 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700361 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800362 errno = ENOENT;
363 return -1;
364
365 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700366 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800367 errno = ENOTDIR;
368 return -1;
369
370 default:
David Pursellc573d522016-01-27 08:52:53 -0800371 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800372 errno = ENOENT;
373 return -1;
374 }
375 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800376
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800377 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700378 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800379 return _fh_to_int(f);
380}
381
382/* ignore mode on Win32 */
383int adb_creat(const char* path, int mode)
384{
385 FH f;
386
387 f = _fh_alloc( &_fh_file_class );
388 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800389 return -1;
390 }
391
Spencer Low50f5bf12015-11-12 15:20:15 -0800392 std::wstring path_wide;
393 if (!android::base::UTF8ToWide(path, &path_wide)) {
394 return -1;
395 }
396 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Low6815c072015-05-11 01:08:48 -0700397 FILE_SHARE_READ | FILE_SHARE_WRITE,
398 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
399 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800400
401 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700402 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800403 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700404 D( "adb_creat: could not open '%s': ", path );
405 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800406 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700407 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800408 errno = ENOENT;
409 return -1;
410
411 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700412 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800413 errno = ENOTDIR;
414 return -1;
415
416 default:
David Pursellc573d522016-01-27 08:52:53 -0800417 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800418 errno = ENOENT;
419 return -1;
420 }
421 }
422 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700423 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800424 return _fh_to_int(f);
425}
426
427
428int adb_read(int fd, void* buf, int len)
429{
Spencer Low3a2421b2015-05-22 20:09:06 -0700430 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800431
432 if (f == NULL) {
433 return -1;
434 }
435
436 return f->clazz->_fh_read( f, buf, len );
437}
438
439
440int adb_write(int fd, const void* buf, int len)
441{
Spencer Low3a2421b2015-05-22 20:09:06 -0700442 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800443
444 if (f == NULL) {
445 return -1;
446 }
447
448 return f->clazz->_fh_write(f, buf, len);
449}
450
451
452int adb_lseek(int fd, int pos, int where)
453{
Spencer Low3a2421b2015-05-22 20:09:06 -0700454 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800455
456 if (!f) {
457 return -1;
458 }
459
460 return f->clazz->_fh_lseek(f, pos, where);
461}
462
463
464int adb_close(int fd)
465{
Spencer Low3a2421b2015-05-22 20:09:06 -0700466 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800467
468 if (!f) {
469 return -1;
470 }
471
Yabin Cui815ad882015-09-02 17:44:28 -0700472 D( "adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800473 _fh_close(f);
474 return 0;
475}
476
477/**************************************************************************/
478/**************************************************************************/
479/***** *****/
480/***** socket-based file descriptors *****/
481/***** *****/
482/**************************************************************************/
483/**************************************************************************/
484
Spencer Low31aafa62015-01-25 14:40:16 -0800485#undef setsockopt
486
Spencer Low753d4852015-07-30 23:07:55 -0700487static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700488 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
489 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gao75e96bb2016-12-05 13:24:48 -0800490 // are mapped to strings by adb_strerror().
Spencer Low753d4852015-07-30 23:07:55 -0700491 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800492 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700493 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
494 // case WSAEINTR: errno = EINTR; break;
495 case WSAEFAULT: errno = EFAULT; break;
496 case WSAEINVAL: errno = EINVAL; break;
497 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700498 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
499 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
500 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800501 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700502 case WSAENOTSOCK: errno = ENOTSOCK; break;
503 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
504 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
505 case WSAENETDOWN: errno = ENETDOWN; break;
506 case WSAENETRESET: errno = ENETRESET; break;
507 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
508 // to use EPIPE for these situations and there are some callers that look
509 // for EPIPE.
510 case WSAECONNABORTED: errno = EPIPE; break;
511 case WSAECONNRESET: errno = ECONNRESET; break;
512 case WSAENOBUFS: errno = ENOBUFS; break;
513 case WSAENOTCONN: errno = ENOTCONN; break;
514 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
515 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
516 // considerations: Reportedly send() can return zero on timeout, and POSIX
517 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
518 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
519 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800520 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800521 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700522 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700523 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800524 }
525}
526
Josh Gaoe7388122016-02-16 17:34:53 -0800527extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
528 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
529 int skipped = 0;
530 std::vector<WSAPOLLFD> sockets;
531 std::vector<adb_pollfd*> original;
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700532
Josh Gaoe7388122016-02-16 17:34:53 -0800533 for (size_t i = 0; i < nfds; ++i) {
534 FH fh = _fh_from_int(fds[i].fd, __func__);
535 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
536 D("adb_poll received bad FD %d", fds[i].fd);
537 fds[i].revents = POLLNVAL;
538 ++skipped;
539 } else {
540 WSAPOLLFD wsapollfd = {
541 .fd = fh->u.socket,
542 .events = static_cast<short>(fds[i].events)
543 };
544 sockets.push_back(wsapollfd);
545 original.push_back(&fds[i]);
546 }
Spencer Low753d4852015-07-30 23:07:55 -0700547 }
Josh Gaoe7388122016-02-16 17:34:53 -0800548
549 if (sockets.empty()) {
550 return skipped;
551 }
552
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700553 // If we have any invalid FDs in our FD set, make sure to return immediately.
554 if (skipped > 0) {
555 timeout = 0;
556 }
557
Josh Gaoe7388122016-02-16 17:34:53 -0800558 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
559 if (result == SOCKET_ERROR) {
560 _socket_set_errno(WSAGetLastError());
561 return -1;
562 }
563
564 // Map the results back onto the original set.
565 for (size_t i = 0; i < sockets.size(); ++i) {
566 original[i]->revents = sockets[i].revents;
567 }
568
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700569 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gaoe7388122016-02-16 17:34:53 -0800570 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
571 // to do. Ignore its result and calculate the proper return value.
572 result = 0;
573 for (size_t i = 0; i < nfds; ++i) {
574 if (fds[i].revents != 0) {
575 ++result;
576 }
577 }
578 return result;
579}
580
581static void _fh_socket_init(FH f) {
582 f->fh_socket = INVALID_SOCKET;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800583}
584
Elliott Hughes6a096932015-04-16 16:47:02 -0700585static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700586 if (f->fh_socket != INVALID_SOCKET) {
587 /* gently tell any peer that we're closing the socket */
588 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
589 // If the socket is not connected, this returns an error. We want to
590 // minimize logging spam, so don't log these errors for now.
591#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700592 D("socket shutdown failed: %s",
David Pursellc573d522016-01-27 08:52:53 -0800593 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700594#endif
595 }
596 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800597 // Don't set errno here, since adb_close will ignore it.
598 const DWORD err = WSAGetLastError();
599 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700600 }
601 f->fh_socket = INVALID_SOCKET;
602 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800603 return 0;
604}
605
Elliott Hughes6a096932015-04-16 16:47:02 -0700606static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800607 errno = EPIPE;
608 return -1;
609}
610
Elliott Hughes6a096932015-04-16 16:47:02 -0700611static int _fh_socket_read(FH f, void* buf, int len) {
612 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800613 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700614 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700615 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
616 // that to reduce spam and confusion.
617 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700618 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800619 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low32625852015-08-11 16:45:32 -0700620 }
Spencer Low753d4852015-07-30 23:07:55 -0700621 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800622 result = -1;
623 }
624 return result;
625}
626
Elliott Hughes6a096932015-04-16 16:47:02 -0700627static int _fh_socket_write(FH f, const void* buf, int len) {
628 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800629 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700630 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700631 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
632 // that to reduce spam and confusion.
633 if (err != WSAEWOULDBLOCK) {
634 D("send fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800635 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low028e1592015-10-18 16:45:09 -0700636 }
Spencer Low753d4852015-07-30 23:07:55 -0700637 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800638 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700639 } else {
640 // According to https://code.google.com/p/chromium/issues/detail?id=27870
641 // Winsock Layered Service Providers may cause this.
642 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
643 << f->name << ", but " << result
644 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800645 }
646 return result;
647}
648
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800649/**************************************************************************/
650/**************************************************************************/
651/***** *****/
652/***** replacement for libs/cutils/socket_xxxx.c *****/
653/***** *****/
654/**************************************************************************/
655/**************************************************************************/
656
657#include <winsock2.h>
658
659static int _winsock_init;
660
661static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800662_init_winsock( void )
663{
Spencer Low753d4852015-07-30 23:07:55 -0700664 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700665 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800666 if (!_winsock_init) {
667 WSADATA wsaData;
668 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
669 if (rc != 0) {
David Pursellc573d522016-01-27 08:52:53 -0800670 fatal("adb: could not initialize Winsock: %s",
671 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800672 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800673 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700674
675 // Note that we do not call atexit() to register WSACleanup to be called
676 // at normal process termination because:
677 // 1) When exit() is called, there are still threads actively using
678 // Winsock because we don't cleanly shutdown all threads, so it
679 // doesn't make sense to call WSACleanup() and may cause problems
680 // with those threads.
681 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
682 // calls WSACleanup() which tries to unload a DLL, which tries to
683 // grab the LoaderLock. This conflicts with the device_poll_thread
684 // which holds the LoaderLock because AdbWinApi.dll calls
685 // setupapi.dll which tries to load wintrust.dll which tries to load
686 // crypt32.dll which calls atexit() which tries to acquire the C
687 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800688 }
689}
690
Spencer Lowc7c45612015-09-29 15:05:29 -0700691// Map a socket type to an explicit socket protocol instead of using the socket
692// protocol of 0. Explicit socket protocols are used by most apps and we should
693// do the same to reduce the chance of exercising uncommon code-paths that might
694// have problems or that might load different Winsock service providers that
695// have problems.
696static int GetSocketProtocolFromSocketType(int type) {
697 switch (type) {
698 case SOCK_STREAM:
699 return IPPROTO_TCP;
700 case SOCK_DGRAM:
701 return IPPROTO_UDP;
702 default:
703 LOG(FATAL) << "Unknown socket type: " << type;
704 return 0;
705 }
706}
707
Spencer Low753d4852015-07-30 23:07:55 -0700708int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800709 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800710 SOCKET s;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800711
Josh Gao61eda8d2016-02-18 13:43:55 -0800712 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low753d4852015-07-30 23:07:55 -0700713 if (!f) {
714 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800715 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700716 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800717
Josh Gao61eda8d2016-02-18 13:43:55 -0800718 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800719
720 memset(&addr, 0, sizeof(addr));
721 addr.sin_family = AF_INET;
722 addr.sin_port = htons(port);
723 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
724
Spencer Lowc7c45612015-09-29 15:05:29 -0700725 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao61eda8d2016-02-18 13:43:55 -0800726 if (s == INVALID_SOCKET) {
727 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700728 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800729 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700730 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800731 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700732 return -1;
733 }
734 f->fh_socket = s;
735
Josh Gao61eda8d2016-02-18 13:43:55 -0800736 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700737 // Save err just in case inet_ntoa() or ntohs() changes the last error.
738 const DWORD err = WSAGetLastError();
739 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800740 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
741 android::base::SystemErrorCodeToString(err).c_str());
742 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
743 error->c_str());
744 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800745 return -1;
746 }
747
Spencer Low753d4852015-07-30 23:07:55 -0700748 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800749 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
750 port);
751 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700752 f.release();
753 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800754}
755
Spencer Low753d4852015-07-30 23:07:55 -0700756// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao61eda8d2016-02-18 13:43:55 -0800757static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800758 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800759 SOCKET s;
760 int n;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800761
Josh Gao61eda8d2016-02-18 13:43:55 -0800762 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800763 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700764 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800765 return -1;
766 }
767
Josh Gao61eda8d2016-02-18 13:43:55 -0800768 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800769
770 memset(&addr, 0, sizeof(addr));
771 addr.sin_family = AF_INET;
772 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700773 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800774
Spencer Low753d4852015-07-30 23:07:55 -0700775 // TODO: Consider using dual-stack socket that can simultaneously listen on
776 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700777 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700778 if (s == INVALID_SOCKET) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800779 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700780 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800781 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700782 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800783 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700784 return -1;
785 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800786
787 f->fh_socket = s;
788
Spencer Low32625852015-08-11 16:45:32 -0700789 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
790 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800791 n = 1;
Josh Gao61eda8d2016-02-18 13:43:55 -0800792 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
793 const DWORD err = WSAGetLastError();
794 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
795 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700796 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800797 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700798 return -1;
799 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800800
Josh Gao61eda8d2016-02-18 13:43:55 -0800801 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700802 // Save err just in case inet_ntoa() or ntohs() changes the last error.
803 const DWORD err = WSAGetLastError();
Josh Gao61eda8d2016-02-18 13:43:55 -0800804 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
805 ntohs(addr.sin_port),
806 android::base::SystemErrorCodeToString(err).c_str());
807 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
808 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800809 return -1;
810 }
811 if (type == SOCK_STREAM) {
Josh Gaoa076b152018-03-20 14:25:03 -0700812 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800813 const DWORD err = WSAGetLastError();
814 *error = android::base::StringPrintf(
815 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
816 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
817 error->c_str());
818 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800819 return -1;
820 }
821 }
Spencer Low753d4852015-07-30 23:07:55 -0700822 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800823 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
824 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
825 port);
826 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700827 f.release();
828 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800829}
830
Spencer Low753d4852015-07-30 23:07:55 -0700831int network_loopback_server(int port, int type, std::string* error) {
832 return _network_server(port, type, INADDR_LOOPBACK, error);
833}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800834
Spencer Low753d4852015-07-30 23:07:55 -0700835int network_inaddr_any_server(int port, int type, std::string* error) {
836 return _network_server(port, type, INADDR_ANY, error);
837}
838
839int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
840 unique_fh f(_fh_alloc(&_fh_socket_class));
841 if (!f) {
842 *error = strerror(errno);
843 return -1;
844 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800845
Elliott Hughes43df1092015-07-23 17:12:58 -0700846 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800847
Spencer Low753d4852015-07-30 23:07:55 -0700848 struct addrinfo hints;
849 memset(&hints, 0, sizeof(hints));
850 hints.ai_family = AF_UNSPEC;
851 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700852 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700853
854 char port_str[16];
855 snprintf(port_str, sizeof(port_str), "%d", port);
856
857 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700858
859#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao61eda8d2016-02-18 13:43:55 -0800860// TODO: When the Android SDK tools increases the Windows system
861// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700862#else
Josh Gao61eda8d2016-02-18 13:43:55 -0800863// Otherwise, keep using getaddrinfo(), or do runtime API detection
864// with GetProcAddress("GetAddrInfoW").
Spencer Lowcc467f12015-08-02 18:13:54 -0700865#endif
Spencer Low753d4852015-07-30 23:07:55 -0700866 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800867 const DWORD err = WSAGetLastError();
868 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
869 host.c_str(), port_str,
870 android::base::SystemErrorCodeToString(err).c_str());
871
Yabin Cui815ad882015-09-02 17:44:28 -0700872 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800873 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800874 return -1;
875 }
Elliott Hughes8ac45992016-08-08 12:52:37 -0700876 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low753d4852015-07-30 23:07:55 -0700877 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800878
Spencer Low753d4852015-07-30 23:07:55 -0700879 // TODO: Try all the addresses if there's more than one? This just uses
880 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
881 // which tries all addresses, takes a timeout and more.
Josh Gao61eda8d2016-02-18 13:43:55 -0800882 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
883 if (s == INVALID_SOCKET) {
884 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700885 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800886 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700887 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800888 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800889 return -1;
890 }
891 f->fh_socket = s;
892
Spencer Low753d4852015-07-30 23:07:55 -0700893 // TODO: Implement timeouts for Windows. Seems like the default in theory
894 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao61eda8d2016-02-18 13:43:55 -0800895 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700896 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao61eda8d2016-02-18 13:43:55 -0800897 const DWORD err = WSAGetLastError();
898 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
899 android::base::SystemErrorCodeToString(err).c_str());
900 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
901 port_str, error->c_str());
902 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800903 return -1;
904 }
905
Spencer Low753d4852015-07-30 23:07:55 -0700906 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800907 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
908 port);
909 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
910 fd);
Spencer Low753d4852015-07-30 23:07:55 -0700911 f.release();
912 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800913}
914
Casey Dahlin20238f22016-09-21 14:03:39 -0700915int adb_register_socket(SOCKET s) {
916 FH f = _fh_alloc( &_fh_socket_class );
917 f->fh_socket = s;
918 return _fh_to_int(f);
919}
920
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800921#undef accept
922int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
923{
Spencer Low3a2421b2015-05-22 20:09:06 -0700924 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200925
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800926 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700927 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -0700928 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800929 return -1;
930 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200931
Spencer Low753d4852015-07-30 23:07:55 -0700932 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800933 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700934 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
935 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800936 return -1;
937 }
938
939 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
940 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700941 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700942 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursellc573d522016-01-27 08:52:53 -0800943 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low753d4852015-07-30 23:07:55 -0700944 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800945 return -1;
946 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200947
Spencer Low753d4852015-07-30 23:07:55 -0700948 const int fd = _fh_to_int(fh.get());
949 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -0700950 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -0700951 fh.release();
952 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800953}
954
955
Spencer Low31aafa62015-01-25 14:40:16 -0800956int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800957{
Spencer Low3a2421b2015-05-22 20:09:06 -0700958 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200959
Spencer Low31aafa62015-01-25 14:40:16 -0800960 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700961 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700962 errno = EBADF;
963 return -1;
964 }
Spencer Lowc7c45612015-09-29 15:05:29 -0700965
966 // TODO: Once we can assume Windows Vista or later, if the caller is trying
967 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
968 // auto-tuning.
969
Spencer Low753d4852015-07-30 23:07:55 -0700970 int result = setsockopt( fh->fh_socket, level, optname,
971 reinterpret_cast<const char*>(optval), optlen );
972 if ( result == SOCKET_ERROR ) {
973 const DWORD err = WSAGetLastError();
David Pursellc573d522016-01-27 08:52:53 -0800974 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
975 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700976 _socket_set_errno( err );
977 result = -1;
978 }
979 return result;
980}
981
Josh Gaoe7388122016-02-16 17:34:53 -0800982int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
983 FH fh = _fh_from_int(fd, __func__);
984
985 if (!fh || fh->clazz != &_fh_socket_class) {
986 D("adb_getsockname: invalid fd %d", fd);
987 errno = EBADF;
988 return -1;
989 }
990
Josh Gao4f6f4422017-03-30 13:04:35 -0700991 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gaoe7388122016-02-16 17:34:53 -0800992 if (result == SOCKET_ERROR) {
993 const DWORD err = WSAGetLastError();
994 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
995 android::base::SystemErrorCodeToString(err).c_str());
996 _socket_set_errno(err);
997 result = -1;
998 }
999 return result;
1000}
Spencer Low753d4852015-07-30 23:07:55 -07001001
David Pursell19d0c232016-04-07 11:25:48 -07001002int adb_socket_get_local_port(int fd) {
1003 sockaddr_storage addr_storage;
1004 socklen_t addr_len = sizeof(addr_storage);
1005
1006 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1007 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1008 return -1;
1009 }
1010
1011 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1012 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1013 errno = ECONNABORTED;
1014 return -1;
1015 }
1016
1017 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1018}
1019
Josh Gao96049b92018-03-23 13:03:28 -07001020int adb_shutdown(int fd, int direction) {
1021 FH f = _fh_from_int(fd, __func__);
Spencer Low753d4852015-07-30 23:07:55 -07001022
1023 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001024 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001025 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001026 return -1;
1027 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001028
Josh Gao96049b92018-03-23 13:03:28 -07001029 D("adb_shutdown: %s", f->name);
1030 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -07001031 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001032 D("socket shutdown fd %d failed: %s", fd,
David Pursellc573d522016-01-27 08:52:53 -08001033 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001034 _socket_set_errno(err);
1035 return -1;
1036 }
1037 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001038}
1039
Josh Gaoe7388122016-02-16 17:34:53 -08001040// Emulate socketpair(2) by binding and connecting to a socket.
1041int adb_socketpair(int sv[2]) {
1042 int server = -1;
1043 int client = -1;
1044 int accepted = -1;
David Pursell19d0c232016-04-07 11:25:48 -07001045 int local_port = -1;
Josh Gaoe7388122016-02-16 17:34:53 -08001046 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001047
Josh Gaoe7388122016-02-16 17:34:53 -08001048 server = network_loopback_server(0, SOCK_STREAM, &error);
1049 if (server < 0) {
1050 D("adb_socketpair: failed to create server: %s", error.c_str());
1051 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001052 }
1053
David Pursell19d0c232016-04-07 11:25:48 -07001054 local_port = adb_socket_get_local_port(server);
1055 if (local_port < 0) {
1056 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gaoe7388122016-02-16 17:34:53 -08001057 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001058 }
David Pursell19d0c232016-04-07 11:25:48 -07001059 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001060
David Pursell19d0c232016-04-07 11:25:48 -07001061 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gaoe7388122016-02-16 17:34:53 -08001062 if (client < 0) {
1063 D("adb_socketpair: failed to connect client: %s", error.c_str());
1064 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001065 }
1066
Josh Gao4f6f4422017-03-30 13:04:35 -07001067 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gaoe7388122016-02-16 17:34:53 -08001068 if (accepted < 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -08001069 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoe7388122016-02-16 17:34:53 -08001070 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001071 }
Josh Gaoe7388122016-02-16 17:34:53 -08001072 adb_close(server);
1073 sv[0] = client;
1074 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001075 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001076
Josh Gaoe7388122016-02-16 17:34:53 -08001077fail:
1078 if (server >= 0) {
1079 adb_close(server);
1080 }
1081 if (client >= 0) {
1082 adb_close(client);
1083 }
1084 if (accepted >= 0) {
1085 adb_close(accepted);
1086 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001087 return -1;
1088}
1089
Josh Gaoe7388122016-02-16 17:34:53 -08001090bool set_file_block_mode(int fd, bool block) {
1091 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001092
Josh Gaoe7388122016-02-16 17:34:53 -08001093 if (!fh || !fh->used) {
1094 errno = EBADF;
Casey Dahlin20238f22016-09-21 14:03:39 -07001095 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gaoe7388122016-02-16 17:34:53 -08001096 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001097 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001098
Josh Gaoe7388122016-02-16 17:34:53 -08001099 if (fh->clazz == &_fh_socket_class) {
1100 u_long x = !block;
1101 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin20238f22016-09-21 14:03:39 -07001102 int error = WSAGetLastError();
1103 _socket_set_errno(error);
1104 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gaoe7388122016-02-16 17:34:53 -08001105 return false;
1106 }
1107 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001108 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001109 errno = ENOTSOCK;
Casey Dahlin20238f22016-09-21 14:03:39 -07001110 D("Setting nonblocking on non-socket %d", fd);
Josh Gaoe7388122016-02-16 17:34:53 -08001111 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001112 }
1113}
1114
David Pursellc25a34e2016-02-22 14:27:23 -08001115bool set_tcp_keepalive(int fd, int interval_sec) {
1116 FH fh = _fh_from_int(fd, __func__);
1117
1118 if (!fh || fh->clazz != &_fh_socket_class) {
1119 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1120 errno = EBADF;
1121 return false;
1122 }
1123
1124 tcp_keepalive keepalive;
1125 keepalive.onoff = (interval_sec > 0);
1126 keepalive.keepalivetime = interval_sec * 1000;
1127 keepalive.keepaliveinterval = interval_sec * 1000;
1128
1129 DWORD bytes_returned = 0;
1130 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1131 &bytes_returned, nullptr, nullptr) != 0) {
1132 const DWORD err = WSAGetLastError();
1133 D("set_tcp_keepalive(%d) failed: %s", fd,
1134 android::base::SystemErrorCodeToString(err).c_str());
1135 _socket_set_errno(err);
1136 return false;
1137 }
1138
1139 return true;
1140}
1141
Spencer Lowbeb61982015-03-01 15:06:21 -08001142/**************************************************************************/
1143/**************************************************************************/
1144/***** *****/
1145/***** Console Window Terminal Emulation *****/
1146/***** *****/
1147/**************************************************************************/
1148/**************************************************************************/
1149
1150// This reads input from a Win32 console window and translates it into Unix
1151// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1152// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1153// is emulated instead of xterm because it is probably more popular than xterm:
1154// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1155// supports modern fonts, etc. It seems best to emulate the terminal that most
1156// Android developers use because they'll fix apps (the shell, etc.) to keep
1157// working with that terminal's emulation.
1158//
1159// The point of this emulation is not to be perfect or to solve all issues with
1160// console windows on Windows, but to be better than the original code which
1161// just called read() (which called ReadFile(), which called ReadConsoleA())
1162// which did not support Ctrl-C, tab completion, shell input line editing
1163// keys, server echo, and more.
1164//
1165// This implementation reconfigures the console with SetConsoleMode(), then
1166// calls ReadConsoleInput() to get raw input which it remaps to Unix
1167// terminal-style sequences which is returned via unix_read() which is used
1168// by the 'adb shell' command.
1169//
1170// Code organization:
1171//
David Pursell58805362015-10-28 14:29:51 -07001172// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001173// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1174// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1175// * _console_read() is the main code of the emulation.
1176
David Pursell58805362015-10-28 14:29:51 -07001177// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1178// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1179// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1180static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1181 // First check isatty(); this is very fast and eliminates most non-console
1182 // FDs, but returns 1 for both consoles and character devices like NUL.
1183#pragma push_macro("isatty")
1184#undef isatty
1185 if (!isatty(fd)) {
1186 return nullptr;
1187 }
1188#pragma pop_macro("isatty")
1189
1190 // To differentiate between character devices and consoles we need to get
1191 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1192 // GENERIC_READ permissions.
1193 const intptr_t intptr_handle = _get_osfhandle(fd);
1194 if (intptr_handle == -1) {
1195 return nullptr;
1196 }
1197 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1198 DWORD temp_mode = 0;
1199 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1200 return nullptr;
1201 }
1202
1203 return handle;
1204}
1205
1206// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1207static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001208 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1209 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001210 const int fd = fileno(stream);
1211 if (fd < 0) {
1212 return nullptr;
1213 }
1214 return _get_console_handle(fd);
1215}
1216
1217int unix_isatty(int fd) {
1218 return _get_console_handle(fd) ? 1 : 0;
1219}
Spencer Lowbeb61982015-03-01 15:06:21 -08001220
Spencer Low9c8f7462015-11-10 19:17:16 -08001221// Get the next KEY_EVENT_RECORD that should be processed.
1222static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001223 for (;;) {
1224 DWORD read_count = 0;
1225 memset(input_record, 0, sizeof(*input_record));
1226 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001227 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001228 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001229 errno = EIO;
1230 return false;
1231 }
1232
1233 if (read_count == 0) { // should be impossible
1234 fatal("ReadConsoleInputA returned 0");
1235 }
1236
1237 if (read_count != 1) { // should be impossible
1238 fatal("ReadConsoleInputA did not return one input record");
1239 }
1240
Spencer Low55441402015-11-07 17:34:39 -08001241 // If the console window is resized, emulate SIGWINCH by breaking out
1242 // of read() with errno == EINTR. Note that there is no event on
1243 // vertical resize because we don't give the console our own custom
1244 // screen buffer (with CreateConsoleScreenBuffer() +
1245 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1246 // supports scrollback, but doesn't seem to raise an event for vertical
1247 // window resize.
1248 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1249 errno = EINTR;
1250 return false;
1251 }
1252
Spencer Lowbeb61982015-03-01 15:06:21 -08001253 if ((input_record->EventType == KEY_EVENT) &&
1254 (input_record->Event.KeyEvent.bKeyDown)) {
1255 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1256 fatal("ReadConsoleInputA returned a key event with zero repeat"
1257 " count");
1258 }
1259
1260 // Got an interesting INPUT_RECORD, so return
1261 return true;
1262 }
1263 }
1264}
1265
Spencer Lowbeb61982015-03-01 15:06:21 -08001266static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1267 return (control_key_state & SHIFT_PRESSED) != 0;
1268}
1269
1270static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1271 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1272}
1273
1274static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1275 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1276}
1277
1278static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1279 return (control_key_state & NUMLOCK_ON) != 0;
1280}
1281
1282static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1283 return (control_key_state & CAPSLOCK_ON) != 0;
1284}
1285
1286static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1287 return (control_key_state & ENHANCED_KEY) != 0;
1288}
1289
1290// Constants from MSDN for ToAscii().
1291static const BYTE TOASCII_KEY_OFF = 0x00;
1292static const BYTE TOASCII_KEY_DOWN = 0x80;
1293static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1294
1295// Given a key event, ignore a modifier key and return the character that was
1296// entered without the modifier. Writes to *ch and returns the number of bytes
1297// written.
1298static size_t _get_char_ignoring_modifier(char* const ch,
1299 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1300 const WORD modifier) {
1301 // If there is no character from Windows, try ignoring the specified
1302 // modifier and look for a character. Note that if AltGr is being used,
1303 // there will be a character from Windows.
1304 if (key_event->uChar.AsciiChar == '\0') {
1305 // Note that we read the control key state from the passed in argument
1306 // instead of from key_event since the argument has been normalized.
1307 if (((modifier == VK_SHIFT) &&
1308 _is_shift_pressed(control_key_state)) ||
1309 ((modifier == VK_CONTROL) &&
1310 _is_ctrl_pressed(control_key_state)) ||
1311 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1312
1313 BYTE key_state[256] = {0};
1314 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1315 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1316 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1317 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1318 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1319 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1320 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1321 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1322
1323 // cause this modifier to be ignored
1324 key_state[modifier] = TOASCII_KEY_OFF;
1325
1326 WORD translated = 0;
1327 if (ToAscii(key_event->wVirtualKeyCode,
1328 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1329 // Ignoring the modifier, we found a character.
1330 *ch = (CHAR)translated;
1331 return 1;
1332 }
1333 }
1334 }
1335
1336 // Just use whatever Windows told us originally.
1337 *ch = key_event->uChar.AsciiChar;
1338
1339 // If the character from Windows is NULL, return a size of zero.
1340 return (*ch == '\0') ? 0 : 1;
1341}
1342
1343// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1344// but taking into account the shift key. This is because for a sequence like
1345// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1346// we want to find the character ')'.
1347//
1348// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1349// because it is the default key-sequence to switch the input language.
1350// This is configurable in the Region and Language control panel.
1351static __inline__ size_t _get_non_control_char(char* const ch,
1352 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1353 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1354 VK_CONTROL);
1355}
1356
1357// Get without Alt.
1358static __inline__ size_t _get_non_alt_char(char* const ch,
1359 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1360 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1361 VK_MENU);
1362}
1363
1364// Ignore the control key, find the character from Windows, and apply any
1365// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1366// *pch and returns number of bytes written.
1367static size_t _get_control_character(char* const pch,
1368 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1369 const size_t len = _get_non_control_char(pch, key_event,
1370 control_key_state);
1371
1372 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1373 char ch = *pch;
1374 switch (ch) {
1375 case '2':
1376 case '@':
1377 case '`':
1378 ch = '\0';
1379 break;
1380 case '3':
1381 case '[':
1382 case '{':
1383 ch = '\x1b';
1384 break;
1385 case '4':
1386 case '\\':
1387 case '|':
1388 ch = '\x1c';
1389 break;
1390 case '5':
1391 case ']':
1392 case '}':
1393 ch = '\x1d';
1394 break;
1395 case '6':
1396 case '^':
1397 case '~':
1398 ch = '\x1e';
1399 break;
1400 case '7':
1401 case '-':
1402 case '_':
1403 ch = '\x1f';
1404 break;
1405 case '8':
1406 ch = '\x7f';
1407 break;
1408 case '/':
1409 if (!_is_alt_pressed(control_key_state)) {
1410 ch = '\x1f';
1411 }
1412 break;
1413 case '?':
1414 if (!_is_alt_pressed(control_key_state)) {
1415 ch = '\x7f';
1416 }
1417 break;
1418 }
1419 *pch = ch;
1420 }
1421
1422 return len;
1423}
1424
1425static DWORD _normalize_altgr_control_key_state(
1426 const KEY_EVENT_RECORD* const key_event) {
1427 DWORD control_key_state = key_event->dwControlKeyState;
1428
1429 // If we're in an AltGr situation where the AltGr key is down (depending on
1430 // the keyboard layout, that might be the physical right alt key which
1431 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1432 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1433 // a character (which indicates that there was an AltGr mapping), then act
1434 // as if alt and control are not really down for the purposes of modifiers.
1435 // This makes it so that if the user with, say, a German keyboard layout
1436 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1437 // output the key and we don't see the Alt and Ctrl keys.
1438 if (_is_ctrl_pressed(control_key_state) &&
1439 _is_alt_pressed(control_key_state)
1440 && (key_event->uChar.AsciiChar != '\0')) {
1441 // Try to remove as few bits as possible to improve our chances of
1442 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1443 // Left-Alt + Right-Ctrl + AltGr.
1444 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1445 // Remove Right-Alt.
1446 control_key_state &= ~RIGHT_ALT_PRESSED;
1447 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1448 // pressed, Left-Ctrl is almost always set, except if the user
1449 // presses Right-Ctrl, then AltGr (in that specific order) for
1450 // whatever reason. At any rate, make sure the bit is not set.
1451 control_key_state &= ~LEFT_CTRL_PRESSED;
1452 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1453 // Remove Left-Alt.
1454 control_key_state &= ~LEFT_ALT_PRESSED;
1455 // Whichever Ctrl key is down, remove it from the state. We only
1456 // remove one key, to improve our chances of detecting the
1457 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1458 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1459 // Remove Left-Ctrl.
1460 control_key_state &= ~LEFT_CTRL_PRESSED;
1461 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1462 // Remove Right-Ctrl.
1463 control_key_state &= ~RIGHT_CTRL_PRESSED;
1464 }
1465 }
1466
1467 // Note that this logic isn't 100% perfect because Windows doesn't
1468 // allow us to detect all combinations because a physical AltGr key
1469 // press shows up as two bits, plus some combinations are ambiguous
1470 // about what is actually physically pressed.
1471 }
1472
1473 return control_key_state;
1474}
1475
1476// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1477// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1478// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1479// appropriately.
1480static DWORD _normalize_keypad_control_key_state(const WORD vk,
1481 const DWORD control_key_state) {
1482 if (!_is_numlock_on(control_key_state)) {
1483 return control_key_state;
1484 }
1485 if (!_is_enhanced_key(control_key_state)) {
1486 switch (vk) {
1487 case VK_INSERT: // 0
1488 case VK_DELETE: // .
1489 case VK_END: // 1
1490 case VK_DOWN: // 2
1491 case VK_NEXT: // 3
1492 case VK_LEFT: // 4
1493 case VK_CLEAR: // 5
1494 case VK_RIGHT: // 6
1495 case VK_HOME: // 7
1496 case VK_UP: // 8
1497 case VK_PRIOR: // 9
1498 return control_key_state | SHIFT_PRESSED;
1499 }
1500 }
1501
1502 return control_key_state;
1503}
1504
1505static const char* _get_keypad_sequence(const DWORD control_key_state,
1506 const char* const normal, const char* const shifted) {
1507 if (_is_shift_pressed(control_key_state)) {
1508 // Shift is pressed and NumLock is off
1509 return shifted;
1510 } else {
1511 // Shift is not pressed and NumLock is off, or,
1512 // Shift is pressed and NumLock is on, in which case we want the
1513 // NumLock and Shift to neutralize each other, thus, we want the normal
1514 // sequence.
1515 return normal;
1516 }
1517 // If Shift is not pressed and NumLock is on, a different virtual key code
1518 // is returned by Windows, which can be taken care of by a different case
1519 // statement in _console_read().
1520}
1521
1522// Write sequence to buf and return the number of bytes written.
1523static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1524 DWORD control_key_state, const char* const normal) {
1525 // Copy the base sequence into buf.
1526 const size_t len = strlen(normal);
1527 memcpy(buf, normal, len);
1528
1529 int code = 0;
1530
1531 control_key_state = _normalize_keypad_control_key_state(vk,
1532 control_key_state);
1533
1534 if (_is_shift_pressed(control_key_state)) {
1535 code |= 0x1;
1536 }
1537 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1538 code |= 0x2;
1539 }
1540 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1541 code |= 0x4;
1542 }
1543 // If some modifier was held down, then we need to insert the modifier code
1544 if (code != 0) {
1545 if (len == 0) {
1546 // Should be impossible because caller should pass a string of
1547 // non-zero length.
1548 return 0;
1549 }
1550 size_t index = len - 1;
1551 const char lastChar = buf[index];
1552 if (lastChar != '~') {
1553 buf[index++] = '1';
1554 }
1555 buf[index++] = ';'; // modifier separator
1556 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1557 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1558 buf[index++] = '1' + code;
1559 buf[index++] = lastChar; // move ~ (or other last char) to the end
1560 return index;
1561 }
1562 return len;
1563}
1564
1565// Write sequence to buf and return the number of bytes written.
1566static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1567 const DWORD control_key_state, const char* const normal,
1568 const char shifted) {
1569 if (_is_shift_pressed(control_key_state)) {
1570 // Shift is pressed and NumLock is off
1571 if (shifted != '\0') {
1572 buf[0] = shifted;
1573 return sizeof(buf[0]);
1574 } else {
1575 return 0;
1576 }
1577 } else {
1578 // Shift is not pressed and NumLock is off, or,
1579 // Shift is pressed and NumLock is on, in which case we want the
1580 // NumLock and Shift to neutralize each other, thus, we want the normal
1581 // sequence.
1582 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1583 }
1584 // If Shift is not pressed and NumLock is on, a different virtual key code
1585 // is returned by Windows, which can be taken care of by a different case
1586 // statement in _console_read().
1587}
1588
1589// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1590// Standard German. Figure this out at runtime so we know what to output for
1591// Shift-VK_DELETE.
1592static char _get_decimal_char() {
1593 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1594}
1595
1596// Prefix the len bytes in buf with the escape character, and then return the
1597// new buffer length.
1598size_t _escape_prefix(char* const buf, const size_t len) {
1599 // If nothing to prefix, don't do anything. We might be called with
1600 // len == 0, if alt was held down with a dead key which produced nothing.
1601 if (len == 0) {
1602 return 0;
1603 }
1604
1605 memmove(&buf[1], buf, len);
1606 buf[0] = '\x1b';
1607 return len + 1;
1608}
1609
Spencer Low9c8f7462015-11-10 19:17:16 -08001610// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001611static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001612
1613// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1614// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001615static int _console_read(const HANDLE console, void* buf, size_t len) {
1616 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001617 // Read of zero bytes should not block waiting for something from the console.
1618 if (len == 0) {
1619 return 0;
1620 }
1621
1622 // Flush as much as possible from input buffer.
1623 if (!g_console_input_buffer.empty()) {
1624 const int bytes_read = std::min(len, g_console_input_buffer.size());
1625 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1626 const auto begin = g_console_input_buffer.begin();
1627 g_console_input_buffer.erase(begin, begin + bytes_read);
1628 return bytes_read;
1629 }
1630
1631 // Read from the actual console. This may block until input.
1632 INPUT_RECORD input_record;
1633 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001634 return -1;
1635 }
1636
Spencer Low9c8f7462015-11-10 19:17:16 -08001637 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001638 const WORD vk = key_event->wVirtualKeyCode;
1639 const CHAR ch = key_event->uChar.AsciiChar;
1640 const DWORD control_key_state = _normalize_altgr_control_key_state(
1641 key_event);
1642
1643 // The following emulation code should write the output sequence to
1644 // either seqstr or to seqbuf and seqbuflen.
1645 const char* seqstr = NULL; // NULL terminated C-string
1646 // Enough space for max sequence string below, plus modifiers and/or
1647 // escape prefix.
1648 char seqbuf[16];
1649 size_t seqbuflen = 0; // Space used in seqbuf.
1650
1651#define MATCH(vk, normal) \
1652 case (vk): \
1653 { \
1654 seqstr = (normal); \
1655 } \
1656 break;
1657
1658 // Modifier keys should affect the output sequence.
1659#define MATCH_MODIFIER(vk, normal) \
1660 case (vk): \
1661 { \
1662 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1663 control_key_state, (normal)); \
1664 } \
1665 break;
1666
1667 // The shift key should affect the output sequence.
1668#define MATCH_KEYPAD(vk, normal, shifted) \
1669 case (vk): \
1670 { \
1671 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1672 (shifted)); \
1673 } \
1674 break;
1675
1676 // The shift key and other modifier keys should affect the output
1677 // sequence.
1678#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1679 case (vk): \
1680 { \
1681 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1682 control_key_state, (normal), (shifted)); \
1683 } \
1684 break;
1685
1686#define ESC "\x1b"
1687#define CSI ESC "["
1688#define SS3 ESC "O"
1689
1690 // Only support normal mode, not application mode.
1691
1692 // Enhanced keys:
1693 // * 6-pack: insert, delete, home, end, page up, page down
1694 // * cursor keys: up, down, right, left
1695 // * keypad: divide, enter
1696 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1697 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1698 if (_is_enhanced_key(control_key_state)) {
1699 switch (vk) {
1700 case VK_RETURN: // Enter key on keypad
1701 if (_is_ctrl_pressed(control_key_state)) {
1702 seqstr = "\n";
1703 } else {
1704 seqstr = "\r";
1705 }
1706 break;
1707
1708 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1709 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1710
1711 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1712 // will be fixed soon to match xterm which sends CSI "F" and
1713 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1714 MATCH(VK_END, CSI "F");
1715 MATCH(VK_HOME, CSI "H");
1716
1717 MATCH_MODIFIER(VK_LEFT, CSI "D");
1718 MATCH_MODIFIER(VK_UP, CSI "A");
1719 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1720 MATCH_MODIFIER(VK_DOWN, CSI "B");
1721
1722 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1723 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1724
1725 MATCH(VK_DIVIDE, "/");
1726 }
1727 } else { // Non-enhanced keys:
1728 switch (vk) {
1729 case VK_BACK: // backspace
1730 if (_is_alt_pressed(control_key_state)) {
1731 seqstr = ESC "\x7f";
1732 } else {
1733 seqstr = "\x7f";
1734 }
1735 break;
1736
1737 case VK_TAB:
1738 if (_is_shift_pressed(control_key_state)) {
1739 seqstr = CSI "Z";
1740 } else {
1741 seqstr = "\t";
1742 }
1743 break;
1744
1745 // Number 5 key in keypad when NumLock is off, or if NumLock is
1746 // on and Shift is down.
1747 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1748
1749 case VK_RETURN: // Enter key on main keyboard
1750 if (_is_alt_pressed(control_key_state)) {
1751 seqstr = ESC "\n";
1752 } else if (_is_ctrl_pressed(control_key_state)) {
1753 seqstr = "\n";
1754 } else {
1755 seqstr = "\r";
1756 }
1757 break;
1758
1759 // VK_ESCAPE: Don't do any special handling. The OS uses many
1760 // of the sequences with Escape and many of the remaining
1761 // sequences don't produce bKeyDown messages, only !bKeyDown
1762 // for whatever reason.
1763
1764 case VK_SPACE:
1765 if (_is_alt_pressed(control_key_state)) {
1766 seqstr = ESC " ";
1767 } else if (_is_ctrl_pressed(control_key_state)) {
1768 seqbuf[0] = '\0'; // NULL char
1769 seqbuflen = 1;
1770 } else {
1771 seqstr = " ";
1772 }
1773 break;
1774
1775 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1776 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1777
1778 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1779 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1780
1781 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1782 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1783 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1784 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1785
1786 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1787 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1788 _get_decimal_char());
1789
1790 case 0x30: // 0
1791 case 0x31: // 1
1792 case 0x39: // 9
1793 case VK_OEM_1: // ;:
1794 case VK_OEM_PLUS: // =+
1795 case VK_OEM_COMMA: // ,<
1796 case VK_OEM_PERIOD: // .>
1797 case VK_OEM_7: // '"
1798 case VK_OEM_102: // depends on keyboard, could be <> or \|
1799 case VK_OEM_2: // /?
1800 case VK_OEM_3: // `~
1801 case VK_OEM_4: // [{
1802 case VK_OEM_5: // \|
1803 case VK_OEM_6: // ]}
1804 {
1805 seqbuflen = _get_control_character(seqbuf, key_event,
1806 control_key_state);
1807
1808 if (_is_alt_pressed(control_key_state)) {
1809 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1810 }
1811 }
1812 break;
1813
1814 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001815 case 0x33: // 3
1816 case 0x34: // 4
1817 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001818 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001819 case 0x37: // 7
1820 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001821 case VK_OEM_MINUS: // -_
1822 {
1823 seqbuflen = _get_control_character(seqbuf, key_event,
1824 control_key_state);
1825
1826 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1827 // prefix with escape.
1828 if (_is_alt_pressed(control_key_state) &&
1829 !(_is_ctrl_pressed(control_key_state) &&
1830 !_is_shift_pressed(control_key_state))) {
1831 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1832 }
1833 }
1834 break;
1835
Spencer Lowbeb61982015-03-01 15:06:21 -08001836 case 0x41: // a
1837 case 0x42: // b
1838 case 0x43: // c
1839 case 0x44: // d
1840 case 0x45: // e
1841 case 0x46: // f
1842 case 0x47: // g
1843 case 0x48: // h
1844 case 0x49: // i
1845 case 0x4a: // j
1846 case 0x4b: // k
1847 case 0x4c: // l
1848 case 0x4d: // m
1849 case 0x4e: // n
1850 case 0x4f: // o
1851 case 0x50: // p
1852 case 0x51: // q
1853 case 0x52: // r
1854 case 0x53: // s
1855 case 0x54: // t
1856 case 0x55: // u
1857 case 0x56: // v
1858 case 0x57: // w
1859 case 0x58: // x
1860 case 0x59: // y
1861 case 0x5a: // z
1862 {
1863 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1864 control_key_state);
1865
1866 // If Alt is pressed, then prefix with escape.
1867 if (_is_alt_pressed(control_key_state)) {
1868 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1869 }
1870 }
1871 break;
1872
1873 // These virtual key codes are generated by the keys on the
1874 // keypad *when NumLock is on* and *Shift is up*.
1875 MATCH(VK_NUMPAD0, "0");
1876 MATCH(VK_NUMPAD1, "1");
1877 MATCH(VK_NUMPAD2, "2");
1878 MATCH(VK_NUMPAD3, "3");
1879 MATCH(VK_NUMPAD4, "4");
1880 MATCH(VK_NUMPAD5, "5");
1881 MATCH(VK_NUMPAD6, "6");
1882 MATCH(VK_NUMPAD7, "7");
1883 MATCH(VK_NUMPAD8, "8");
1884 MATCH(VK_NUMPAD9, "9");
1885
1886 MATCH(VK_MULTIPLY, "*");
1887 MATCH(VK_ADD, "+");
1888 MATCH(VK_SUBTRACT, "-");
1889 // VK_DECIMAL is generated by the . key on the keypad *when
1890 // NumLock is on* and *Shift is up* and the sequence is not
1891 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1892 // Windows Security screen to come up).
1893 case VK_DECIMAL:
1894 // U.S. English uses '.', Germany German uses ','.
1895 seqbuflen = _get_non_control_char(seqbuf, key_event,
1896 control_key_state);
1897 break;
1898
1899 MATCH_MODIFIER(VK_F1, SS3 "P");
1900 MATCH_MODIFIER(VK_F2, SS3 "Q");
1901 MATCH_MODIFIER(VK_F3, SS3 "R");
1902 MATCH_MODIFIER(VK_F4, SS3 "S");
1903 MATCH_MODIFIER(VK_F5, CSI "15~");
1904 MATCH_MODIFIER(VK_F6, CSI "17~");
1905 MATCH_MODIFIER(VK_F7, CSI "18~");
1906 MATCH_MODIFIER(VK_F8, CSI "19~");
1907 MATCH_MODIFIER(VK_F9, CSI "20~");
1908 MATCH_MODIFIER(VK_F10, CSI "21~");
1909 MATCH_MODIFIER(VK_F11, CSI "23~");
1910 MATCH_MODIFIER(VK_F12, CSI "24~");
1911
1912 MATCH_MODIFIER(VK_F13, CSI "25~");
1913 MATCH_MODIFIER(VK_F14, CSI "26~");
1914 MATCH_MODIFIER(VK_F15, CSI "28~");
1915 MATCH_MODIFIER(VK_F16, CSI "29~");
1916 MATCH_MODIFIER(VK_F17, CSI "31~");
1917 MATCH_MODIFIER(VK_F18, CSI "32~");
1918 MATCH_MODIFIER(VK_F19, CSI "33~");
1919 MATCH_MODIFIER(VK_F20, CSI "34~");
1920
1921 // MATCH_MODIFIER(VK_F21, ???);
1922 // MATCH_MODIFIER(VK_F22, ???);
1923 // MATCH_MODIFIER(VK_F23, ???);
1924 // MATCH_MODIFIER(VK_F24, ???);
1925 }
1926 }
1927
1928#undef MATCH
1929#undef MATCH_MODIFIER
1930#undef MATCH_KEYPAD
1931#undef MATCH_MODIFIER_KEYPAD
1932#undef ESC
1933#undef CSI
1934#undef SS3
1935
1936 const char* out;
1937 size_t outlen;
1938
1939 // Check for output in any of:
1940 // * seqstr is set (and strlen can be used to determine the length).
1941 // * seqbuf and seqbuflen are set
1942 // Fallback to ch from Windows.
1943 if (seqstr != NULL) {
1944 out = seqstr;
1945 outlen = strlen(seqstr);
1946 } else if (seqbuflen > 0) {
1947 out = seqbuf;
1948 outlen = seqbuflen;
1949 } else if (ch != '\0') {
1950 // Use whatever Windows told us it is.
1951 seqbuf[0] = ch;
1952 seqbuflen = 1;
1953 out = seqbuf;
1954 outlen = seqbuflen;
1955 } else {
1956 // No special handling for the virtual key code and Windows isn't
1957 // telling us a character code, then we don't know how to translate
1958 // the key press.
1959 //
1960 // Consume the input and 'continue' to cause us to get a new key
1961 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07001962 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08001963 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08001964 continue;
1965 }
1966
Spencer Low9c8f7462015-11-10 19:17:16 -08001967 // put output wRepeatCount times into g_console_input_buffer
1968 while (key_event->wRepeatCount-- > 0) {
1969 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08001970 }
1971
Spencer Low9c8f7462015-11-10 19:17:16 -08001972 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08001973 }
1974}
1975
1976static DWORD _old_console_mode; // previous GetConsoleMode() result
1977static HANDLE _console_handle; // when set, console mode should be restored
1978
Elliott Hughesa8265792015-11-03 11:18:40 -08001979void stdin_raw_init() {
1980 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08001981 if (in == nullptr) {
1982 return;
1983 }
Spencer Lowbeb61982015-03-01 15:06:21 -08001984
Elliott Hughesa8265792015-11-03 11:18:40 -08001985 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
1986 // calling the process Ctrl-C routine (configured by
1987 // SetConsoleCtrlHandler()).
1988 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
1989 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
1990 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08001991 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
1992 ENABLE_LINE_INPUT |
1993 ENABLE_ECHO_INPUT);
1994 // Enable ENABLE_WINDOW_INPUT to get window resizes.
1995 new_console_mode |= ENABLE_WINDOW_INPUT;
1996
1997 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08001998 // This really should not fail.
1999 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002000 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002001 }
Elliott Hughesa8265792015-11-03 11:18:40 -08002002
2003 // Once this is set, it means that stdin has been configured for
2004 // reading from and that the old console mode should be restored later.
2005 _console_handle = in;
2006
2007 // Note that we don't need to configure C Runtime line-ending
2008 // translation because _console_read() does not call the C Runtime to
2009 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002010}
2011
Elliott Hughesa8265792015-11-03 11:18:40 -08002012void stdin_raw_restore() {
2013 if (_console_handle != NULL) {
2014 const HANDLE in = _console_handle;
2015 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002016
Elliott Hughesa8265792015-11-03 11:18:40 -08002017 if (!SetConsoleMode(in, _old_console_mode)) {
2018 // This really should not fail.
2019 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002020 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002021 }
2022 }
2023}
2024
Spencer Low55441402015-11-07 17:34:39 -08002025// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2026int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002027 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2028 // If it is a request to read from stdin, and stdin_raw_init() has been
2029 // called, and it successfully configured the console, then read from
2030 // the console using Win32 console APIs and partially emulate a unix
2031 // terminal.
2032 return _console_read(_console_handle, buf, len);
2033 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002034 // On older versions of Windows (definitely 7, definitely not 10),
2035 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002036 // we need to limit the read size.
2037 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002038 len = 4096;
2039 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002040 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002041 // can do LF/CR translation (which is overridable with _setmode()).
2042 // Undefine the macro that is set in sysdeps.h which bans calls to
2043 // plain read() in favor of unix_read() or adb_read().
2044#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002045#undef read
2046 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002047#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002048 }
2049}
Spencer Low6815c072015-05-11 01:08:48 -07002050
2051/**************************************************************************/
2052/**************************************************************************/
2053/***** *****/
2054/***** Unicode support *****/
2055/***** *****/
2056/**************************************************************************/
2057/**************************************************************************/
2058
2059// This implements support for using files with Unicode filenames and for
2060// outputting Unicode text to a Win32 console window. This is inspired from
2061// http://utf8everywhere.org/.
2062//
2063// Background
2064// ----------
2065//
2066// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2067// filenames to APIs such as open(). This works because filenames are largely
2068// opaque 'cookies' (perhaps excluding path separators).
2069//
2070// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2071// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2072// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2073// CreateFile() API is really just a macro that adds the W/A based on whether
2074// the UNICODE preprocessor symbol is defined).
2075//
2076// Options
2077// -------
2078//
2079// Thus, to write a portable program, there are a few options:
2080//
2081// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2082// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2083// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2084// open() API.
2085//
2086// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2087// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2088// potentially touching a lot of code.
2089//
2090// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2091// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2092// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2093// or C Runtime API.
2094//
2095// The Choice
2096// ----------
2097//
Spencer Low50f5bf12015-11-12 15:20:15 -08002098// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2099// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002100// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002101// args that are passed to main() at the beginning of program startup. We also use
2102// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002103// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2104//
2105// Unicode console output
2106// ----------------------
2107//
2108// The way to output Unicode to a Win32 console window is to call
2109// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002110// such as Lucida Console or Consolas, and in the case of East Asian languages
2111// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2112// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2113// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002114//
2115// The problem is getting the C Runtime to make fprintf and related APIs call
2116// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2117// promising, but the various modes have issues:
2118//
2119// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2120// UTF-16 do not display properly.
2121// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2122// totally wrong.
2123// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2124// handler to be called (upon a later I/O call), aborting the process.
2125// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2126// to output nothing.
2127//
2128// So the only solution is to write our own adb_fprintf() that converts UTF-8
2129// to UTF-16 and then calls WriteConsoleW().
2130
2131
Spencer Low6815c072015-05-11 01:08:48 -07002132// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2133// be passed to main().
2134NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2135 narrow_args = new char*[argc + 1];
2136
2137 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002138 std::string arg_narrow;
2139 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2140 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2141 }
2142 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002143 }
2144 narrow_args[argc] = nullptr; // terminate
2145}
2146
2147NarrowArgs::~NarrowArgs() {
2148 if (narrow_args != nullptr) {
2149 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2150 free(*argp);
2151 }
2152 delete[] narrow_args;
2153 narrow_args = nullptr;
2154 }
2155}
2156
2157int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002158 std::wstring path_wide;
2159 if (!android::base::UTF8ToWide(path, &path_wide)) {
2160 return -1;
2161 }
Spencer Low6815c072015-05-11 01:08:48 -07002162 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002163 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002164 } else {
2165 int mode;
2166 va_list args;
2167 va_start(args, options);
2168 mode = va_arg(args, int);
2169 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002170 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002171 }
2172}
2173
Spencer Low6815c072015-05-11 01:08:48 -07002174// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002175DIR* adb_opendir(const char* path) {
2176 std::wstring path_wide;
2177 if (!android::base::UTF8ToWide(path, &path_wide)) {
2178 return nullptr;
2179 }
2180
Spencer Low6815c072015-05-11 01:08:48 -07002181 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2182 // the fields, but right now all the callers treat the structure as
2183 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002184 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002185}
2186
2187// Version of readdir() that returns UTF-8 paths.
2188struct dirent* adb_readdir(DIR* dir) {
2189 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2190 struct _wdirent* const went = _wreaddir(wdir);
2191 if (went == nullptr) {
2192 return nullptr;
2193 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002194
Spencer Low6815c072015-05-11 01:08:48 -07002195 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002196 std::string name_utf8;
2197 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2198 return nullptr;
2199 }
Spencer Low6815c072015-05-11 01:08:48 -07002200
2201 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2202 // space for UTF-16 wchar_t's) with UTF-8 char's.
2203 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2204
2205 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2206 // Name too big to fit in existing buffer.
2207 errno = ENOMEM;
2208 return nullptr;
2209 }
2210
2211 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2212 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2213 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2214 // bigger than the caller expects because they expect a dirent structure
2215 // which has a smaller d_name field. Ignore this since the caller should be
2216 // resilient.
2217
2218 // Rewrite the UTF-16 d_name field to UTF-8.
2219 strcpy(ent->d_name, name_utf8.c_str());
2220
2221 return ent;
2222}
2223
2224// Version of closedir() to go with our version of adb_opendir().
2225int adb_closedir(DIR* dir) {
2226 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2227}
2228
2229// Version of unlink() that takes a UTF-8 path.
2230int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002231 std::wstring wpath;
2232 if (!android::base::UTF8ToWide(path, &wpath)) {
2233 return -1;
2234 }
Spencer Low6815c072015-05-11 01:08:48 -07002235
2236 int rc = _wunlink(wpath.c_str());
2237
2238 if (rc == -1 && errno == EACCES) {
2239 /* unlink returns EACCES when the file is read-only, so we first */
2240 /* try to make it writable, then unlink again... */
2241 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2242 if (rc == 0)
2243 rc = _wunlink(wpath.c_str());
2244 }
2245 return rc;
2246}
2247
2248// Version of mkdir() that takes a UTF-8 path.
2249int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002250 std::wstring path_wide;
2251 if (!android::base::UTF8ToWide(path, &path_wide)) {
2252 return -1;
2253 }
2254
2255 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002256}
2257
2258// Version of utime() that takes a UTF-8 path.
2259int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002260 std::wstring path_wide;
2261 if (!android::base::UTF8ToWide(path, &path_wide)) {
2262 return -1;
2263 }
2264
Spencer Low6815c072015-05-11 01:08:48 -07002265 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2266 "utimbuf and _utimbuf should be the same size because they both "
2267 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002268 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002269}
2270
2271// Version of chmod() that takes a UTF-8 path.
2272int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002273 std::wstring path_wide;
2274 if (!android::base::UTF8ToWide(path, &path_wide)) {
2275 return -1;
2276 }
2277
2278 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002279}
2280
Spencer Lowf373c352015-11-15 16:29:36 -08002281// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2282static inline size_t utf8_codepoint_len(uint8_t ch) {
2283 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2284}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002285
Spencer Lowf373c352015-11-15 16:29:36 -08002286namespace internal {
2287
2288// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2289// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2290// remaining_bytes.
2291size_t ParseCompleteUTF8(const char* const first, const char* const last,
2292 std::vector<char>* const remaining_bytes) {
2293 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2294 // Current_after points one byte past the current byte to be examined.
2295 for (const char* current_after = last; current_after != first; --current_after) {
2296 const char* const current = current_after - 1;
2297 const char ch = *current;
2298 const char kHighBit = 0x80u;
2299 const char kTwoHighestBits = 0xC0u;
2300 if ((ch & kHighBit) == 0) { // high bit not set
2301 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2302 // bytes with no leading byte, so return the entire buffer.
2303 break;
2304 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2305 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2306 const size_t bytes_available = last - current;
2307 if (bytes_available < utf8_codepoint_len(ch)) {
2308 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2309 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2310 // to remaining_bytes.
2311 remaining_bytes->insert(remaining_bytes->end(), current, last);
2312 return current - first;
2313 } else {
2314 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2315 // trailing bytes with no lead byte, so return the entire buffer.
2316 break;
2317 }
2318 } else {
2319 // Trailing byte, so keep going backwards looking for the lead byte.
2320 }
2321 }
2322
2323 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2324 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2325 // so that they can be processed.
2326 return last - first;
2327}
2328
2329}
2330
2331// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2332// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2333// This matches the behavior of Linux.
Spencer Lowf373c352015-11-15 16:29:36 -08002334
2335// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2336static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2337 HANDLE console) {
Josh Gaoe7daf572016-09-21 12:37:10 -07002338 static std::mutex& console_output_buffer_lock = *new std::mutex();
2339 static auto& console_output_buffer = *new std::vector<char>();
2340
Spencer Lowf373c352015-11-15 16:29:36 -08002341 const int saved_errno = errno;
2342 std::vector<char> combined_buffer;
2343
2344 // Complete UTF-8 sequences that should be immediately written to the console.
2345 const char* utf8;
2346 size_t utf8_size;
2347
Josh Gaoe7daf572016-09-21 12:37:10 -07002348 {
2349 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2350 if (console_output_buffer.empty()) {
2351 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2352 // common case with plain ASCII), parse buf directly.
2353 utf8 = buf;
2354 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2355 } else {
2356 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2357 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2358 // combined_buffer, then parse it all together.
2359 combined_buffer.swap(console_output_buffer);
2360 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowf373c352015-11-15 16:29:36 -08002361
Josh Gaoe7daf572016-09-21 12:37:10 -07002362 utf8 = combined_buffer.data();
2363 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2364 &console_output_buffer);
2365 }
Spencer Lowf373c352015-11-15 16:29:36 -08002366 }
Spencer Lowf373c352015-11-15 16:29:36 -08002367
2368 std::wstring utf16;
2369
2370 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2371 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2372 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002373 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002374 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002375
2376 // Note that this does not do \n => \r\n translation because that
2377 // doesn't seem necessary for the Windows console. For the Windows
2378 // console \r moves to the beginning of the line and \n moves to a new
2379 // line.
2380
2381 // Flush any stream buffering so that our output is afterwards which
2382 // makes sense because our call is afterwards.
2383 (void)fflush(stream);
2384
2385 // Write UTF-16 to the console.
2386 DWORD written = 0;
Spencer Lowf373c352015-11-15 16:29:36 -08002387 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Low6815c072015-05-11 01:08:48 -07002388 errno = EIO;
2389 return -1;
2390 }
2391
Spencer Lowf373c352015-11-15 16:29:36 -08002392 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2393 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2394 // matches the Linux behavior.
2395 errno = saved_errno;
2396 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002397}
2398
2399// Function prototype because attributes cannot be placed on func definitions.
2400static int _console_vfprintf(const HANDLE console, FILE* stream,
2401 const char *format, va_list ap)
2402 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2403
2404// Internal function to format a UTF-8 string and write it to a Win32 console.
2405// Returns -1 on error.
2406static int _console_vfprintf(const HANDLE console, FILE* stream,
2407 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002408 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002409 std::string output_utf8;
2410
2411 // Format the string.
2412 // This could throw std::bad_alloc.
2413 android::base::StringAppendV(&output_utf8, format, ap);
2414
Spencer Lowf373c352015-11-15 16:29:36 -08002415 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2416 console);
2417 if (result != -1) {
2418 errno = saved_errno;
2419 } else {
2420 // If -1 was returned, errno has been set.
2421 }
2422 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002423}
2424
2425// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2426// Windows console.
2427int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2428 const HANDLE console = _get_console_handle(stream);
2429
2430 // If there is an associated Win32 console, write to it specially,
2431 // otherwise defer to the regular C Runtime, passing it UTF-8.
2432 if (console != NULL) {
2433 return _console_vfprintf(console, stream, format, ap);
2434 } else {
2435 // If vfprintf is a macro, undefine it, so we can call the real
2436 // C Runtime API.
2437#pragma push_macro("vfprintf")
2438#undef vfprintf
2439 return vfprintf(stream, format, ap);
2440#pragma pop_macro("vfprintf")
2441 }
2442}
2443
Spencer Lowf373c352015-11-15 16:29:36 -08002444// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2445int adb_vprintf(const char *format, va_list ap) {
2446 return adb_vfprintf(stdout, format, ap);
2447}
2448
Spencer Low6815c072015-05-11 01:08:48 -07002449// Version of fprintf() that takes UTF-8 and can write Unicode to a
2450// Windows console.
2451int adb_fprintf(FILE *stream, const char *format, ...) {
2452 va_list ap;
2453 va_start(ap, format);
2454 const int result = adb_vfprintf(stream, format, ap);
2455 va_end(ap);
2456
2457 return result;
2458}
2459
2460// Version of printf() that takes UTF-8 and can write Unicode to a
2461// Windows console.
2462int adb_printf(const char *format, ...) {
2463 va_list ap;
2464 va_start(ap, format);
2465 const int result = adb_vfprintf(stdout, format, ap);
2466 va_end(ap);
2467
2468 return result;
2469}
2470
2471// Version of fputs() that takes UTF-8 and can write Unicode to a
2472// Windows console.
2473int adb_fputs(const char* buf, FILE* stream) {
2474 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2475 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002476 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002477 return adb_fprintf(stream, "%s", buf);
2478}
2479
2480// Version of fputc() that takes UTF-8 and can write Unicode to a
2481// Windows console.
2482int adb_fputc(int ch, FILE* stream) {
2483 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002484 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002485 return EOF;
2486 }
2487 // For success, fputc returns the char, cast to unsigned char, then to int.
2488 return static_cast<unsigned char>(ch);
2489}
2490
Spencer Lowf373c352015-11-15 16:29:36 -08002491// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2492int adb_putchar(int ch) {
2493 return adb_fputc(ch, stdout);
2494}
2495
2496// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2497int adb_puts(const char* buf) {
2498 // adb_printf returns -1 on error, which is conveniently the same as EOF
2499 // which puts (and hence adb_puts) should return on error.
2500 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2501 return adb_printf("%s\n", buf);
2502}
2503
Spencer Low6815c072015-05-11 01:08:48 -07002504// Internal function to write UTF-8 to a Win32 console. Returns the number of
2505// items (of length size) written. On error, returns a short item count or 0.
2506static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2507 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002508 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2509 console);
Spencer Low6815c072015-05-11 01:08:48 -07002510 if (result == -1) {
2511 return 0;
2512 }
2513 return result / size;
2514}
2515
2516// Version of fwrite() that takes UTF-8 and can write Unicode to a
2517// Windows console.
2518size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2519 const HANDLE console = _get_console_handle(stream);
2520
2521 // If there is an associated Win32 console, write to it specially,
2522 // otherwise defer to the regular C Runtime, passing it UTF-8.
2523 if (console != NULL) {
2524 return _console_fwrite(ptr, size, nmemb, stream, console);
2525 } else {
2526 // If fwrite is a macro, undefine it, so we can call the real
2527 // C Runtime API.
2528#pragma push_macro("fwrite")
2529#undef fwrite
2530 return fwrite(ptr, size, nmemb, stream);
2531#pragma pop_macro("fwrite")
2532 }
2533}
2534
2535// Version of fopen() that takes a UTF-8 filename and can access a file with
2536// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002537FILE* adb_fopen(const char* path, const char* mode) {
2538 std::wstring path_wide;
2539 if (!android::base::UTF8ToWide(path, &path_wide)) {
2540 return nullptr;
2541 }
2542
2543 std::wstring mode_wide;
2544 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2545 return nullptr;
2546 }
2547
2548 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002549}
2550
Spencer Low50740f52015-09-08 17:13:04 -07002551// Return a lowercase version of the argument. Uses C Runtime tolower() on
2552// each byte which is not UTF-8 aware, and theoretically uses the current C
2553// Runtime locale (which in practice is not changed, so this becomes a ASCII
2554// conversion).
2555static std::string ToLower(const std::string& anycase) {
2556 // copy string
2557 std::string str(anycase);
2558 // transform the copy
2559 std::transform(str.begin(), str.end(), str.begin(), tolower);
2560 return str;
2561}
2562
2563extern "C" int main(int argc, char** argv);
2564
2565// Link with -municode to cause this wmain() to be used as the program
2566// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2567// regular main() with UTF-8 args.
2568extern "C" int wmain(int argc, wchar_t **argv) {
2569 // Convert args from UTF-16 to UTF-8 and pass that to main().
2570 NarrowArgs narrow_args(argc, argv);
2571 return main(argc, narrow_args.data());
2572}
2573
Spencer Low6815c072015-05-11 01:08:48 -07002574// Shadow UTF-8 environment variable name/value pairs that are created from
2575// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07002576// currently updated if putenv, setenv, unsetenv are called. Note that no
2577// thread synchronization is done, but we're called early enough in
2578// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002579static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002580
2581// Make sure that shadow UTF-8 environment variables are setup.
2582static void _ensure_env_setup() {
2583 // If some name/value pairs exist, then we've already done the setup below.
2584 if (g_environ_utf8.size() != 0) {
2585 return;
2586 }
2587
Spencer Low50740f52015-09-08 17:13:04 -07002588 if (_wenviron == nullptr) {
2589 // If _wenviron is null, then -municode probably wasn't used. That
2590 // linker flag will cause the entry point to setup _wenviron. It will
2591 // also require an implementation of wmain() (which we provide above).
2592 fatal("_wenviron is not set, did you link with -municode?");
2593 }
2594
Spencer Low6815c072015-05-11 01:08:48 -07002595 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2596 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2597 // to use the D() macro here because that tracing only works if the
2598 // ADB_TRACE environment variable is setup, but that env var can't be read
2599 // until this code completes.
2600 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2601 wchar_t* const equal = wcschr(*env, L'=');
2602 if (equal == nullptr) {
2603 // Malformed environment variable with no equal sign. Shouldn't
2604 // really happen, but we should be resilient to this.
2605 continue;
2606 }
2607
Spencer Low50f5bf12015-11-12 15:20:15 -08002608 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2609 // var because the program might never even read this particular variable.
2610 std::string name_utf8;
2611 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2612 continue;
2613 }
2614
Spencer Low50740f52015-09-08 17:13:04 -07002615 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002616 name_utf8 = ToLower(name_utf8);
2617
2618 std::string value_utf8;
2619 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2620 continue;
2621 }
2622
2623 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002624
Spencer Low50740f52015-09-08 17:13:04 -07002625 // Don't overwrite a previus env var with the same name. In reality,
2626 // the system probably won't let two env vars with the same name exist
2627 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002628 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002629 }
2630}
2631
2632// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002633// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002634char* adb_getenv(const char* name) {
2635 _ensure_env_setup();
2636
Spencer Low50740f52015-09-08 17:13:04 -07002637 // Case-insensitive search by searching for lowercase name in a map of
2638 // lowercase names.
2639 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002640 if (it == g_environ_utf8.end()) {
2641 return nullptr;
2642 }
2643
2644 return it->second;
2645}
2646
2647// Version of getcwd() that returns the current working directory in UTF-8.
2648char* adb_getcwd(char* buf, int size) {
2649 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2650 if (wbuf == nullptr) {
2651 return nullptr;
2652 }
2653
Spencer Low50f5bf12015-11-12 15:20:15 -08002654 std::string buf_utf8;
2655 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002656 free(wbuf);
2657 wbuf = nullptr;
2658
Spencer Low50f5bf12015-11-12 15:20:15 -08002659 if (!narrow_result) {
2660 return nullptr;
2661 }
2662
Spencer Low6815c072015-05-11 01:08:48 -07002663 // If size was specified, make sure all the chars will fit.
2664 if (size != 0) {
2665 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2666 errno = ERANGE;
2667 return nullptr;
2668 }
2669 }
2670
2671 // If buf was not specified, allocate storage.
2672 if (buf == nullptr) {
2673 if (size == 0) {
2674 size = buf_utf8.length() + 1;
2675 }
2676 buf = reinterpret_cast<char*>(malloc(size));
2677 if (buf == nullptr) {
2678 return nullptr;
2679 }
2680 }
2681
2682 // Destination buffer was allocated with enough space, or we've already
2683 // checked an existing buffer size for enough space.
2684 strcpy(buf, buf_utf8.c_str());
2685
2686 return buf;
2687}