blob: cd7d187aaaf34bb52a5402e506733f131122ae00 [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;
532 for (size_t i = 0; i < nfds; ++i) {
533 FH fh = _fh_from_int(fds[i].fd, __func__);
534 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
535 D("adb_poll received bad FD %d", fds[i].fd);
536 fds[i].revents = POLLNVAL;
537 ++skipped;
538 } else {
539 WSAPOLLFD wsapollfd = {
540 .fd = fh->u.socket,
541 .events = static_cast<short>(fds[i].events)
542 };
543 sockets.push_back(wsapollfd);
544 original.push_back(&fds[i]);
545 }
Spencer Low753d4852015-07-30 23:07:55 -0700546 }
Josh Gaoe7388122016-02-16 17:34:53 -0800547
548 if (sockets.empty()) {
549 return skipped;
550 }
551
552 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
553 if (result == SOCKET_ERROR) {
554 _socket_set_errno(WSAGetLastError());
555 return -1;
556 }
557
558 // Map the results back onto the original set.
559 for (size_t i = 0; i < sockets.size(); ++i) {
560 original[i]->revents = sockets[i].revents;
561 }
562
563 // WSAPoll appears to return the number of unique FDs with avaiable events, instead of how many
564 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
565 // to do. Ignore its result and calculate the proper return value.
566 result = 0;
567 for (size_t i = 0; i < nfds; ++i) {
568 if (fds[i].revents != 0) {
569 ++result;
570 }
571 }
572 return result;
573}
574
575static void _fh_socket_init(FH f) {
576 f->fh_socket = INVALID_SOCKET;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800577}
578
Elliott Hughes6a096932015-04-16 16:47:02 -0700579static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700580 if (f->fh_socket != INVALID_SOCKET) {
581 /* gently tell any peer that we're closing the socket */
582 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
583 // If the socket is not connected, this returns an error. We want to
584 // minimize logging spam, so don't log these errors for now.
585#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700586 D("socket shutdown failed: %s",
David Pursellc573d522016-01-27 08:52:53 -0800587 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700588#endif
589 }
590 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800591 // Don't set errno here, since adb_close will ignore it.
592 const DWORD err = WSAGetLastError();
593 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700594 }
595 f->fh_socket = INVALID_SOCKET;
596 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800597 return 0;
598}
599
Elliott Hughes6a096932015-04-16 16:47:02 -0700600static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800601 errno = EPIPE;
602 return -1;
603}
604
Elliott Hughes6a096932015-04-16 16:47:02 -0700605static int _fh_socket_read(FH f, void* buf, int len) {
606 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800607 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700608 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700609 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
610 // that to reduce spam and confusion.
611 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700612 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800613 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low32625852015-08-11 16:45:32 -0700614 }
Spencer Low753d4852015-07-30 23:07:55 -0700615 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800616 result = -1;
617 }
618 return result;
619}
620
Elliott Hughes6a096932015-04-16 16:47:02 -0700621static int _fh_socket_write(FH f, const void* buf, int len) {
622 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800623 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700624 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700625 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
626 // that to reduce spam and confusion.
627 if (err != WSAEWOULDBLOCK) {
628 D("send fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800629 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low028e1592015-10-18 16:45:09 -0700630 }
Spencer Low753d4852015-07-30 23:07:55 -0700631 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800632 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700633 } else {
634 // According to https://code.google.com/p/chromium/issues/detail?id=27870
635 // Winsock Layered Service Providers may cause this.
636 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
637 << f->name << ", but " << result
638 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639 }
640 return result;
641}
642
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800643/**************************************************************************/
644/**************************************************************************/
645/***** *****/
646/***** replacement for libs/cutils/socket_xxxx.c *****/
647/***** *****/
648/**************************************************************************/
649/**************************************************************************/
650
651#include <winsock2.h>
652
653static int _winsock_init;
654
655static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800656_init_winsock( void )
657{
Spencer Low753d4852015-07-30 23:07:55 -0700658 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700659 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800660 if (!_winsock_init) {
661 WSADATA wsaData;
662 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
663 if (rc != 0) {
David Pursellc573d522016-01-27 08:52:53 -0800664 fatal("adb: could not initialize Winsock: %s",
665 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800666 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800667 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700668
669 // Note that we do not call atexit() to register WSACleanup to be called
670 // at normal process termination because:
671 // 1) When exit() is called, there are still threads actively using
672 // Winsock because we don't cleanly shutdown all threads, so it
673 // doesn't make sense to call WSACleanup() and may cause problems
674 // with those threads.
675 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
676 // calls WSACleanup() which tries to unload a DLL, which tries to
677 // grab the LoaderLock. This conflicts with the device_poll_thread
678 // which holds the LoaderLock because AdbWinApi.dll calls
679 // setupapi.dll which tries to load wintrust.dll which tries to load
680 // crypt32.dll which calls atexit() which tries to acquire the C
681 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800682 }
683}
684
Spencer Lowc7c45612015-09-29 15:05:29 -0700685// Map a socket type to an explicit socket protocol instead of using the socket
686// protocol of 0. Explicit socket protocols are used by most apps and we should
687// do the same to reduce the chance of exercising uncommon code-paths that might
688// have problems or that might load different Winsock service providers that
689// have problems.
690static int GetSocketProtocolFromSocketType(int type) {
691 switch (type) {
692 case SOCK_STREAM:
693 return IPPROTO_TCP;
694 case SOCK_DGRAM:
695 return IPPROTO_UDP;
696 default:
697 LOG(FATAL) << "Unknown socket type: " << type;
698 return 0;
699 }
700}
701
Spencer Low753d4852015-07-30 23:07:55 -0700702int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800703 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800704 SOCKET s;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800705
Josh Gao61eda8d2016-02-18 13:43:55 -0800706 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low753d4852015-07-30 23:07:55 -0700707 if (!f) {
708 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800709 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700710 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800711
Josh Gao61eda8d2016-02-18 13:43:55 -0800712 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800713
714 memset(&addr, 0, sizeof(addr));
715 addr.sin_family = AF_INET;
716 addr.sin_port = htons(port);
717 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
718
Spencer Lowc7c45612015-09-29 15:05:29 -0700719 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao61eda8d2016-02-18 13:43:55 -0800720 if (s == INVALID_SOCKET) {
721 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700722 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800723 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700724 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800725 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700726 return -1;
727 }
728 f->fh_socket = s;
729
Josh Gao61eda8d2016-02-18 13:43:55 -0800730 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700731 // Save err just in case inet_ntoa() or ntohs() changes the last error.
732 const DWORD err = WSAGetLastError();
733 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800734 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
735 android::base::SystemErrorCodeToString(err).c_str());
736 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
737 error->c_str());
738 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800739 return -1;
740 }
741
Spencer Low753d4852015-07-30 23:07:55 -0700742 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800743 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
744 port);
745 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700746 f.release();
747 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800748}
749
Spencer Low753d4852015-07-30 23:07:55 -0700750// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao61eda8d2016-02-18 13:43:55 -0800751static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800752 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800753 SOCKET s;
754 int n;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800755
Josh Gao61eda8d2016-02-18 13:43:55 -0800756 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800757 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700758 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800759 return -1;
760 }
761
Josh Gao61eda8d2016-02-18 13:43:55 -0800762 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800763
764 memset(&addr, 0, sizeof(addr));
765 addr.sin_family = AF_INET;
766 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700767 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800768
Spencer Low753d4852015-07-30 23:07:55 -0700769 // TODO: Consider using dual-stack socket that can simultaneously listen on
770 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700771 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700772 if (s == INVALID_SOCKET) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800773 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700774 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800775 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700776 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800777 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700778 return -1;
779 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800780
781 f->fh_socket = s;
782
Spencer Low32625852015-08-11 16:45:32 -0700783 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
784 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800785 n = 1;
Josh Gao61eda8d2016-02-18 13:43:55 -0800786 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
787 const DWORD err = WSAGetLastError();
788 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
789 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700790 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800791 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700792 return -1;
793 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800794
Josh Gao61eda8d2016-02-18 13:43:55 -0800795 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700796 // Save err just in case inet_ntoa() or ntohs() changes the last error.
797 const DWORD err = WSAGetLastError();
Josh Gao61eda8d2016-02-18 13:43:55 -0800798 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
799 ntohs(addr.sin_port),
800 android::base::SystemErrorCodeToString(err).c_str());
801 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
802 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800803 return -1;
804 }
805 if (type == SOCK_STREAM) {
Josh Gaoa076b152018-03-20 14:25:03 -0700806 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800807 const DWORD err = WSAGetLastError();
808 *error = android::base::StringPrintf(
809 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
810 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
811 error->c_str());
812 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800813 return -1;
814 }
815 }
Spencer Low753d4852015-07-30 23:07:55 -0700816 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800817 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
818 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
819 port);
820 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700821 f.release();
822 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800823}
824
Spencer Low753d4852015-07-30 23:07:55 -0700825int network_loopback_server(int port, int type, std::string* error) {
826 return _network_server(port, type, INADDR_LOOPBACK, error);
827}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800828
Spencer Low753d4852015-07-30 23:07:55 -0700829int network_inaddr_any_server(int port, int type, std::string* error) {
830 return _network_server(port, type, INADDR_ANY, error);
831}
832
833int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
834 unique_fh f(_fh_alloc(&_fh_socket_class));
835 if (!f) {
836 *error = strerror(errno);
837 return -1;
838 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800839
Elliott Hughes43df1092015-07-23 17:12:58 -0700840 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800841
Spencer Low753d4852015-07-30 23:07:55 -0700842 struct addrinfo hints;
843 memset(&hints, 0, sizeof(hints));
844 hints.ai_family = AF_UNSPEC;
845 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700846 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700847
848 char port_str[16];
849 snprintf(port_str, sizeof(port_str), "%d", port);
850
851 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700852
853#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao61eda8d2016-02-18 13:43:55 -0800854// TODO: When the Android SDK tools increases the Windows system
855// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700856#else
Josh Gao61eda8d2016-02-18 13:43:55 -0800857// Otherwise, keep using getaddrinfo(), or do runtime API detection
858// with GetProcAddress("GetAddrInfoW").
Spencer Lowcc467f12015-08-02 18:13:54 -0700859#endif
Spencer Low753d4852015-07-30 23:07:55 -0700860 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800861 const DWORD err = WSAGetLastError();
862 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
863 host.c_str(), port_str,
864 android::base::SystemErrorCodeToString(err).c_str());
865
Yabin Cui815ad882015-09-02 17:44:28 -0700866 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800867 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800868 return -1;
869 }
Elliott Hughes8ac45992016-08-08 12:52:37 -0700870 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low753d4852015-07-30 23:07:55 -0700871 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800872
Spencer Low753d4852015-07-30 23:07:55 -0700873 // TODO: Try all the addresses if there's more than one? This just uses
874 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
875 // which tries all addresses, takes a timeout and more.
Josh Gao61eda8d2016-02-18 13:43:55 -0800876 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
877 if (s == INVALID_SOCKET) {
878 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700879 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800880 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700881 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800882 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800883 return -1;
884 }
885 f->fh_socket = s;
886
Spencer Low753d4852015-07-30 23:07:55 -0700887 // TODO: Implement timeouts for Windows. Seems like the default in theory
888 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao61eda8d2016-02-18 13:43:55 -0800889 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700890 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao61eda8d2016-02-18 13:43:55 -0800891 const DWORD err = WSAGetLastError();
892 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
893 android::base::SystemErrorCodeToString(err).c_str());
894 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
895 port_str, error->c_str());
896 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800897 return -1;
898 }
899
Spencer Low753d4852015-07-30 23:07:55 -0700900 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800901 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
902 port);
903 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
904 fd);
Spencer Low753d4852015-07-30 23:07:55 -0700905 f.release();
906 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800907}
908
Casey Dahlin20238f22016-09-21 14:03:39 -0700909int adb_register_socket(SOCKET s) {
910 FH f = _fh_alloc( &_fh_socket_class );
911 f->fh_socket = s;
912 return _fh_to_int(f);
913}
914
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800915#undef accept
916int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
917{
Spencer Low3a2421b2015-05-22 20:09:06 -0700918 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200919
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800920 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700921 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -0700922 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800923 return -1;
924 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200925
Spencer Low753d4852015-07-30 23:07:55 -0700926 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800927 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700928 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
929 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800930 return -1;
931 }
932
933 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
934 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700935 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700936 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursellc573d522016-01-27 08:52:53 -0800937 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low753d4852015-07-30 23:07:55 -0700938 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800939 return -1;
940 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200941
Spencer Low753d4852015-07-30 23:07:55 -0700942 const int fd = _fh_to_int(fh.get());
943 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -0700944 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -0700945 fh.release();
946 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800947}
948
949
Spencer Low31aafa62015-01-25 14:40:16 -0800950int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800951{
Spencer Low3a2421b2015-05-22 20:09:06 -0700952 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200953
Spencer Low31aafa62015-01-25 14:40:16 -0800954 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700955 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700956 errno = EBADF;
957 return -1;
958 }
Spencer Lowc7c45612015-09-29 15:05:29 -0700959
960 // TODO: Once we can assume Windows Vista or later, if the caller is trying
961 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
962 // auto-tuning.
963
Spencer Low753d4852015-07-30 23:07:55 -0700964 int result = setsockopt( fh->fh_socket, level, optname,
965 reinterpret_cast<const char*>(optval), optlen );
966 if ( result == SOCKET_ERROR ) {
967 const DWORD err = WSAGetLastError();
David Pursellc573d522016-01-27 08:52:53 -0800968 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
969 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700970 _socket_set_errno( err );
971 result = -1;
972 }
973 return result;
974}
975
Josh Gaoe7388122016-02-16 17:34:53 -0800976int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
977 FH fh = _fh_from_int(fd, __func__);
978
979 if (!fh || fh->clazz != &_fh_socket_class) {
980 D("adb_getsockname: invalid fd %d", fd);
981 errno = EBADF;
982 return -1;
983 }
984
Josh Gao4f6f4422017-03-30 13:04:35 -0700985 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gaoe7388122016-02-16 17:34:53 -0800986 if (result == SOCKET_ERROR) {
987 const DWORD err = WSAGetLastError();
988 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
989 android::base::SystemErrorCodeToString(err).c_str());
990 _socket_set_errno(err);
991 result = -1;
992 }
993 return result;
994}
Spencer Low753d4852015-07-30 23:07:55 -0700995
David Pursell19d0c232016-04-07 11:25:48 -0700996int adb_socket_get_local_port(int fd) {
997 sockaddr_storage addr_storage;
998 socklen_t addr_len = sizeof(addr_storage);
999
1000 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1001 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1002 return -1;
1003 }
1004
1005 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1006 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1007 errno = ECONNABORTED;
1008 return -1;
1009 }
1010
1011 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1012}
1013
Spencer Low753d4852015-07-30 23:07:55 -07001014int adb_shutdown(int fd)
1015{
1016 FH f = _fh_from_int(fd, __func__);
1017
1018 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001019 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001020 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001021 return -1;
1022 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001023
Yabin Cui815ad882015-09-02 17:44:28 -07001024 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001025 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1026 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001027 D("socket shutdown fd %d failed: %s", fd,
David Pursellc573d522016-01-27 08:52:53 -08001028 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001029 _socket_set_errno(err);
1030 return -1;
1031 }
1032 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001033}
1034
Josh Gaoe7388122016-02-16 17:34:53 -08001035// Emulate socketpair(2) by binding and connecting to a socket.
1036int adb_socketpair(int sv[2]) {
1037 int server = -1;
1038 int client = -1;
1039 int accepted = -1;
David Pursell19d0c232016-04-07 11:25:48 -07001040 int local_port = -1;
Josh Gaoe7388122016-02-16 17:34:53 -08001041 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001042
Josh Gaoe7388122016-02-16 17:34:53 -08001043 server = network_loopback_server(0, SOCK_STREAM, &error);
1044 if (server < 0) {
1045 D("adb_socketpair: failed to create server: %s", error.c_str());
1046 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001047 }
1048
David Pursell19d0c232016-04-07 11:25:48 -07001049 local_port = adb_socket_get_local_port(server);
1050 if (local_port < 0) {
1051 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gaoe7388122016-02-16 17:34:53 -08001052 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001053 }
David Pursell19d0c232016-04-07 11:25:48 -07001054 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001055
David Pursell19d0c232016-04-07 11:25:48 -07001056 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gaoe7388122016-02-16 17:34:53 -08001057 if (client < 0) {
1058 D("adb_socketpair: failed to connect client: %s", error.c_str());
1059 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001060 }
1061
Josh Gao4f6f4422017-03-30 13:04:35 -07001062 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gaoe7388122016-02-16 17:34:53 -08001063 if (accepted < 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -08001064 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoe7388122016-02-16 17:34:53 -08001065 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001066 }
Josh Gaoe7388122016-02-16 17:34:53 -08001067 adb_close(server);
1068 sv[0] = client;
1069 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001070 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001071
Josh Gaoe7388122016-02-16 17:34:53 -08001072fail:
1073 if (server >= 0) {
1074 adb_close(server);
1075 }
1076 if (client >= 0) {
1077 adb_close(client);
1078 }
1079 if (accepted >= 0) {
1080 adb_close(accepted);
1081 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001082 return -1;
1083}
1084
Josh Gaoe7388122016-02-16 17:34:53 -08001085bool set_file_block_mode(int fd, bool block) {
1086 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001087
Josh Gaoe7388122016-02-16 17:34:53 -08001088 if (!fh || !fh->used) {
1089 errno = EBADF;
Casey Dahlin20238f22016-09-21 14:03:39 -07001090 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gaoe7388122016-02-16 17:34:53 -08001091 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001092 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001093
Josh Gaoe7388122016-02-16 17:34:53 -08001094 if (fh->clazz == &_fh_socket_class) {
1095 u_long x = !block;
1096 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin20238f22016-09-21 14:03:39 -07001097 int error = WSAGetLastError();
1098 _socket_set_errno(error);
1099 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gaoe7388122016-02-16 17:34:53 -08001100 return false;
1101 }
1102 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001103 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001104 errno = ENOTSOCK;
Casey Dahlin20238f22016-09-21 14:03:39 -07001105 D("Setting nonblocking on non-socket %d", fd);
Josh Gaoe7388122016-02-16 17:34:53 -08001106 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001107 }
1108}
1109
David Pursellc25a34e2016-02-22 14:27:23 -08001110bool set_tcp_keepalive(int fd, int interval_sec) {
1111 FH fh = _fh_from_int(fd, __func__);
1112
1113 if (!fh || fh->clazz != &_fh_socket_class) {
1114 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1115 errno = EBADF;
1116 return false;
1117 }
1118
1119 tcp_keepalive keepalive;
1120 keepalive.onoff = (interval_sec > 0);
1121 keepalive.keepalivetime = interval_sec * 1000;
1122 keepalive.keepaliveinterval = interval_sec * 1000;
1123
1124 DWORD bytes_returned = 0;
1125 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1126 &bytes_returned, nullptr, nullptr) != 0) {
1127 const DWORD err = WSAGetLastError();
1128 D("set_tcp_keepalive(%d) failed: %s", fd,
1129 android::base::SystemErrorCodeToString(err).c_str());
1130 _socket_set_errno(err);
1131 return false;
1132 }
1133
1134 return true;
1135}
1136
Spencer Lowbeb61982015-03-01 15:06:21 -08001137/**************************************************************************/
1138/**************************************************************************/
1139/***** *****/
1140/***** Console Window Terminal Emulation *****/
1141/***** *****/
1142/**************************************************************************/
1143/**************************************************************************/
1144
1145// This reads input from a Win32 console window and translates it into Unix
1146// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1147// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1148// is emulated instead of xterm because it is probably more popular than xterm:
1149// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1150// supports modern fonts, etc. It seems best to emulate the terminal that most
1151// Android developers use because they'll fix apps (the shell, etc.) to keep
1152// working with that terminal's emulation.
1153//
1154// The point of this emulation is not to be perfect or to solve all issues with
1155// console windows on Windows, but to be better than the original code which
1156// just called read() (which called ReadFile(), which called ReadConsoleA())
1157// which did not support Ctrl-C, tab completion, shell input line editing
1158// keys, server echo, and more.
1159//
1160// This implementation reconfigures the console with SetConsoleMode(), then
1161// calls ReadConsoleInput() to get raw input which it remaps to Unix
1162// terminal-style sequences which is returned via unix_read() which is used
1163// by the 'adb shell' command.
1164//
1165// Code organization:
1166//
David Pursell58805362015-10-28 14:29:51 -07001167// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001168// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1169// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1170// * _console_read() is the main code of the emulation.
1171
David Pursell58805362015-10-28 14:29:51 -07001172// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1173// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1174// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1175static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1176 // First check isatty(); this is very fast and eliminates most non-console
1177 // FDs, but returns 1 for both consoles and character devices like NUL.
1178#pragma push_macro("isatty")
1179#undef isatty
1180 if (!isatty(fd)) {
1181 return nullptr;
1182 }
1183#pragma pop_macro("isatty")
1184
1185 // To differentiate between character devices and consoles we need to get
1186 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1187 // GENERIC_READ permissions.
1188 const intptr_t intptr_handle = _get_osfhandle(fd);
1189 if (intptr_handle == -1) {
1190 return nullptr;
1191 }
1192 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1193 DWORD temp_mode = 0;
1194 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1195 return nullptr;
1196 }
1197
1198 return handle;
1199}
1200
1201// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1202static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001203 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1204 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001205 const int fd = fileno(stream);
1206 if (fd < 0) {
1207 return nullptr;
1208 }
1209 return _get_console_handle(fd);
1210}
1211
1212int unix_isatty(int fd) {
1213 return _get_console_handle(fd) ? 1 : 0;
1214}
Spencer Lowbeb61982015-03-01 15:06:21 -08001215
Spencer Low9c8f7462015-11-10 19:17:16 -08001216// Get the next KEY_EVENT_RECORD that should be processed.
1217static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001218 for (;;) {
1219 DWORD read_count = 0;
1220 memset(input_record, 0, sizeof(*input_record));
1221 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001222 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001223 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001224 errno = EIO;
1225 return false;
1226 }
1227
1228 if (read_count == 0) { // should be impossible
1229 fatal("ReadConsoleInputA returned 0");
1230 }
1231
1232 if (read_count != 1) { // should be impossible
1233 fatal("ReadConsoleInputA did not return one input record");
1234 }
1235
Spencer Low55441402015-11-07 17:34:39 -08001236 // If the console window is resized, emulate SIGWINCH by breaking out
1237 // of read() with errno == EINTR. Note that there is no event on
1238 // vertical resize because we don't give the console our own custom
1239 // screen buffer (with CreateConsoleScreenBuffer() +
1240 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1241 // supports scrollback, but doesn't seem to raise an event for vertical
1242 // window resize.
1243 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1244 errno = EINTR;
1245 return false;
1246 }
1247
Spencer Lowbeb61982015-03-01 15:06:21 -08001248 if ((input_record->EventType == KEY_EVENT) &&
1249 (input_record->Event.KeyEvent.bKeyDown)) {
1250 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1251 fatal("ReadConsoleInputA returned a key event with zero repeat"
1252 " count");
1253 }
1254
1255 // Got an interesting INPUT_RECORD, so return
1256 return true;
1257 }
1258 }
1259}
1260
Spencer Lowbeb61982015-03-01 15:06:21 -08001261static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1262 return (control_key_state & SHIFT_PRESSED) != 0;
1263}
1264
1265static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1266 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1267}
1268
1269static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1270 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1271}
1272
1273static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1274 return (control_key_state & NUMLOCK_ON) != 0;
1275}
1276
1277static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1278 return (control_key_state & CAPSLOCK_ON) != 0;
1279}
1280
1281static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1282 return (control_key_state & ENHANCED_KEY) != 0;
1283}
1284
1285// Constants from MSDN for ToAscii().
1286static const BYTE TOASCII_KEY_OFF = 0x00;
1287static const BYTE TOASCII_KEY_DOWN = 0x80;
1288static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1289
1290// Given a key event, ignore a modifier key and return the character that was
1291// entered without the modifier. Writes to *ch and returns the number of bytes
1292// written.
1293static size_t _get_char_ignoring_modifier(char* const ch,
1294 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1295 const WORD modifier) {
1296 // If there is no character from Windows, try ignoring the specified
1297 // modifier and look for a character. Note that if AltGr is being used,
1298 // there will be a character from Windows.
1299 if (key_event->uChar.AsciiChar == '\0') {
1300 // Note that we read the control key state from the passed in argument
1301 // instead of from key_event since the argument has been normalized.
1302 if (((modifier == VK_SHIFT) &&
1303 _is_shift_pressed(control_key_state)) ||
1304 ((modifier == VK_CONTROL) &&
1305 _is_ctrl_pressed(control_key_state)) ||
1306 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1307
1308 BYTE key_state[256] = {0};
1309 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1310 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1311 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1312 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1313 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1314 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1315 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1316 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1317
1318 // cause this modifier to be ignored
1319 key_state[modifier] = TOASCII_KEY_OFF;
1320
1321 WORD translated = 0;
1322 if (ToAscii(key_event->wVirtualKeyCode,
1323 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1324 // Ignoring the modifier, we found a character.
1325 *ch = (CHAR)translated;
1326 return 1;
1327 }
1328 }
1329 }
1330
1331 // Just use whatever Windows told us originally.
1332 *ch = key_event->uChar.AsciiChar;
1333
1334 // If the character from Windows is NULL, return a size of zero.
1335 return (*ch == '\0') ? 0 : 1;
1336}
1337
1338// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1339// but taking into account the shift key. This is because for a sequence like
1340// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1341// we want to find the character ')'.
1342//
1343// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1344// because it is the default key-sequence to switch the input language.
1345// This is configurable in the Region and Language control panel.
1346static __inline__ size_t _get_non_control_char(char* const ch,
1347 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1348 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1349 VK_CONTROL);
1350}
1351
1352// Get without Alt.
1353static __inline__ size_t _get_non_alt_char(char* const ch,
1354 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1355 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1356 VK_MENU);
1357}
1358
1359// Ignore the control key, find the character from Windows, and apply any
1360// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1361// *pch and returns number of bytes written.
1362static size_t _get_control_character(char* const pch,
1363 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1364 const size_t len = _get_non_control_char(pch, key_event,
1365 control_key_state);
1366
1367 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1368 char ch = *pch;
1369 switch (ch) {
1370 case '2':
1371 case '@':
1372 case '`':
1373 ch = '\0';
1374 break;
1375 case '3':
1376 case '[':
1377 case '{':
1378 ch = '\x1b';
1379 break;
1380 case '4':
1381 case '\\':
1382 case '|':
1383 ch = '\x1c';
1384 break;
1385 case '5':
1386 case ']':
1387 case '}':
1388 ch = '\x1d';
1389 break;
1390 case '6':
1391 case '^':
1392 case '~':
1393 ch = '\x1e';
1394 break;
1395 case '7':
1396 case '-':
1397 case '_':
1398 ch = '\x1f';
1399 break;
1400 case '8':
1401 ch = '\x7f';
1402 break;
1403 case '/':
1404 if (!_is_alt_pressed(control_key_state)) {
1405 ch = '\x1f';
1406 }
1407 break;
1408 case '?':
1409 if (!_is_alt_pressed(control_key_state)) {
1410 ch = '\x7f';
1411 }
1412 break;
1413 }
1414 *pch = ch;
1415 }
1416
1417 return len;
1418}
1419
1420static DWORD _normalize_altgr_control_key_state(
1421 const KEY_EVENT_RECORD* const key_event) {
1422 DWORD control_key_state = key_event->dwControlKeyState;
1423
1424 // If we're in an AltGr situation where the AltGr key is down (depending on
1425 // the keyboard layout, that might be the physical right alt key which
1426 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1427 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1428 // a character (which indicates that there was an AltGr mapping), then act
1429 // as if alt and control are not really down for the purposes of modifiers.
1430 // This makes it so that if the user with, say, a German keyboard layout
1431 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1432 // output the key and we don't see the Alt and Ctrl keys.
1433 if (_is_ctrl_pressed(control_key_state) &&
1434 _is_alt_pressed(control_key_state)
1435 && (key_event->uChar.AsciiChar != '\0')) {
1436 // Try to remove as few bits as possible to improve our chances of
1437 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1438 // Left-Alt + Right-Ctrl + AltGr.
1439 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1440 // Remove Right-Alt.
1441 control_key_state &= ~RIGHT_ALT_PRESSED;
1442 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1443 // pressed, Left-Ctrl is almost always set, except if the user
1444 // presses Right-Ctrl, then AltGr (in that specific order) for
1445 // whatever reason. At any rate, make sure the bit is not set.
1446 control_key_state &= ~LEFT_CTRL_PRESSED;
1447 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1448 // Remove Left-Alt.
1449 control_key_state &= ~LEFT_ALT_PRESSED;
1450 // Whichever Ctrl key is down, remove it from the state. We only
1451 // remove one key, to improve our chances of detecting the
1452 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1453 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1454 // Remove Left-Ctrl.
1455 control_key_state &= ~LEFT_CTRL_PRESSED;
1456 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1457 // Remove Right-Ctrl.
1458 control_key_state &= ~RIGHT_CTRL_PRESSED;
1459 }
1460 }
1461
1462 // Note that this logic isn't 100% perfect because Windows doesn't
1463 // allow us to detect all combinations because a physical AltGr key
1464 // press shows up as two bits, plus some combinations are ambiguous
1465 // about what is actually physically pressed.
1466 }
1467
1468 return control_key_state;
1469}
1470
1471// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1472// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1473// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1474// appropriately.
1475static DWORD _normalize_keypad_control_key_state(const WORD vk,
1476 const DWORD control_key_state) {
1477 if (!_is_numlock_on(control_key_state)) {
1478 return control_key_state;
1479 }
1480 if (!_is_enhanced_key(control_key_state)) {
1481 switch (vk) {
1482 case VK_INSERT: // 0
1483 case VK_DELETE: // .
1484 case VK_END: // 1
1485 case VK_DOWN: // 2
1486 case VK_NEXT: // 3
1487 case VK_LEFT: // 4
1488 case VK_CLEAR: // 5
1489 case VK_RIGHT: // 6
1490 case VK_HOME: // 7
1491 case VK_UP: // 8
1492 case VK_PRIOR: // 9
1493 return control_key_state | SHIFT_PRESSED;
1494 }
1495 }
1496
1497 return control_key_state;
1498}
1499
1500static const char* _get_keypad_sequence(const DWORD control_key_state,
1501 const char* const normal, const char* const shifted) {
1502 if (_is_shift_pressed(control_key_state)) {
1503 // Shift is pressed and NumLock is off
1504 return shifted;
1505 } else {
1506 // Shift is not pressed and NumLock is off, or,
1507 // Shift is pressed and NumLock is on, in which case we want the
1508 // NumLock and Shift to neutralize each other, thus, we want the normal
1509 // sequence.
1510 return normal;
1511 }
1512 // If Shift is not pressed and NumLock is on, a different virtual key code
1513 // is returned by Windows, which can be taken care of by a different case
1514 // statement in _console_read().
1515}
1516
1517// Write sequence to buf and return the number of bytes written.
1518static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1519 DWORD control_key_state, const char* const normal) {
1520 // Copy the base sequence into buf.
1521 const size_t len = strlen(normal);
1522 memcpy(buf, normal, len);
1523
1524 int code = 0;
1525
1526 control_key_state = _normalize_keypad_control_key_state(vk,
1527 control_key_state);
1528
1529 if (_is_shift_pressed(control_key_state)) {
1530 code |= 0x1;
1531 }
1532 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1533 code |= 0x2;
1534 }
1535 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1536 code |= 0x4;
1537 }
1538 // If some modifier was held down, then we need to insert the modifier code
1539 if (code != 0) {
1540 if (len == 0) {
1541 // Should be impossible because caller should pass a string of
1542 // non-zero length.
1543 return 0;
1544 }
1545 size_t index = len - 1;
1546 const char lastChar = buf[index];
1547 if (lastChar != '~') {
1548 buf[index++] = '1';
1549 }
1550 buf[index++] = ';'; // modifier separator
1551 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1552 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1553 buf[index++] = '1' + code;
1554 buf[index++] = lastChar; // move ~ (or other last char) to the end
1555 return index;
1556 }
1557 return len;
1558}
1559
1560// Write sequence to buf and return the number of bytes written.
1561static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1562 const DWORD control_key_state, const char* const normal,
1563 const char shifted) {
1564 if (_is_shift_pressed(control_key_state)) {
1565 // Shift is pressed and NumLock is off
1566 if (shifted != '\0') {
1567 buf[0] = shifted;
1568 return sizeof(buf[0]);
1569 } else {
1570 return 0;
1571 }
1572 } else {
1573 // Shift is not pressed and NumLock is off, or,
1574 // Shift is pressed and NumLock is on, in which case we want the
1575 // NumLock and Shift to neutralize each other, thus, we want the normal
1576 // sequence.
1577 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1578 }
1579 // If Shift is not pressed and NumLock is on, a different virtual key code
1580 // is returned by Windows, which can be taken care of by a different case
1581 // statement in _console_read().
1582}
1583
1584// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1585// Standard German. Figure this out at runtime so we know what to output for
1586// Shift-VK_DELETE.
1587static char _get_decimal_char() {
1588 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1589}
1590
1591// Prefix the len bytes in buf with the escape character, and then return the
1592// new buffer length.
1593size_t _escape_prefix(char* const buf, const size_t len) {
1594 // If nothing to prefix, don't do anything. We might be called with
1595 // len == 0, if alt was held down with a dead key which produced nothing.
1596 if (len == 0) {
1597 return 0;
1598 }
1599
1600 memmove(&buf[1], buf, len);
1601 buf[0] = '\x1b';
1602 return len + 1;
1603}
1604
Spencer Low9c8f7462015-11-10 19:17:16 -08001605// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001606static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001607
1608// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1609// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001610static int _console_read(const HANDLE console, void* buf, size_t len) {
1611 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001612 // Read of zero bytes should not block waiting for something from the console.
1613 if (len == 0) {
1614 return 0;
1615 }
1616
1617 // Flush as much as possible from input buffer.
1618 if (!g_console_input_buffer.empty()) {
1619 const int bytes_read = std::min(len, g_console_input_buffer.size());
1620 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1621 const auto begin = g_console_input_buffer.begin();
1622 g_console_input_buffer.erase(begin, begin + bytes_read);
1623 return bytes_read;
1624 }
1625
1626 // Read from the actual console. This may block until input.
1627 INPUT_RECORD input_record;
1628 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001629 return -1;
1630 }
1631
Spencer Low9c8f7462015-11-10 19:17:16 -08001632 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001633 const WORD vk = key_event->wVirtualKeyCode;
1634 const CHAR ch = key_event->uChar.AsciiChar;
1635 const DWORD control_key_state = _normalize_altgr_control_key_state(
1636 key_event);
1637
1638 // The following emulation code should write the output sequence to
1639 // either seqstr or to seqbuf and seqbuflen.
1640 const char* seqstr = NULL; // NULL terminated C-string
1641 // Enough space for max sequence string below, plus modifiers and/or
1642 // escape prefix.
1643 char seqbuf[16];
1644 size_t seqbuflen = 0; // Space used in seqbuf.
1645
1646#define MATCH(vk, normal) \
1647 case (vk): \
1648 { \
1649 seqstr = (normal); \
1650 } \
1651 break;
1652
1653 // Modifier keys should affect the output sequence.
1654#define MATCH_MODIFIER(vk, normal) \
1655 case (vk): \
1656 { \
1657 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1658 control_key_state, (normal)); \
1659 } \
1660 break;
1661
1662 // The shift key should affect the output sequence.
1663#define MATCH_KEYPAD(vk, normal, shifted) \
1664 case (vk): \
1665 { \
1666 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1667 (shifted)); \
1668 } \
1669 break;
1670
1671 // The shift key and other modifier keys should affect the output
1672 // sequence.
1673#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1674 case (vk): \
1675 { \
1676 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1677 control_key_state, (normal), (shifted)); \
1678 } \
1679 break;
1680
1681#define ESC "\x1b"
1682#define CSI ESC "["
1683#define SS3 ESC "O"
1684
1685 // Only support normal mode, not application mode.
1686
1687 // Enhanced keys:
1688 // * 6-pack: insert, delete, home, end, page up, page down
1689 // * cursor keys: up, down, right, left
1690 // * keypad: divide, enter
1691 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1692 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1693 if (_is_enhanced_key(control_key_state)) {
1694 switch (vk) {
1695 case VK_RETURN: // Enter key on keypad
1696 if (_is_ctrl_pressed(control_key_state)) {
1697 seqstr = "\n";
1698 } else {
1699 seqstr = "\r";
1700 }
1701 break;
1702
1703 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1704 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1705
1706 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1707 // will be fixed soon to match xterm which sends CSI "F" and
1708 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1709 MATCH(VK_END, CSI "F");
1710 MATCH(VK_HOME, CSI "H");
1711
1712 MATCH_MODIFIER(VK_LEFT, CSI "D");
1713 MATCH_MODIFIER(VK_UP, CSI "A");
1714 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1715 MATCH_MODIFIER(VK_DOWN, CSI "B");
1716
1717 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1718 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1719
1720 MATCH(VK_DIVIDE, "/");
1721 }
1722 } else { // Non-enhanced keys:
1723 switch (vk) {
1724 case VK_BACK: // backspace
1725 if (_is_alt_pressed(control_key_state)) {
1726 seqstr = ESC "\x7f";
1727 } else {
1728 seqstr = "\x7f";
1729 }
1730 break;
1731
1732 case VK_TAB:
1733 if (_is_shift_pressed(control_key_state)) {
1734 seqstr = CSI "Z";
1735 } else {
1736 seqstr = "\t";
1737 }
1738 break;
1739
1740 // Number 5 key in keypad when NumLock is off, or if NumLock is
1741 // on and Shift is down.
1742 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1743
1744 case VK_RETURN: // Enter key on main keyboard
1745 if (_is_alt_pressed(control_key_state)) {
1746 seqstr = ESC "\n";
1747 } else if (_is_ctrl_pressed(control_key_state)) {
1748 seqstr = "\n";
1749 } else {
1750 seqstr = "\r";
1751 }
1752 break;
1753
1754 // VK_ESCAPE: Don't do any special handling. The OS uses many
1755 // of the sequences with Escape and many of the remaining
1756 // sequences don't produce bKeyDown messages, only !bKeyDown
1757 // for whatever reason.
1758
1759 case VK_SPACE:
1760 if (_is_alt_pressed(control_key_state)) {
1761 seqstr = ESC " ";
1762 } else if (_is_ctrl_pressed(control_key_state)) {
1763 seqbuf[0] = '\0'; // NULL char
1764 seqbuflen = 1;
1765 } else {
1766 seqstr = " ";
1767 }
1768 break;
1769
1770 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1771 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1772
1773 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1774 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1775
1776 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1777 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1778 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1779 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1780
1781 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1782 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1783 _get_decimal_char());
1784
1785 case 0x30: // 0
1786 case 0x31: // 1
1787 case 0x39: // 9
1788 case VK_OEM_1: // ;:
1789 case VK_OEM_PLUS: // =+
1790 case VK_OEM_COMMA: // ,<
1791 case VK_OEM_PERIOD: // .>
1792 case VK_OEM_7: // '"
1793 case VK_OEM_102: // depends on keyboard, could be <> or \|
1794 case VK_OEM_2: // /?
1795 case VK_OEM_3: // `~
1796 case VK_OEM_4: // [{
1797 case VK_OEM_5: // \|
1798 case VK_OEM_6: // ]}
1799 {
1800 seqbuflen = _get_control_character(seqbuf, key_event,
1801 control_key_state);
1802
1803 if (_is_alt_pressed(control_key_state)) {
1804 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1805 }
1806 }
1807 break;
1808
1809 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001810 case 0x33: // 3
1811 case 0x34: // 4
1812 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001813 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001814 case 0x37: // 7
1815 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001816 case VK_OEM_MINUS: // -_
1817 {
1818 seqbuflen = _get_control_character(seqbuf, key_event,
1819 control_key_state);
1820
1821 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1822 // prefix with escape.
1823 if (_is_alt_pressed(control_key_state) &&
1824 !(_is_ctrl_pressed(control_key_state) &&
1825 !_is_shift_pressed(control_key_state))) {
1826 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1827 }
1828 }
1829 break;
1830
Spencer Lowbeb61982015-03-01 15:06:21 -08001831 case 0x41: // a
1832 case 0x42: // b
1833 case 0x43: // c
1834 case 0x44: // d
1835 case 0x45: // e
1836 case 0x46: // f
1837 case 0x47: // g
1838 case 0x48: // h
1839 case 0x49: // i
1840 case 0x4a: // j
1841 case 0x4b: // k
1842 case 0x4c: // l
1843 case 0x4d: // m
1844 case 0x4e: // n
1845 case 0x4f: // o
1846 case 0x50: // p
1847 case 0x51: // q
1848 case 0x52: // r
1849 case 0x53: // s
1850 case 0x54: // t
1851 case 0x55: // u
1852 case 0x56: // v
1853 case 0x57: // w
1854 case 0x58: // x
1855 case 0x59: // y
1856 case 0x5a: // z
1857 {
1858 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1859 control_key_state);
1860
1861 // If Alt is pressed, then prefix with escape.
1862 if (_is_alt_pressed(control_key_state)) {
1863 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1864 }
1865 }
1866 break;
1867
1868 // These virtual key codes are generated by the keys on the
1869 // keypad *when NumLock is on* and *Shift is up*.
1870 MATCH(VK_NUMPAD0, "0");
1871 MATCH(VK_NUMPAD1, "1");
1872 MATCH(VK_NUMPAD2, "2");
1873 MATCH(VK_NUMPAD3, "3");
1874 MATCH(VK_NUMPAD4, "4");
1875 MATCH(VK_NUMPAD5, "5");
1876 MATCH(VK_NUMPAD6, "6");
1877 MATCH(VK_NUMPAD7, "7");
1878 MATCH(VK_NUMPAD8, "8");
1879 MATCH(VK_NUMPAD9, "9");
1880
1881 MATCH(VK_MULTIPLY, "*");
1882 MATCH(VK_ADD, "+");
1883 MATCH(VK_SUBTRACT, "-");
1884 // VK_DECIMAL is generated by the . key on the keypad *when
1885 // NumLock is on* and *Shift is up* and the sequence is not
1886 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1887 // Windows Security screen to come up).
1888 case VK_DECIMAL:
1889 // U.S. English uses '.', Germany German uses ','.
1890 seqbuflen = _get_non_control_char(seqbuf, key_event,
1891 control_key_state);
1892 break;
1893
1894 MATCH_MODIFIER(VK_F1, SS3 "P");
1895 MATCH_MODIFIER(VK_F2, SS3 "Q");
1896 MATCH_MODIFIER(VK_F3, SS3 "R");
1897 MATCH_MODIFIER(VK_F4, SS3 "S");
1898 MATCH_MODIFIER(VK_F5, CSI "15~");
1899 MATCH_MODIFIER(VK_F6, CSI "17~");
1900 MATCH_MODIFIER(VK_F7, CSI "18~");
1901 MATCH_MODIFIER(VK_F8, CSI "19~");
1902 MATCH_MODIFIER(VK_F9, CSI "20~");
1903 MATCH_MODIFIER(VK_F10, CSI "21~");
1904 MATCH_MODIFIER(VK_F11, CSI "23~");
1905 MATCH_MODIFIER(VK_F12, CSI "24~");
1906
1907 MATCH_MODIFIER(VK_F13, CSI "25~");
1908 MATCH_MODIFIER(VK_F14, CSI "26~");
1909 MATCH_MODIFIER(VK_F15, CSI "28~");
1910 MATCH_MODIFIER(VK_F16, CSI "29~");
1911 MATCH_MODIFIER(VK_F17, CSI "31~");
1912 MATCH_MODIFIER(VK_F18, CSI "32~");
1913 MATCH_MODIFIER(VK_F19, CSI "33~");
1914 MATCH_MODIFIER(VK_F20, CSI "34~");
1915
1916 // MATCH_MODIFIER(VK_F21, ???);
1917 // MATCH_MODIFIER(VK_F22, ???);
1918 // MATCH_MODIFIER(VK_F23, ???);
1919 // MATCH_MODIFIER(VK_F24, ???);
1920 }
1921 }
1922
1923#undef MATCH
1924#undef MATCH_MODIFIER
1925#undef MATCH_KEYPAD
1926#undef MATCH_MODIFIER_KEYPAD
1927#undef ESC
1928#undef CSI
1929#undef SS3
1930
1931 const char* out;
1932 size_t outlen;
1933
1934 // Check for output in any of:
1935 // * seqstr is set (and strlen can be used to determine the length).
1936 // * seqbuf and seqbuflen are set
1937 // Fallback to ch from Windows.
1938 if (seqstr != NULL) {
1939 out = seqstr;
1940 outlen = strlen(seqstr);
1941 } else if (seqbuflen > 0) {
1942 out = seqbuf;
1943 outlen = seqbuflen;
1944 } else if (ch != '\0') {
1945 // Use whatever Windows told us it is.
1946 seqbuf[0] = ch;
1947 seqbuflen = 1;
1948 out = seqbuf;
1949 outlen = seqbuflen;
1950 } else {
1951 // No special handling for the virtual key code and Windows isn't
1952 // telling us a character code, then we don't know how to translate
1953 // the key press.
1954 //
1955 // Consume the input and 'continue' to cause us to get a new key
1956 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07001957 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08001958 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08001959 continue;
1960 }
1961
Spencer Low9c8f7462015-11-10 19:17:16 -08001962 // put output wRepeatCount times into g_console_input_buffer
1963 while (key_event->wRepeatCount-- > 0) {
1964 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08001965 }
1966
Spencer Low9c8f7462015-11-10 19:17:16 -08001967 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08001968 }
1969}
1970
1971static DWORD _old_console_mode; // previous GetConsoleMode() result
1972static HANDLE _console_handle; // when set, console mode should be restored
1973
Elliott Hughesa8265792015-11-03 11:18:40 -08001974void stdin_raw_init() {
1975 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08001976 if (in == nullptr) {
1977 return;
1978 }
Spencer Lowbeb61982015-03-01 15:06:21 -08001979
Elliott Hughesa8265792015-11-03 11:18:40 -08001980 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
1981 // calling the process Ctrl-C routine (configured by
1982 // SetConsoleCtrlHandler()).
1983 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
1984 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
1985 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08001986 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
1987 ENABLE_LINE_INPUT |
1988 ENABLE_ECHO_INPUT);
1989 // Enable ENABLE_WINDOW_INPUT to get window resizes.
1990 new_console_mode |= ENABLE_WINDOW_INPUT;
1991
1992 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08001993 // This really should not fail.
1994 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08001995 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001996 }
Elliott Hughesa8265792015-11-03 11:18:40 -08001997
1998 // Once this is set, it means that stdin has been configured for
1999 // reading from and that the old console mode should be restored later.
2000 _console_handle = in;
2001
2002 // Note that we don't need to configure C Runtime line-ending
2003 // translation because _console_read() does not call the C Runtime to
2004 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002005}
2006
Elliott Hughesa8265792015-11-03 11:18:40 -08002007void stdin_raw_restore() {
2008 if (_console_handle != NULL) {
2009 const HANDLE in = _console_handle;
2010 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002011
Elliott Hughesa8265792015-11-03 11:18:40 -08002012 if (!SetConsoleMode(in, _old_console_mode)) {
2013 // This really should not fail.
2014 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002015 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002016 }
2017 }
2018}
2019
Spencer Low55441402015-11-07 17:34:39 -08002020// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2021int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002022 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2023 // If it is a request to read from stdin, and stdin_raw_init() has been
2024 // called, and it successfully configured the console, then read from
2025 // the console using Win32 console APIs and partially emulate a unix
2026 // terminal.
2027 return _console_read(_console_handle, buf, len);
2028 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002029 // On older versions of Windows (definitely 7, definitely not 10),
2030 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002031 // we need to limit the read size.
2032 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002033 len = 4096;
2034 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002035 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002036 // can do LF/CR translation (which is overridable with _setmode()).
2037 // Undefine the macro that is set in sysdeps.h which bans calls to
2038 // plain read() in favor of unix_read() or adb_read().
2039#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002040#undef read
2041 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002042#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002043 }
2044}
Spencer Low6815c072015-05-11 01:08:48 -07002045
2046/**************************************************************************/
2047/**************************************************************************/
2048/***** *****/
2049/***** Unicode support *****/
2050/***** *****/
2051/**************************************************************************/
2052/**************************************************************************/
2053
2054// This implements support for using files with Unicode filenames and for
2055// outputting Unicode text to a Win32 console window. This is inspired from
2056// http://utf8everywhere.org/.
2057//
2058// Background
2059// ----------
2060//
2061// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2062// filenames to APIs such as open(). This works because filenames are largely
2063// opaque 'cookies' (perhaps excluding path separators).
2064//
2065// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2066// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2067// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2068// CreateFile() API is really just a macro that adds the W/A based on whether
2069// the UNICODE preprocessor symbol is defined).
2070//
2071// Options
2072// -------
2073//
2074// Thus, to write a portable program, there are a few options:
2075//
2076// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2077// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2078// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2079// open() API.
2080//
2081// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2082// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2083// potentially touching a lot of code.
2084//
2085// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2086// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2087// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2088// or C Runtime API.
2089//
2090// The Choice
2091// ----------
2092//
Spencer Low50f5bf12015-11-12 15:20:15 -08002093// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2094// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002095// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002096// args that are passed to main() at the beginning of program startup. We also use
2097// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002098// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2099//
2100// Unicode console output
2101// ----------------------
2102//
2103// The way to output Unicode to a Win32 console window is to call
2104// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002105// such as Lucida Console or Consolas, and in the case of East Asian languages
2106// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2107// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2108// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002109//
2110// The problem is getting the C Runtime to make fprintf and related APIs call
2111// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2112// promising, but the various modes have issues:
2113//
2114// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2115// UTF-16 do not display properly.
2116// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2117// totally wrong.
2118// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2119// handler to be called (upon a later I/O call), aborting the process.
2120// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2121// to output nothing.
2122//
2123// So the only solution is to write our own adb_fprintf() that converts UTF-8
2124// to UTF-16 and then calls WriteConsoleW().
2125
2126
Spencer Low6815c072015-05-11 01:08:48 -07002127// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2128// be passed to main().
2129NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2130 narrow_args = new char*[argc + 1];
2131
2132 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002133 std::string arg_narrow;
2134 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2135 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2136 }
2137 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002138 }
2139 narrow_args[argc] = nullptr; // terminate
2140}
2141
2142NarrowArgs::~NarrowArgs() {
2143 if (narrow_args != nullptr) {
2144 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2145 free(*argp);
2146 }
2147 delete[] narrow_args;
2148 narrow_args = nullptr;
2149 }
2150}
2151
2152int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002153 std::wstring path_wide;
2154 if (!android::base::UTF8ToWide(path, &path_wide)) {
2155 return -1;
2156 }
Spencer Low6815c072015-05-11 01:08:48 -07002157 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002158 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002159 } else {
2160 int mode;
2161 va_list args;
2162 va_start(args, options);
2163 mode = va_arg(args, int);
2164 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002165 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002166 }
2167}
2168
Spencer Low6815c072015-05-11 01:08:48 -07002169// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002170DIR* adb_opendir(const char* path) {
2171 std::wstring path_wide;
2172 if (!android::base::UTF8ToWide(path, &path_wide)) {
2173 return nullptr;
2174 }
2175
Spencer Low6815c072015-05-11 01:08:48 -07002176 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2177 // the fields, but right now all the callers treat the structure as
2178 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002179 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002180}
2181
2182// Version of readdir() that returns UTF-8 paths.
2183struct dirent* adb_readdir(DIR* dir) {
2184 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2185 struct _wdirent* const went = _wreaddir(wdir);
2186 if (went == nullptr) {
2187 return nullptr;
2188 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002189
Spencer Low6815c072015-05-11 01:08:48 -07002190 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002191 std::string name_utf8;
2192 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2193 return nullptr;
2194 }
Spencer Low6815c072015-05-11 01:08:48 -07002195
2196 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2197 // space for UTF-16 wchar_t's) with UTF-8 char's.
2198 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2199
2200 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2201 // Name too big to fit in existing buffer.
2202 errno = ENOMEM;
2203 return nullptr;
2204 }
2205
2206 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2207 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2208 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2209 // bigger than the caller expects because they expect a dirent structure
2210 // which has a smaller d_name field. Ignore this since the caller should be
2211 // resilient.
2212
2213 // Rewrite the UTF-16 d_name field to UTF-8.
2214 strcpy(ent->d_name, name_utf8.c_str());
2215
2216 return ent;
2217}
2218
2219// Version of closedir() to go with our version of adb_opendir().
2220int adb_closedir(DIR* dir) {
2221 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2222}
2223
2224// Version of unlink() that takes a UTF-8 path.
2225int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002226 std::wstring wpath;
2227 if (!android::base::UTF8ToWide(path, &wpath)) {
2228 return -1;
2229 }
Spencer Low6815c072015-05-11 01:08:48 -07002230
2231 int rc = _wunlink(wpath.c_str());
2232
2233 if (rc == -1 && errno == EACCES) {
2234 /* unlink returns EACCES when the file is read-only, so we first */
2235 /* try to make it writable, then unlink again... */
2236 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2237 if (rc == 0)
2238 rc = _wunlink(wpath.c_str());
2239 }
2240 return rc;
2241}
2242
2243// Version of mkdir() that takes a UTF-8 path.
2244int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002245 std::wstring path_wide;
2246 if (!android::base::UTF8ToWide(path, &path_wide)) {
2247 return -1;
2248 }
2249
2250 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002251}
2252
2253// Version of utime() that takes a UTF-8 path.
2254int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002255 std::wstring path_wide;
2256 if (!android::base::UTF8ToWide(path, &path_wide)) {
2257 return -1;
2258 }
2259
Spencer Low6815c072015-05-11 01:08:48 -07002260 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2261 "utimbuf and _utimbuf should be the same size because they both "
2262 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002263 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002264}
2265
2266// Version of chmod() that takes a UTF-8 path.
2267int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002268 std::wstring path_wide;
2269 if (!android::base::UTF8ToWide(path, &path_wide)) {
2270 return -1;
2271 }
2272
2273 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002274}
2275
Spencer Lowf373c352015-11-15 16:29:36 -08002276// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2277static inline size_t utf8_codepoint_len(uint8_t ch) {
2278 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2279}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002280
Spencer Lowf373c352015-11-15 16:29:36 -08002281namespace internal {
2282
2283// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2284// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2285// remaining_bytes.
2286size_t ParseCompleteUTF8(const char* const first, const char* const last,
2287 std::vector<char>* const remaining_bytes) {
2288 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2289 // Current_after points one byte past the current byte to be examined.
2290 for (const char* current_after = last; current_after != first; --current_after) {
2291 const char* const current = current_after - 1;
2292 const char ch = *current;
2293 const char kHighBit = 0x80u;
2294 const char kTwoHighestBits = 0xC0u;
2295 if ((ch & kHighBit) == 0) { // high bit not set
2296 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2297 // bytes with no leading byte, so return the entire buffer.
2298 break;
2299 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2300 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2301 const size_t bytes_available = last - current;
2302 if (bytes_available < utf8_codepoint_len(ch)) {
2303 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2304 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2305 // to remaining_bytes.
2306 remaining_bytes->insert(remaining_bytes->end(), current, last);
2307 return current - first;
2308 } else {
2309 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2310 // trailing bytes with no lead byte, so return the entire buffer.
2311 break;
2312 }
2313 } else {
2314 // Trailing byte, so keep going backwards looking for the lead byte.
2315 }
2316 }
2317
2318 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2319 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2320 // so that they can be processed.
2321 return last - first;
2322}
2323
2324}
2325
2326// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2327// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2328// This matches the behavior of Linux.
Spencer Lowf373c352015-11-15 16:29:36 -08002329
2330// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2331static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2332 HANDLE console) {
Josh Gaoe7daf572016-09-21 12:37:10 -07002333 static std::mutex& console_output_buffer_lock = *new std::mutex();
2334 static auto& console_output_buffer = *new std::vector<char>();
2335
Spencer Lowf373c352015-11-15 16:29:36 -08002336 const int saved_errno = errno;
2337 std::vector<char> combined_buffer;
2338
2339 // Complete UTF-8 sequences that should be immediately written to the console.
2340 const char* utf8;
2341 size_t utf8_size;
2342
Josh Gaoe7daf572016-09-21 12:37:10 -07002343 {
2344 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2345 if (console_output_buffer.empty()) {
2346 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2347 // common case with plain ASCII), parse buf directly.
2348 utf8 = buf;
2349 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2350 } else {
2351 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2352 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2353 // combined_buffer, then parse it all together.
2354 combined_buffer.swap(console_output_buffer);
2355 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowf373c352015-11-15 16:29:36 -08002356
Josh Gaoe7daf572016-09-21 12:37:10 -07002357 utf8 = combined_buffer.data();
2358 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2359 &console_output_buffer);
2360 }
Spencer Lowf373c352015-11-15 16:29:36 -08002361 }
Spencer Lowf373c352015-11-15 16:29:36 -08002362
2363 std::wstring utf16;
2364
2365 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2366 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2367 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002368 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002369 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002370
2371 // Note that this does not do \n => \r\n translation because that
2372 // doesn't seem necessary for the Windows console. For the Windows
2373 // console \r moves to the beginning of the line and \n moves to a new
2374 // line.
2375
2376 // Flush any stream buffering so that our output is afterwards which
2377 // makes sense because our call is afterwards.
2378 (void)fflush(stream);
2379
2380 // Write UTF-16 to the console.
2381 DWORD written = 0;
Spencer Lowf373c352015-11-15 16:29:36 -08002382 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Low6815c072015-05-11 01:08:48 -07002383 errno = EIO;
2384 return -1;
2385 }
2386
Spencer Lowf373c352015-11-15 16:29:36 -08002387 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2388 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2389 // matches the Linux behavior.
2390 errno = saved_errno;
2391 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002392}
2393
2394// Function prototype because attributes cannot be placed on func definitions.
2395static int _console_vfprintf(const HANDLE console, FILE* stream,
2396 const char *format, va_list ap)
2397 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2398
2399// Internal function to format a UTF-8 string and write it to a Win32 console.
2400// Returns -1 on error.
2401static int _console_vfprintf(const HANDLE console, FILE* stream,
2402 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002403 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002404 std::string output_utf8;
2405
2406 // Format the string.
2407 // This could throw std::bad_alloc.
2408 android::base::StringAppendV(&output_utf8, format, ap);
2409
Spencer Lowf373c352015-11-15 16:29:36 -08002410 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2411 console);
2412 if (result != -1) {
2413 errno = saved_errno;
2414 } else {
2415 // If -1 was returned, errno has been set.
2416 }
2417 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002418}
2419
2420// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2421// Windows console.
2422int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2423 const HANDLE console = _get_console_handle(stream);
2424
2425 // If there is an associated Win32 console, write to it specially,
2426 // otherwise defer to the regular C Runtime, passing it UTF-8.
2427 if (console != NULL) {
2428 return _console_vfprintf(console, stream, format, ap);
2429 } else {
2430 // If vfprintf is a macro, undefine it, so we can call the real
2431 // C Runtime API.
2432#pragma push_macro("vfprintf")
2433#undef vfprintf
2434 return vfprintf(stream, format, ap);
2435#pragma pop_macro("vfprintf")
2436 }
2437}
2438
Spencer Lowf373c352015-11-15 16:29:36 -08002439// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2440int adb_vprintf(const char *format, va_list ap) {
2441 return adb_vfprintf(stdout, format, ap);
2442}
2443
Spencer Low6815c072015-05-11 01:08:48 -07002444// Version of fprintf() that takes UTF-8 and can write Unicode to a
2445// Windows console.
2446int adb_fprintf(FILE *stream, const char *format, ...) {
2447 va_list ap;
2448 va_start(ap, format);
2449 const int result = adb_vfprintf(stream, format, ap);
2450 va_end(ap);
2451
2452 return result;
2453}
2454
2455// Version of printf() that takes UTF-8 and can write Unicode to a
2456// Windows console.
2457int adb_printf(const char *format, ...) {
2458 va_list ap;
2459 va_start(ap, format);
2460 const int result = adb_vfprintf(stdout, format, ap);
2461 va_end(ap);
2462
2463 return result;
2464}
2465
2466// Version of fputs() that takes UTF-8 and can write Unicode to a
2467// Windows console.
2468int adb_fputs(const char* buf, FILE* stream) {
2469 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2470 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002471 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002472 return adb_fprintf(stream, "%s", buf);
2473}
2474
2475// Version of fputc() that takes UTF-8 and can write Unicode to a
2476// Windows console.
2477int adb_fputc(int ch, FILE* stream) {
2478 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002479 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002480 return EOF;
2481 }
2482 // For success, fputc returns the char, cast to unsigned char, then to int.
2483 return static_cast<unsigned char>(ch);
2484}
2485
Spencer Lowf373c352015-11-15 16:29:36 -08002486// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2487int adb_putchar(int ch) {
2488 return adb_fputc(ch, stdout);
2489}
2490
2491// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2492int adb_puts(const char* buf) {
2493 // adb_printf returns -1 on error, which is conveniently the same as EOF
2494 // which puts (and hence adb_puts) should return on error.
2495 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2496 return adb_printf("%s\n", buf);
2497}
2498
Spencer Low6815c072015-05-11 01:08:48 -07002499// Internal function to write UTF-8 to a Win32 console. Returns the number of
2500// items (of length size) written. On error, returns a short item count or 0.
2501static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2502 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002503 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2504 console);
Spencer Low6815c072015-05-11 01:08:48 -07002505 if (result == -1) {
2506 return 0;
2507 }
2508 return result / size;
2509}
2510
2511// Version of fwrite() that takes UTF-8 and can write Unicode to a
2512// Windows console.
2513size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2514 const HANDLE console = _get_console_handle(stream);
2515
2516 // If there is an associated Win32 console, write to it specially,
2517 // otherwise defer to the regular C Runtime, passing it UTF-8.
2518 if (console != NULL) {
2519 return _console_fwrite(ptr, size, nmemb, stream, console);
2520 } else {
2521 // If fwrite is a macro, undefine it, so we can call the real
2522 // C Runtime API.
2523#pragma push_macro("fwrite")
2524#undef fwrite
2525 return fwrite(ptr, size, nmemb, stream);
2526#pragma pop_macro("fwrite")
2527 }
2528}
2529
2530// Version of fopen() that takes a UTF-8 filename and can access a file with
2531// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002532FILE* adb_fopen(const char* path, const char* mode) {
2533 std::wstring path_wide;
2534 if (!android::base::UTF8ToWide(path, &path_wide)) {
2535 return nullptr;
2536 }
2537
2538 std::wstring mode_wide;
2539 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2540 return nullptr;
2541 }
2542
2543 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002544}
2545
Spencer Low50740f52015-09-08 17:13:04 -07002546// Return a lowercase version of the argument. Uses C Runtime tolower() on
2547// each byte which is not UTF-8 aware, and theoretically uses the current C
2548// Runtime locale (which in practice is not changed, so this becomes a ASCII
2549// conversion).
2550static std::string ToLower(const std::string& anycase) {
2551 // copy string
2552 std::string str(anycase);
2553 // transform the copy
2554 std::transform(str.begin(), str.end(), str.begin(), tolower);
2555 return str;
2556}
2557
2558extern "C" int main(int argc, char** argv);
2559
2560// Link with -municode to cause this wmain() to be used as the program
2561// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2562// regular main() with UTF-8 args.
2563extern "C" int wmain(int argc, wchar_t **argv) {
2564 // Convert args from UTF-16 to UTF-8 and pass that to main().
2565 NarrowArgs narrow_args(argc, argv);
2566 return main(argc, narrow_args.data());
2567}
2568
Spencer Low6815c072015-05-11 01:08:48 -07002569// Shadow UTF-8 environment variable name/value pairs that are created from
2570// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07002571// currently updated if putenv, setenv, unsetenv are called. Note that no
2572// thread synchronization is done, but we're called early enough in
2573// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002574static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002575
2576// Make sure that shadow UTF-8 environment variables are setup.
2577static void _ensure_env_setup() {
2578 // If some name/value pairs exist, then we've already done the setup below.
2579 if (g_environ_utf8.size() != 0) {
2580 return;
2581 }
2582
Spencer Low50740f52015-09-08 17:13:04 -07002583 if (_wenviron == nullptr) {
2584 // If _wenviron is null, then -municode probably wasn't used. That
2585 // linker flag will cause the entry point to setup _wenviron. It will
2586 // also require an implementation of wmain() (which we provide above).
2587 fatal("_wenviron is not set, did you link with -municode?");
2588 }
2589
Spencer Low6815c072015-05-11 01:08:48 -07002590 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2591 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2592 // to use the D() macro here because that tracing only works if the
2593 // ADB_TRACE environment variable is setup, but that env var can't be read
2594 // until this code completes.
2595 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2596 wchar_t* const equal = wcschr(*env, L'=');
2597 if (equal == nullptr) {
2598 // Malformed environment variable with no equal sign. Shouldn't
2599 // really happen, but we should be resilient to this.
2600 continue;
2601 }
2602
Spencer Low50f5bf12015-11-12 15:20:15 -08002603 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2604 // var because the program might never even read this particular variable.
2605 std::string name_utf8;
2606 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2607 continue;
2608 }
2609
Spencer Low50740f52015-09-08 17:13:04 -07002610 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002611 name_utf8 = ToLower(name_utf8);
2612
2613 std::string value_utf8;
2614 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2615 continue;
2616 }
2617
2618 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002619
Spencer Low50740f52015-09-08 17:13:04 -07002620 // Don't overwrite a previus env var with the same name. In reality,
2621 // the system probably won't let two env vars with the same name exist
2622 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002623 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002624 }
2625}
2626
2627// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002628// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002629char* adb_getenv(const char* name) {
2630 _ensure_env_setup();
2631
Spencer Low50740f52015-09-08 17:13:04 -07002632 // Case-insensitive search by searching for lowercase name in a map of
2633 // lowercase names.
2634 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002635 if (it == g_environ_utf8.end()) {
2636 return nullptr;
2637 }
2638
2639 return it->second;
2640}
2641
2642// Version of getcwd() that returns the current working directory in UTF-8.
2643char* adb_getcwd(char* buf, int size) {
2644 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2645 if (wbuf == nullptr) {
2646 return nullptr;
2647 }
2648
Spencer Low50f5bf12015-11-12 15:20:15 -08002649 std::string buf_utf8;
2650 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002651 free(wbuf);
2652 wbuf = nullptr;
2653
Spencer Low50f5bf12015-11-12 15:20:15 -08002654 if (!narrow_result) {
2655 return nullptr;
2656 }
2657
Spencer Low6815c072015-05-11 01:08:48 -07002658 // If size was specified, make sure all the chars will fit.
2659 if (size != 0) {
2660 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2661 errno = ERANGE;
2662 return nullptr;
2663 }
2664 }
2665
2666 // If buf was not specified, allocate storage.
2667 if (buf == nullptr) {
2668 if (size == 0) {
2669 size = buf_utf8.length() + 1;
2670 }
2671 buf = reinterpret_cast<char*>(malloc(size));
2672 if (buf == nullptr) {
2673 return nullptr;
2674 }
2675 }
2676
2677 // Destination buffer was allocated with enough space, or we've already
2678 // checked an existing buffer size for enough space.
2679 strcpy(buf, buf_utf8.c_str());
2680
2681 return buf;
2682}