blob: f997e6b84826160e125fb97c47c5d77fbb9d7bfb [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
750#define LISTEN_BACKLOG 4
751
Spencer Low753d4852015-07-30 23:07:55 -0700752// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao61eda8d2016-02-18 13:43:55 -0800753static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800754 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800755 SOCKET s;
756 int n;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800757
Josh Gao61eda8d2016-02-18 13:43:55 -0800758 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800759 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700760 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800761 return -1;
762 }
763
Josh Gao61eda8d2016-02-18 13:43:55 -0800764 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800765
766 memset(&addr, 0, sizeof(addr));
767 addr.sin_family = AF_INET;
768 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700769 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800770
Spencer Low753d4852015-07-30 23:07:55 -0700771 // TODO: Consider using dual-stack socket that can simultaneously listen on
772 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700773 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700774 if (s == INVALID_SOCKET) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800775 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700776 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800777 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700778 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800779 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700780 return -1;
781 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800782
783 f->fh_socket = s;
784
Spencer Low32625852015-08-11 16:45:32 -0700785 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
786 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800787 n = 1;
Josh Gao61eda8d2016-02-18 13:43:55 -0800788 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
789 const DWORD err = WSAGetLastError();
790 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
791 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700792 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800793 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700794 return -1;
795 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800796
Josh Gao61eda8d2016-02-18 13:43:55 -0800797 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700798 // Save err just in case inet_ntoa() or ntohs() changes the last error.
799 const DWORD err = WSAGetLastError();
Josh Gao61eda8d2016-02-18 13:43:55 -0800800 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
801 ntohs(addr.sin_port),
802 android::base::SystemErrorCodeToString(err).c_str());
803 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
804 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800805 return -1;
806 }
807 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700808 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800809 const DWORD err = WSAGetLastError();
810 *error = android::base::StringPrintf(
811 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
812 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
813 error->c_str());
814 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800815 return -1;
816 }
817 }
Spencer Low753d4852015-07-30 23:07:55 -0700818 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800819 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
820 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
821 port);
822 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700823 f.release();
824 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800825}
826
Spencer Low753d4852015-07-30 23:07:55 -0700827int network_loopback_server(int port, int type, std::string* error) {
828 return _network_server(port, type, INADDR_LOOPBACK, error);
829}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800830
Spencer Low753d4852015-07-30 23:07:55 -0700831int network_inaddr_any_server(int port, int type, std::string* error) {
832 return _network_server(port, type, INADDR_ANY, error);
833}
834
835int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
836 unique_fh f(_fh_alloc(&_fh_socket_class));
837 if (!f) {
838 *error = strerror(errno);
839 return -1;
840 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800841
Elliott Hughes43df1092015-07-23 17:12:58 -0700842 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800843
Spencer Low753d4852015-07-30 23:07:55 -0700844 struct addrinfo hints;
845 memset(&hints, 0, sizeof(hints));
846 hints.ai_family = AF_UNSPEC;
847 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700848 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700849
850 char port_str[16];
851 snprintf(port_str, sizeof(port_str), "%d", port);
852
853 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700854
855#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao61eda8d2016-02-18 13:43:55 -0800856// TODO: When the Android SDK tools increases the Windows system
857// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700858#else
Josh Gao61eda8d2016-02-18 13:43:55 -0800859// Otherwise, keep using getaddrinfo(), or do runtime API detection
860// with GetProcAddress("GetAddrInfoW").
Spencer Lowcc467f12015-08-02 18:13:54 -0700861#endif
Spencer Low753d4852015-07-30 23:07:55 -0700862 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800863 const DWORD err = WSAGetLastError();
864 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
865 host.c_str(), port_str,
866 android::base::SystemErrorCodeToString(err).c_str());
867
Yabin Cui815ad882015-09-02 17:44:28 -0700868 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800869 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800870 return -1;
871 }
Elliott Hughes8ac45992016-08-08 12:52:37 -0700872 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low753d4852015-07-30 23:07:55 -0700873 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800874
Spencer Low753d4852015-07-30 23:07:55 -0700875 // TODO: Try all the addresses if there's more than one? This just uses
876 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
877 // which tries all addresses, takes a timeout and more.
Josh Gao61eda8d2016-02-18 13:43:55 -0800878 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
879 if (s == INVALID_SOCKET) {
880 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700881 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800882 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700883 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800884 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800885 return -1;
886 }
887 f->fh_socket = s;
888
Spencer Low753d4852015-07-30 23:07:55 -0700889 // TODO: Implement timeouts for Windows. Seems like the default in theory
890 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao61eda8d2016-02-18 13:43:55 -0800891 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700892 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao61eda8d2016-02-18 13:43:55 -0800893 const DWORD err = WSAGetLastError();
894 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
895 android::base::SystemErrorCodeToString(err).c_str());
896 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
897 port_str, error->c_str());
898 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800899 return -1;
900 }
901
Spencer Low753d4852015-07-30 23:07:55 -0700902 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800903 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
904 port);
905 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
906 fd);
Spencer Low753d4852015-07-30 23:07:55 -0700907 f.release();
908 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800909}
910
Casey Dahlin20238f22016-09-21 14:03:39 -0700911int adb_register_socket(SOCKET s) {
912 FH f = _fh_alloc( &_fh_socket_class );
913 f->fh_socket = s;
914 return _fh_to_int(f);
915}
916
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800917#undef accept
918int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
919{
Spencer Low3a2421b2015-05-22 20:09:06 -0700920 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200921
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800922 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700923 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -0700924 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800925 return -1;
926 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200927
Spencer Low753d4852015-07-30 23:07:55 -0700928 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800929 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700930 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
931 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800932 return -1;
933 }
934
935 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
936 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700937 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700938 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursellc573d522016-01-27 08:52:53 -0800939 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low753d4852015-07-30 23:07:55 -0700940 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800941 return -1;
942 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200943
Spencer Low753d4852015-07-30 23:07:55 -0700944 const int fd = _fh_to_int(fh.get());
945 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -0700946 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -0700947 fh.release();
948 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800949}
950
951
Spencer Low31aafa62015-01-25 14:40:16 -0800952int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800953{
Spencer Low3a2421b2015-05-22 20:09:06 -0700954 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200955
Spencer Low31aafa62015-01-25 14:40:16 -0800956 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700957 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700958 errno = EBADF;
959 return -1;
960 }
Spencer Lowc7c45612015-09-29 15:05:29 -0700961
962 // TODO: Once we can assume Windows Vista or later, if the caller is trying
963 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
964 // auto-tuning.
965
Spencer Low753d4852015-07-30 23:07:55 -0700966 int result = setsockopt( fh->fh_socket, level, optname,
967 reinterpret_cast<const char*>(optval), optlen );
968 if ( result == SOCKET_ERROR ) {
969 const DWORD err = WSAGetLastError();
David Pursellc573d522016-01-27 08:52:53 -0800970 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
971 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700972 _socket_set_errno( err );
973 result = -1;
974 }
975 return result;
976}
977
Josh Gaoe7388122016-02-16 17:34:53 -0800978int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
979 FH fh = _fh_from_int(fd, __func__);
980
981 if (!fh || fh->clazz != &_fh_socket_class) {
982 D("adb_getsockname: invalid fd %d", fd);
983 errno = EBADF;
984 return -1;
985 }
986
Josh Gaod6001b52016-08-23 15:28:43 -0700987 int result = (getsockname)(fh->fh_socket, sockaddr, optlen);
Josh Gaoe7388122016-02-16 17:34:53 -0800988 if (result == SOCKET_ERROR) {
989 const DWORD err = WSAGetLastError();
990 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
991 android::base::SystemErrorCodeToString(err).c_str());
992 _socket_set_errno(err);
993 result = -1;
994 }
995 return result;
996}
Spencer Low753d4852015-07-30 23:07:55 -0700997
David Pursell19d0c232016-04-07 11:25:48 -0700998int adb_socket_get_local_port(int fd) {
999 sockaddr_storage addr_storage;
1000 socklen_t addr_len = sizeof(addr_storage);
1001
1002 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1003 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1004 return -1;
1005 }
1006
1007 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1008 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1009 errno = ECONNABORTED;
1010 return -1;
1011 }
1012
1013 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1014}
1015
Spencer Low753d4852015-07-30 23:07:55 -07001016int adb_shutdown(int fd)
1017{
1018 FH f = _fh_from_int(fd, __func__);
1019
1020 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001021 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001022 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001023 return -1;
1024 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001025
Yabin Cui815ad882015-09-02 17:44:28 -07001026 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001027 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1028 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001029 D("socket shutdown fd %d failed: %s", fd,
David Pursellc573d522016-01-27 08:52:53 -08001030 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001031 _socket_set_errno(err);
1032 return -1;
1033 }
1034 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001035}
1036
Josh Gaoe7388122016-02-16 17:34:53 -08001037// Emulate socketpair(2) by binding and connecting to a socket.
1038int adb_socketpair(int sv[2]) {
1039 int server = -1;
1040 int client = -1;
1041 int accepted = -1;
David Pursell19d0c232016-04-07 11:25:48 -07001042 int local_port = -1;
Josh Gaoe7388122016-02-16 17:34:53 -08001043 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001044
Josh Gaod6001b52016-08-23 15:28:43 -07001045 struct sockaddr_storage peer_addr = {};
1046 struct sockaddr_storage client_addr = {};
1047 socklen_t peer_socklen = sizeof(peer_addr);
1048 socklen_t client_socklen = sizeof(client_addr);
1049
Josh Gaoe7388122016-02-16 17:34:53 -08001050 server = network_loopback_server(0, SOCK_STREAM, &error);
1051 if (server < 0) {
1052 D("adb_socketpair: failed to create server: %s", error.c_str());
1053 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001054 }
1055
David Pursell19d0c232016-04-07 11:25:48 -07001056 local_port = adb_socket_get_local_port(server);
1057 if (local_port < 0) {
1058 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gaoe7388122016-02-16 17:34:53 -08001059 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001060 }
David Pursell19d0c232016-04-07 11:25:48 -07001061 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001062
David Pursell19d0c232016-04-07 11:25:48 -07001063 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gaoe7388122016-02-16 17:34:53 -08001064 if (client < 0) {
1065 D("adb_socketpair: failed to connect client: %s", error.c_str());
1066 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001067 }
1068
Josh Gaod6001b52016-08-23 15:28:43 -07001069 // Make sure that the peer that connected to us and the client are the same.
1070 accepted = adb_socket_accept(server, reinterpret_cast<sockaddr*>(&peer_addr), &peer_socklen);
Josh Gaoe7388122016-02-16 17:34:53 -08001071 if (accepted < 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -08001072 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoe7388122016-02-16 17:34:53 -08001073 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001074 }
Josh Gaod6001b52016-08-23 15:28:43 -07001075
1076 if (adb_getsockname(client, reinterpret_cast<sockaddr*>(&client_addr), &client_socklen) != 0) {
1077 D("adb_socketpair: failed to getpeername: %s", strerror(errno));
1078 goto fail;
1079 }
1080
1081 if (peer_socklen != client_socklen) {
1082 D("adb_socketpair: client and peer sockaddrs have different lengths");
1083 errno = EIO;
1084 goto fail;
1085 }
1086
1087 if (memcmp(&peer_addr, &client_addr, peer_socklen) != 0) {
1088 D("adb_socketpair: client and peer sockaddrs don't match");
1089 errno = EIO;
1090 goto fail;
1091 }
1092
Josh Gaoe7388122016-02-16 17:34:53 -08001093 adb_close(server);
Josh Gaod6001b52016-08-23 15:28:43 -07001094
Josh Gaoe7388122016-02-16 17:34:53 -08001095 sv[0] = client;
1096 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001097 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001098
Josh Gaoe7388122016-02-16 17:34:53 -08001099fail:
1100 if (server >= 0) {
1101 adb_close(server);
1102 }
1103 if (client >= 0) {
1104 adb_close(client);
1105 }
1106 if (accepted >= 0) {
1107 adb_close(accepted);
1108 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001109 return -1;
1110}
1111
Josh Gaoe7388122016-02-16 17:34:53 -08001112bool set_file_block_mode(int fd, bool block) {
1113 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001114
Josh Gaoe7388122016-02-16 17:34:53 -08001115 if (!fh || !fh->used) {
1116 errno = EBADF;
Casey Dahlin20238f22016-09-21 14:03:39 -07001117 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gaoe7388122016-02-16 17:34:53 -08001118 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001119 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001120
Josh Gaoe7388122016-02-16 17:34:53 -08001121 if (fh->clazz == &_fh_socket_class) {
1122 u_long x = !block;
1123 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin20238f22016-09-21 14:03:39 -07001124 int error = WSAGetLastError();
1125 _socket_set_errno(error);
1126 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gaoe7388122016-02-16 17:34:53 -08001127 return false;
1128 }
1129 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001130 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001131 errno = ENOTSOCK;
Casey Dahlin20238f22016-09-21 14:03:39 -07001132 D("Setting nonblocking on non-socket %d", fd);
Josh Gaoe7388122016-02-16 17:34:53 -08001133 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001134 }
1135}
1136
David Pursellc25a34e2016-02-22 14:27:23 -08001137bool set_tcp_keepalive(int fd, int interval_sec) {
1138 FH fh = _fh_from_int(fd, __func__);
1139
1140 if (!fh || fh->clazz != &_fh_socket_class) {
1141 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1142 errno = EBADF;
1143 return false;
1144 }
1145
1146 tcp_keepalive keepalive;
1147 keepalive.onoff = (interval_sec > 0);
1148 keepalive.keepalivetime = interval_sec * 1000;
1149 keepalive.keepaliveinterval = interval_sec * 1000;
1150
1151 DWORD bytes_returned = 0;
1152 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1153 &bytes_returned, nullptr, nullptr) != 0) {
1154 const DWORD err = WSAGetLastError();
1155 D("set_tcp_keepalive(%d) failed: %s", fd,
1156 android::base::SystemErrorCodeToString(err).c_str());
1157 _socket_set_errno(err);
1158 return false;
1159 }
1160
1161 return true;
1162}
1163
Spencer Lowbeb61982015-03-01 15:06:21 -08001164/**************************************************************************/
1165/**************************************************************************/
1166/***** *****/
1167/***** Console Window Terminal Emulation *****/
1168/***** *****/
1169/**************************************************************************/
1170/**************************************************************************/
1171
1172// This reads input from a Win32 console window and translates it into Unix
1173// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1174// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1175// is emulated instead of xterm because it is probably more popular than xterm:
1176// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1177// supports modern fonts, etc. It seems best to emulate the terminal that most
1178// Android developers use because they'll fix apps (the shell, etc.) to keep
1179// working with that terminal's emulation.
1180//
1181// The point of this emulation is not to be perfect or to solve all issues with
1182// console windows on Windows, but to be better than the original code which
1183// just called read() (which called ReadFile(), which called ReadConsoleA())
1184// which did not support Ctrl-C, tab completion, shell input line editing
1185// keys, server echo, and more.
1186//
1187// This implementation reconfigures the console with SetConsoleMode(), then
1188// calls ReadConsoleInput() to get raw input which it remaps to Unix
1189// terminal-style sequences which is returned via unix_read() which is used
1190// by the 'adb shell' command.
1191//
1192// Code organization:
1193//
David Pursell58805362015-10-28 14:29:51 -07001194// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001195// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1196// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1197// * _console_read() is the main code of the emulation.
1198
David Pursell58805362015-10-28 14:29:51 -07001199// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1200// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1201// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1202static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1203 // First check isatty(); this is very fast and eliminates most non-console
1204 // FDs, but returns 1 for both consoles and character devices like NUL.
1205#pragma push_macro("isatty")
1206#undef isatty
1207 if (!isatty(fd)) {
1208 return nullptr;
1209 }
1210#pragma pop_macro("isatty")
1211
1212 // To differentiate between character devices and consoles we need to get
1213 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1214 // GENERIC_READ permissions.
1215 const intptr_t intptr_handle = _get_osfhandle(fd);
1216 if (intptr_handle == -1) {
1217 return nullptr;
1218 }
1219 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1220 DWORD temp_mode = 0;
1221 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1222 return nullptr;
1223 }
1224
1225 return handle;
1226}
1227
1228// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1229static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001230 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1231 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001232 const int fd = fileno(stream);
1233 if (fd < 0) {
1234 return nullptr;
1235 }
1236 return _get_console_handle(fd);
1237}
1238
1239int unix_isatty(int fd) {
1240 return _get_console_handle(fd) ? 1 : 0;
1241}
Spencer Lowbeb61982015-03-01 15:06:21 -08001242
Spencer Low9c8f7462015-11-10 19:17:16 -08001243// Get the next KEY_EVENT_RECORD that should be processed.
1244static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001245 for (;;) {
1246 DWORD read_count = 0;
1247 memset(input_record, 0, sizeof(*input_record));
1248 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001249 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001250 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001251 errno = EIO;
1252 return false;
1253 }
1254
1255 if (read_count == 0) { // should be impossible
1256 fatal("ReadConsoleInputA returned 0");
1257 }
1258
1259 if (read_count != 1) { // should be impossible
1260 fatal("ReadConsoleInputA did not return one input record");
1261 }
1262
Spencer Low55441402015-11-07 17:34:39 -08001263 // If the console window is resized, emulate SIGWINCH by breaking out
1264 // of read() with errno == EINTR. Note that there is no event on
1265 // vertical resize because we don't give the console our own custom
1266 // screen buffer (with CreateConsoleScreenBuffer() +
1267 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1268 // supports scrollback, but doesn't seem to raise an event for vertical
1269 // window resize.
1270 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1271 errno = EINTR;
1272 return false;
1273 }
1274
Spencer Lowbeb61982015-03-01 15:06:21 -08001275 if ((input_record->EventType == KEY_EVENT) &&
1276 (input_record->Event.KeyEvent.bKeyDown)) {
1277 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1278 fatal("ReadConsoleInputA returned a key event with zero repeat"
1279 " count");
1280 }
1281
1282 // Got an interesting INPUT_RECORD, so return
1283 return true;
1284 }
1285 }
1286}
1287
Spencer Lowbeb61982015-03-01 15:06:21 -08001288static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1289 return (control_key_state & SHIFT_PRESSED) != 0;
1290}
1291
1292static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1293 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1294}
1295
1296static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1297 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1298}
1299
1300static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1301 return (control_key_state & NUMLOCK_ON) != 0;
1302}
1303
1304static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1305 return (control_key_state & CAPSLOCK_ON) != 0;
1306}
1307
1308static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1309 return (control_key_state & ENHANCED_KEY) != 0;
1310}
1311
1312// Constants from MSDN for ToAscii().
1313static const BYTE TOASCII_KEY_OFF = 0x00;
1314static const BYTE TOASCII_KEY_DOWN = 0x80;
1315static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1316
1317// Given a key event, ignore a modifier key and return the character that was
1318// entered without the modifier. Writes to *ch and returns the number of bytes
1319// written.
1320static size_t _get_char_ignoring_modifier(char* const ch,
1321 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1322 const WORD modifier) {
1323 // If there is no character from Windows, try ignoring the specified
1324 // modifier and look for a character. Note that if AltGr is being used,
1325 // there will be a character from Windows.
1326 if (key_event->uChar.AsciiChar == '\0') {
1327 // Note that we read the control key state from the passed in argument
1328 // instead of from key_event since the argument has been normalized.
1329 if (((modifier == VK_SHIFT) &&
1330 _is_shift_pressed(control_key_state)) ||
1331 ((modifier == VK_CONTROL) &&
1332 _is_ctrl_pressed(control_key_state)) ||
1333 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1334
1335 BYTE key_state[256] = {0};
1336 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1337 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1338 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1339 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1340 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1341 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1342 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1343 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1344
1345 // cause this modifier to be ignored
1346 key_state[modifier] = TOASCII_KEY_OFF;
1347
1348 WORD translated = 0;
1349 if (ToAscii(key_event->wVirtualKeyCode,
1350 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1351 // Ignoring the modifier, we found a character.
1352 *ch = (CHAR)translated;
1353 return 1;
1354 }
1355 }
1356 }
1357
1358 // Just use whatever Windows told us originally.
1359 *ch = key_event->uChar.AsciiChar;
1360
1361 // If the character from Windows is NULL, return a size of zero.
1362 return (*ch == '\0') ? 0 : 1;
1363}
1364
1365// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1366// but taking into account the shift key. This is because for a sequence like
1367// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1368// we want to find the character ')'.
1369//
1370// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1371// because it is the default key-sequence to switch the input language.
1372// This is configurable in the Region and Language control panel.
1373static __inline__ size_t _get_non_control_char(char* const ch,
1374 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1375 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1376 VK_CONTROL);
1377}
1378
1379// Get without Alt.
1380static __inline__ size_t _get_non_alt_char(char* const ch,
1381 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1382 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1383 VK_MENU);
1384}
1385
1386// Ignore the control key, find the character from Windows, and apply any
1387// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1388// *pch and returns number of bytes written.
1389static size_t _get_control_character(char* const pch,
1390 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1391 const size_t len = _get_non_control_char(pch, key_event,
1392 control_key_state);
1393
1394 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1395 char ch = *pch;
1396 switch (ch) {
1397 case '2':
1398 case '@':
1399 case '`':
1400 ch = '\0';
1401 break;
1402 case '3':
1403 case '[':
1404 case '{':
1405 ch = '\x1b';
1406 break;
1407 case '4':
1408 case '\\':
1409 case '|':
1410 ch = '\x1c';
1411 break;
1412 case '5':
1413 case ']':
1414 case '}':
1415 ch = '\x1d';
1416 break;
1417 case '6':
1418 case '^':
1419 case '~':
1420 ch = '\x1e';
1421 break;
1422 case '7':
1423 case '-':
1424 case '_':
1425 ch = '\x1f';
1426 break;
1427 case '8':
1428 ch = '\x7f';
1429 break;
1430 case '/':
1431 if (!_is_alt_pressed(control_key_state)) {
1432 ch = '\x1f';
1433 }
1434 break;
1435 case '?':
1436 if (!_is_alt_pressed(control_key_state)) {
1437 ch = '\x7f';
1438 }
1439 break;
1440 }
1441 *pch = ch;
1442 }
1443
1444 return len;
1445}
1446
1447static DWORD _normalize_altgr_control_key_state(
1448 const KEY_EVENT_RECORD* const key_event) {
1449 DWORD control_key_state = key_event->dwControlKeyState;
1450
1451 // If we're in an AltGr situation where the AltGr key is down (depending on
1452 // the keyboard layout, that might be the physical right alt key which
1453 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1454 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1455 // a character (which indicates that there was an AltGr mapping), then act
1456 // as if alt and control are not really down for the purposes of modifiers.
1457 // This makes it so that if the user with, say, a German keyboard layout
1458 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1459 // output the key and we don't see the Alt and Ctrl keys.
1460 if (_is_ctrl_pressed(control_key_state) &&
1461 _is_alt_pressed(control_key_state)
1462 && (key_event->uChar.AsciiChar != '\0')) {
1463 // Try to remove as few bits as possible to improve our chances of
1464 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1465 // Left-Alt + Right-Ctrl + AltGr.
1466 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1467 // Remove Right-Alt.
1468 control_key_state &= ~RIGHT_ALT_PRESSED;
1469 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1470 // pressed, Left-Ctrl is almost always set, except if the user
1471 // presses Right-Ctrl, then AltGr (in that specific order) for
1472 // whatever reason. At any rate, make sure the bit is not set.
1473 control_key_state &= ~LEFT_CTRL_PRESSED;
1474 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1475 // Remove Left-Alt.
1476 control_key_state &= ~LEFT_ALT_PRESSED;
1477 // Whichever Ctrl key is down, remove it from the state. We only
1478 // remove one key, to improve our chances of detecting the
1479 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1480 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1481 // Remove Left-Ctrl.
1482 control_key_state &= ~LEFT_CTRL_PRESSED;
1483 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1484 // Remove Right-Ctrl.
1485 control_key_state &= ~RIGHT_CTRL_PRESSED;
1486 }
1487 }
1488
1489 // Note that this logic isn't 100% perfect because Windows doesn't
1490 // allow us to detect all combinations because a physical AltGr key
1491 // press shows up as two bits, plus some combinations are ambiguous
1492 // about what is actually physically pressed.
1493 }
1494
1495 return control_key_state;
1496}
1497
1498// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1499// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1500// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1501// appropriately.
1502static DWORD _normalize_keypad_control_key_state(const WORD vk,
1503 const DWORD control_key_state) {
1504 if (!_is_numlock_on(control_key_state)) {
1505 return control_key_state;
1506 }
1507 if (!_is_enhanced_key(control_key_state)) {
1508 switch (vk) {
1509 case VK_INSERT: // 0
1510 case VK_DELETE: // .
1511 case VK_END: // 1
1512 case VK_DOWN: // 2
1513 case VK_NEXT: // 3
1514 case VK_LEFT: // 4
1515 case VK_CLEAR: // 5
1516 case VK_RIGHT: // 6
1517 case VK_HOME: // 7
1518 case VK_UP: // 8
1519 case VK_PRIOR: // 9
1520 return control_key_state | SHIFT_PRESSED;
1521 }
1522 }
1523
1524 return control_key_state;
1525}
1526
1527static const char* _get_keypad_sequence(const DWORD control_key_state,
1528 const char* const normal, const char* const shifted) {
1529 if (_is_shift_pressed(control_key_state)) {
1530 // Shift is pressed and NumLock is off
1531 return shifted;
1532 } else {
1533 // Shift is not pressed and NumLock is off, or,
1534 // Shift is pressed and NumLock is on, in which case we want the
1535 // NumLock and Shift to neutralize each other, thus, we want the normal
1536 // sequence.
1537 return normal;
1538 }
1539 // If Shift is not pressed and NumLock is on, a different virtual key code
1540 // is returned by Windows, which can be taken care of by a different case
1541 // statement in _console_read().
1542}
1543
1544// Write sequence to buf and return the number of bytes written.
1545static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1546 DWORD control_key_state, const char* const normal) {
1547 // Copy the base sequence into buf.
1548 const size_t len = strlen(normal);
1549 memcpy(buf, normal, len);
1550
1551 int code = 0;
1552
1553 control_key_state = _normalize_keypad_control_key_state(vk,
1554 control_key_state);
1555
1556 if (_is_shift_pressed(control_key_state)) {
1557 code |= 0x1;
1558 }
1559 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1560 code |= 0x2;
1561 }
1562 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1563 code |= 0x4;
1564 }
1565 // If some modifier was held down, then we need to insert the modifier code
1566 if (code != 0) {
1567 if (len == 0) {
1568 // Should be impossible because caller should pass a string of
1569 // non-zero length.
1570 return 0;
1571 }
1572 size_t index = len - 1;
1573 const char lastChar = buf[index];
1574 if (lastChar != '~') {
1575 buf[index++] = '1';
1576 }
1577 buf[index++] = ';'; // modifier separator
1578 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1579 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1580 buf[index++] = '1' + code;
1581 buf[index++] = lastChar; // move ~ (or other last char) to the end
1582 return index;
1583 }
1584 return len;
1585}
1586
1587// Write sequence to buf and return the number of bytes written.
1588static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1589 const DWORD control_key_state, const char* const normal,
1590 const char shifted) {
1591 if (_is_shift_pressed(control_key_state)) {
1592 // Shift is pressed and NumLock is off
1593 if (shifted != '\0') {
1594 buf[0] = shifted;
1595 return sizeof(buf[0]);
1596 } else {
1597 return 0;
1598 }
1599 } else {
1600 // Shift is not pressed and NumLock is off, or,
1601 // Shift is pressed and NumLock is on, in which case we want the
1602 // NumLock and Shift to neutralize each other, thus, we want the normal
1603 // sequence.
1604 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1605 }
1606 // If Shift is not pressed and NumLock is on, a different virtual key code
1607 // is returned by Windows, which can be taken care of by a different case
1608 // statement in _console_read().
1609}
1610
1611// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1612// Standard German. Figure this out at runtime so we know what to output for
1613// Shift-VK_DELETE.
1614static char _get_decimal_char() {
1615 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1616}
1617
1618// Prefix the len bytes in buf with the escape character, and then return the
1619// new buffer length.
1620size_t _escape_prefix(char* const buf, const size_t len) {
1621 // If nothing to prefix, don't do anything. We might be called with
1622 // len == 0, if alt was held down with a dead key which produced nothing.
1623 if (len == 0) {
1624 return 0;
1625 }
1626
1627 memmove(&buf[1], buf, len);
1628 buf[0] = '\x1b';
1629 return len + 1;
1630}
1631
Spencer Low9c8f7462015-11-10 19:17:16 -08001632// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001633static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001634
1635// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1636// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001637static int _console_read(const HANDLE console, void* buf, size_t len) {
1638 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001639 // Read of zero bytes should not block waiting for something from the console.
1640 if (len == 0) {
1641 return 0;
1642 }
1643
1644 // Flush as much as possible from input buffer.
1645 if (!g_console_input_buffer.empty()) {
1646 const int bytes_read = std::min(len, g_console_input_buffer.size());
1647 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1648 const auto begin = g_console_input_buffer.begin();
1649 g_console_input_buffer.erase(begin, begin + bytes_read);
1650 return bytes_read;
1651 }
1652
1653 // Read from the actual console. This may block until input.
1654 INPUT_RECORD input_record;
1655 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001656 return -1;
1657 }
1658
Spencer Low9c8f7462015-11-10 19:17:16 -08001659 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001660 const WORD vk = key_event->wVirtualKeyCode;
1661 const CHAR ch = key_event->uChar.AsciiChar;
1662 const DWORD control_key_state = _normalize_altgr_control_key_state(
1663 key_event);
1664
1665 // The following emulation code should write the output sequence to
1666 // either seqstr or to seqbuf and seqbuflen.
1667 const char* seqstr = NULL; // NULL terminated C-string
1668 // Enough space for max sequence string below, plus modifiers and/or
1669 // escape prefix.
1670 char seqbuf[16];
1671 size_t seqbuflen = 0; // Space used in seqbuf.
1672
1673#define MATCH(vk, normal) \
1674 case (vk): \
1675 { \
1676 seqstr = (normal); \
1677 } \
1678 break;
1679
1680 // Modifier keys should affect the output sequence.
1681#define MATCH_MODIFIER(vk, normal) \
1682 case (vk): \
1683 { \
1684 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1685 control_key_state, (normal)); \
1686 } \
1687 break;
1688
1689 // The shift key should affect the output sequence.
1690#define MATCH_KEYPAD(vk, normal, shifted) \
1691 case (vk): \
1692 { \
1693 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1694 (shifted)); \
1695 } \
1696 break;
1697
1698 // The shift key and other modifier keys should affect the output
1699 // sequence.
1700#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1701 case (vk): \
1702 { \
1703 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1704 control_key_state, (normal), (shifted)); \
1705 } \
1706 break;
1707
1708#define ESC "\x1b"
1709#define CSI ESC "["
1710#define SS3 ESC "O"
1711
1712 // Only support normal mode, not application mode.
1713
1714 // Enhanced keys:
1715 // * 6-pack: insert, delete, home, end, page up, page down
1716 // * cursor keys: up, down, right, left
1717 // * keypad: divide, enter
1718 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1719 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1720 if (_is_enhanced_key(control_key_state)) {
1721 switch (vk) {
1722 case VK_RETURN: // Enter key on keypad
1723 if (_is_ctrl_pressed(control_key_state)) {
1724 seqstr = "\n";
1725 } else {
1726 seqstr = "\r";
1727 }
1728 break;
1729
1730 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1731 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1732
1733 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1734 // will be fixed soon to match xterm which sends CSI "F" and
1735 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1736 MATCH(VK_END, CSI "F");
1737 MATCH(VK_HOME, CSI "H");
1738
1739 MATCH_MODIFIER(VK_LEFT, CSI "D");
1740 MATCH_MODIFIER(VK_UP, CSI "A");
1741 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1742 MATCH_MODIFIER(VK_DOWN, CSI "B");
1743
1744 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1745 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1746
1747 MATCH(VK_DIVIDE, "/");
1748 }
1749 } else { // Non-enhanced keys:
1750 switch (vk) {
1751 case VK_BACK: // backspace
1752 if (_is_alt_pressed(control_key_state)) {
1753 seqstr = ESC "\x7f";
1754 } else {
1755 seqstr = "\x7f";
1756 }
1757 break;
1758
1759 case VK_TAB:
1760 if (_is_shift_pressed(control_key_state)) {
1761 seqstr = CSI "Z";
1762 } else {
1763 seqstr = "\t";
1764 }
1765 break;
1766
1767 // Number 5 key in keypad when NumLock is off, or if NumLock is
1768 // on and Shift is down.
1769 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1770
1771 case VK_RETURN: // Enter key on main keyboard
1772 if (_is_alt_pressed(control_key_state)) {
1773 seqstr = ESC "\n";
1774 } else if (_is_ctrl_pressed(control_key_state)) {
1775 seqstr = "\n";
1776 } else {
1777 seqstr = "\r";
1778 }
1779 break;
1780
1781 // VK_ESCAPE: Don't do any special handling. The OS uses many
1782 // of the sequences with Escape and many of the remaining
1783 // sequences don't produce bKeyDown messages, only !bKeyDown
1784 // for whatever reason.
1785
1786 case VK_SPACE:
1787 if (_is_alt_pressed(control_key_state)) {
1788 seqstr = ESC " ";
1789 } else if (_is_ctrl_pressed(control_key_state)) {
1790 seqbuf[0] = '\0'; // NULL char
1791 seqbuflen = 1;
1792 } else {
1793 seqstr = " ";
1794 }
1795 break;
1796
1797 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1798 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1799
1800 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1801 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1802
1803 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1804 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1805 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1806 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1807
1808 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1809 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1810 _get_decimal_char());
1811
1812 case 0x30: // 0
1813 case 0x31: // 1
1814 case 0x39: // 9
1815 case VK_OEM_1: // ;:
1816 case VK_OEM_PLUS: // =+
1817 case VK_OEM_COMMA: // ,<
1818 case VK_OEM_PERIOD: // .>
1819 case VK_OEM_7: // '"
1820 case VK_OEM_102: // depends on keyboard, could be <> or \|
1821 case VK_OEM_2: // /?
1822 case VK_OEM_3: // `~
1823 case VK_OEM_4: // [{
1824 case VK_OEM_5: // \|
1825 case VK_OEM_6: // ]}
1826 {
1827 seqbuflen = _get_control_character(seqbuf, key_event,
1828 control_key_state);
1829
1830 if (_is_alt_pressed(control_key_state)) {
1831 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1832 }
1833 }
1834 break;
1835
1836 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001837 case 0x33: // 3
1838 case 0x34: // 4
1839 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001840 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001841 case 0x37: // 7
1842 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001843 case VK_OEM_MINUS: // -_
1844 {
1845 seqbuflen = _get_control_character(seqbuf, key_event,
1846 control_key_state);
1847
1848 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1849 // prefix with escape.
1850 if (_is_alt_pressed(control_key_state) &&
1851 !(_is_ctrl_pressed(control_key_state) &&
1852 !_is_shift_pressed(control_key_state))) {
1853 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1854 }
1855 }
1856 break;
1857
Spencer Lowbeb61982015-03-01 15:06:21 -08001858 case 0x41: // a
1859 case 0x42: // b
1860 case 0x43: // c
1861 case 0x44: // d
1862 case 0x45: // e
1863 case 0x46: // f
1864 case 0x47: // g
1865 case 0x48: // h
1866 case 0x49: // i
1867 case 0x4a: // j
1868 case 0x4b: // k
1869 case 0x4c: // l
1870 case 0x4d: // m
1871 case 0x4e: // n
1872 case 0x4f: // o
1873 case 0x50: // p
1874 case 0x51: // q
1875 case 0x52: // r
1876 case 0x53: // s
1877 case 0x54: // t
1878 case 0x55: // u
1879 case 0x56: // v
1880 case 0x57: // w
1881 case 0x58: // x
1882 case 0x59: // y
1883 case 0x5a: // z
1884 {
1885 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1886 control_key_state);
1887
1888 // If Alt is pressed, then prefix with escape.
1889 if (_is_alt_pressed(control_key_state)) {
1890 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1891 }
1892 }
1893 break;
1894
1895 // These virtual key codes are generated by the keys on the
1896 // keypad *when NumLock is on* and *Shift is up*.
1897 MATCH(VK_NUMPAD0, "0");
1898 MATCH(VK_NUMPAD1, "1");
1899 MATCH(VK_NUMPAD2, "2");
1900 MATCH(VK_NUMPAD3, "3");
1901 MATCH(VK_NUMPAD4, "4");
1902 MATCH(VK_NUMPAD5, "5");
1903 MATCH(VK_NUMPAD6, "6");
1904 MATCH(VK_NUMPAD7, "7");
1905 MATCH(VK_NUMPAD8, "8");
1906 MATCH(VK_NUMPAD9, "9");
1907
1908 MATCH(VK_MULTIPLY, "*");
1909 MATCH(VK_ADD, "+");
1910 MATCH(VK_SUBTRACT, "-");
1911 // VK_DECIMAL is generated by the . key on the keypad *when
1912 // NumLock is on* and *Shift is up* and the sequence is not
1913 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1914 // Windows Security screen to come up).
1915 case VK_DECIMAL:
1916 // U.S. English uses '.', Germany German uses ','.
1917 seqbuflen = _get_non_control_char(seqbuf, key_event,
1918 control_key_state);
1919 break;
1920
1921 MATCH_MODIFIER(VK_F1, SS3 "P");
1922 MATCH_MODIFIER(VK_F2, SS3 "Q");
1923 MATCH_MODIFIER(VK_F3, SS3 "R");
1924 MATCH_MODIFIER(VK_F4, SS3 "S");
1925 MATCH_MODIFIER(VK_F5, CSI "15~");
1926 MATCH_MODIFIER(VK_F6, CSI "17~");
1927 MATCH_MODIFIER(VK_F7, CSI "18~");
1928 MATCH_MODIFIER(VK_F8, CSI "19~");
1929 MATCH_MODIFIER(VK_F9, CSI "20~");
1930 MATCH_MODIFIER(VK_F10, CSI "21~");
1931 MATCH_MODIFIER(VK_F11, CSI "23~");
1932 MATCH_MODIFIER(VK_F12, CSI "24~");
1933
1934 MATCH_MODIFIER(VK_F13, CSI "25~");
1935 MATCH_MODIFIER(VK_F14, CSI "26~");
1936 MATCH_MODIFIER(VK_F15, CSI "28~");
1937 MATCH_MODIFIER(VK_F16, CSI "29~");
1938 MATCH_MODIFIER(VK_F17, CSI "31~");
1939 MATCH_MODIFIER(VK_F18, CSI "32~");
1940 MATCH_MODIFIER(VK_F19, CSI "33~");
1941 MATCH_MODIFIER(VK_F20, CSI "34~");
1942
1943 // MATCH_MODIFIER(VK_F21, ???);
1944 // MATCH_MODIFIER(VK_F22, ???);
1945 // MATCH_MODIFIER(VK_F23, ???);
1946 // MATCH_MODIFIER(VK_F24, ???);
1947 }
1948 }
1949
1950#undef MATCH
1951#undef MATCH_MODIFIER
1952#undef MATCH_KEYPAD
1953#undef MATCH_MODIFIER_KEYPAD
1954#undef ESC
1955#undef CSI
1956#undef SS3
1957
1958 const char* out;
1959 size_t outlen;
1960
1961 // Check for output in any of:
1962 // * seqstr is set (and strlen can be used to determine the length).
1963 // * seqbuf and seqbuflen are set
1964 // Fallback to ch from Windows.
1965 if (seqstr != NULL) {
1966 out = seqstr;
1967 outlen = strlen(seqstr);
1968 } else if (seqbuflen > 0) {
1969 out = seqbuf;
1970 outlen = seqbuflen;
1971 } else if (ch != '\0') {
1972 // Use whatever Windows told us it is.
1973 seqbuf[0] = ch;
1974 seqbuflen = 1;
1975 out = seqbuf;
1976 outlen = seqbuflen;
1977 } else {
1978 // No special handling for the virtual key code and Windows isn't
1979 // telling us a character code, then we don't know how to translate
1980 // the key press.
1981 //
1982 // Consume the input and 'continue' to cause us to get a new key
1983 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07001984 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08001985 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08001986 continue;
1987 }
1988
Spencer Low9c8f7462015-11-10 19:17:16 -08001989 // put output wRepeatCount times into g_console_input_buffer
1990 while (key_event->wRepeatCount-- > 0) {
1991 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08001992 }
1993
Spencer Low9c8f7462015-11-10 19:17:16 -08001994 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08001995 }
1996}
1997
1998static DWORD _old_console_mode; // previous GetConsoleMode() result
1999static HANDLE _console_handle; // when set, console mode should be restored
2000
Elliott Hughesa8265792015-11-03 11:18:40 -08002001void stdin_raw_init() {
2002 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08002003 if (in == nullptr) {
2004 return;
2005 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002006
Elliott Hughesa8265792015-11-03 11:18:40 -08002007 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2008 // calling the process Ctrl-C routine (configured by
2009 // SetConsoleCtrlHandler()).
2010 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2011 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2012 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08002013 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2014 ENABLE_LINE_INPUT |
2015 ENABLE_ECHO_INPUT);
2016 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2017 new_console_mode |= ENABLE_WINDOW_INPUT;
2018
2019 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002020 // This really should not fail.
2021 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002022 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002023 }
Elliott Hughesa8265792015-11-03 11:18:40 -08002024
2025 // Once this is set, it means that stdin has been configured for
2026 // reading from and that the old console mode should be restored later.
2027 _console_handle = in;
2028
2029 // Note that we don't need to configure C Runtime line-ending
2030 // translation because _console_read() does not call the C Runtime to
2031 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002032}
2033
Elliott Hughesa8265792015-11-03 11:18:40 -08002034void stdin_raw_restore() {
2035 if (_console_handle != NULL) {
2036 const HANDLE in = _console_handle;
2037 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002038
Elliott Hughesa8265792015-11-03 11:18:40 -08002039 if (!SetConsoleMode(in, _old_console_mode)) {
2040 // This really should not fail.
2041 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002042 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002043 }
2044 }
2045}
2046
Spencer Low55441402015-11-07 17:34:39 -08002047// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2048int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002049 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2050 // If it is a request to read from stdin, and stdin_raw_init() has been
2051 // called, and it successfully configured the console, then read from
2052 // the console using Win32 console APIs and partially emulate a unix
2053 // terminal.
2054 return _console_read(_console_handle, buf, len);
2055 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002056 // On older versions of Windows (definitely 7, definitely not 10),
2057 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002058 // we need to limit the read size.
2059 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002060 len = 4096;
2061 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002062 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002063 // can do LF/CR translation (which is overridable with _setmode()).
2064 // Undefine the macro that is set in sysdeps.h which bans calls to
2065 // plain read() in favor of unix_read() or adb_read().
2066#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002067#undef read
2068 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002069#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002070 }
2071}
Spencer Low6815c072015-05-11 01:08:48 -07002072
2073/**************************************************************************/
2074/**************************************************************************/
2075/***** *****/
2076/***** Unicode support *****/
2077/***** *****/
2078/**************************************************************************/
2079/**************************************************************************/
2080
2081// This implements support for using files with Unicode filenames and for
2082// outputting Unicode text to a Win32 console window. This is inspired from
2083// http://utf8everywhere.org/.
2084//
2085// Background
2086// ----------
2087//
2088// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2089// filenames to APIs such as open(). This works because filenames are largely
2090// opaque 'cookies' (perhaps excluding path separators).
2091//
2092// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2093// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2094// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2095// CreateFile() API is really just a macro that adds the W/A based on whether
2096// the UNICODE preprocessor symbol is defined).
2097//
2098// Options
2099// -------
2100//
2101// Thus, to write a portable program, there are a few options:
2102//
2103// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2104// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2105// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2106// open() API.
2107//
2108// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2109// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2110// potentially touching a lot of code.
2111//
2112// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2113// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2114// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2115// or C Runtime API.
2116//
2117// The Choice
2118// ----------
2119//
Spencer Low50f5bf12015-11-12 15:20:15 -08002120// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2121// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002122// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002123// args that are passed to main() at the beginning of program startup. We also use
2124// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002125// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2126//
2127// Unicode console output
2128// ----------------------
2129//
2130// The way to output Unicode to a Win32 console window is to call
2131// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002132// such as Lucida Console or Consolas, and in the case of East Asian languages
2133// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2134// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2135// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002136//
2137// The problem is getting the C Runtime to make fprintf and related APIs call
2138// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2139// promising, but the various modes have issues:
2140//
2141// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2142// UTF-16 do not display properly.
2143// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2144// totally wrong.
2145// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2146// handler to be called (upon a later I/O call), aborting the process.
2147// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2148// to output nothing.
2149//
2150// So the only solution is to write our own adb_fprintf() that converts UTF-8
2151// to UTF-16 and then calls WriteConsoleW().
2152
2153
Spencer Low6815c072015-05-11 01:08:48 -07002154// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2155// be passed to main().
2156NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2157 narrow_args = new char*[argc + 1];
2158
2159 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002160 std::string arg_narrow;
2161 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2162 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2163 }
2164 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002165 }
2166 narrow_args[argc] = nullptr; // terminate
2167}
2168
2169NarrowArgs::~NarrowArgs() {
2170 if (narrow_args != nullptr) {
2171 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2172 free(*argp);
2173 }
2174 delete[] narrow_args;
2175 narrow_args = nullptr;
2176 }
2177}
2178
2179int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002180 std::wstring path_wide;
2181 if (!android::base::UTF8ToWide(path, &path_wide)) {
2182 return -1;
2183 }
Spencer Low6815c072015-05-11 01:08:48 -07002184 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002185 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002186 } else {
2187 int mode;
2188 va_list args;
2189 va_start(args, options);
2190 mode = va_arg(args, int);
2191 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002192 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002193 }
2194}
2195
Spencer Low6815c072015-05-11 01:08:48 -07002196// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002197DIR* adb_opendir(const char* path) {
2198 std::wstring path_wide;
2199 if (!android::base::UTF8ToWide(path, &path_wide)) {
2200 return nullptr;
2201 }
2202
Spencer Low6815c072015-05-11 01:08:48 -07002203 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2204 // the fields, but right now all the callers treat the structure as
2205 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002206 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002207}
2208
2209// Version of readdir() that returns UTF-8 paths.
2210struct dirent* adb_readdir(DIR* dir) {
2211 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2212 struct _wdirent* const went = _wreaddir(wdir);
2213 if (went == nullptr) {
2214 return nullptr;
2215 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002216
Spencer Low6815c072015-05-11 01:08:48 -07002217 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002218 std::string name_utf8;
2219 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2220 return nullptr;
2221 }
Spencer Low6815c072015-05-11 01:08:48 -07002222
2223 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2224 // space for UTF-16 wchar_t's) with UTF-8 char's.
2225 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2226
2227 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2228 // Name too big to fit in existing buffer.
2229 errno = ENOMEM;
2230 return nullptr;
2231 }
2232
2233 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2234 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2235 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2236 // bigger than the caller expects because they expect a dirent structure
2237 // which has a smaller d_name field. Ignore this since the caller should be
2238 // resilient.
2239
2240 // Rewrite the UTF-16 d_name field to UTF-8.
2241 strcpy(ent->d_name, name_utf8.c_str());
2242
2243 return ent;
2244}
2245
2246// Version of closedir() to go with our version of adb_opendir().
2247int adb_closedir(DIR* dir) {
2248 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2249}
2250
2251// Version of unlink() that takes a UTF-8 path.
2252int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002253 std::wstring wpath;
2254 if (!android::base::UTF8ToWide(path, &wpath)) {
2255 return -1;
2256 }
Spencer Low6815c072015-05-11 01:08:48 -07002257
2258 int rc = _wunlink(wpath.c_str());
2259
2260 if (rc == -1 && errno == EACCES) {
2261 /* unlink returns EACCES when the file is read-only, so we first */
2262 /* try to make it writable, then unlink again... */
2263 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2264 if (rc == 0)
2265 rc = _wunlink(wpath.c_str());
2266 }
2267 return rc;
2268}
2269
2270// Version of mkdir() that takes a UTF-8 path.
2271int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002272 std::wstring path_wide;
2273 if (!android::base::UTF8ToWide(path, &path_wide)) {
2274 return -1;
2275 }
2276
2277 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002278}
2279
2280// Version of utime() that takes a UTF-8 path.
2281int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002282 std::wstring path_wide;
2283 if (!android::base::UTF8ToWide(path, &path_wide)) {
2284 return -1;
2285 }
2286
Spencer Low6815c072015-05-11 01:08:48 -07002287 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2288 "utimbuf and _utimbuf should be the same size because they both "
2289 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002290 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002291}
2292
2293// Version of chmod() that takes a UTF-8 path.
2294int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002295 std::wstring path_wide;
2296 if (!android::base::UTF8ToWide(path, &path_wide)) {
2297 return -1;
2298 }
2299
2300 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002301}
2302
Spencer Lowf373c352015-11-15 16:29:36 -08002303// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2304static inline size_t utf8_codepoint_len(uint8_t ch) {
2305 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2306}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002307
Spencer Lowf373c352015-11-15 16:29:36 -08002308namespace internal {
2309
2310// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2311// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2312// remaining_bytes.
2313size_t ParseCompleteUTF8(const char* const first, const char* const last,
2314 std::vector<char>* const remaining_bytes) {
2315 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2316 // Current_after points one byte past the current byte to be examined.
2317 for (const char* current_after = last; current_after != first; --current_after) {
2318 const char* const current = current_after - 1;
2319 const char ch = *current;
2320 const char kHighBit = 0x80u;
2321 const char kTwoHighestBits = 0xC0u;
2322 if ((ch & kHighBit) == 0) { // high bit not set
2323 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2324 // bytes with no leading byte, so return the entire buffer.
2325 break;
2326 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2327 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2328 const size_t bytes_available = last - current;
2329 if (bytes_available < utf8_codepoint_len(ch)) {
2330 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2331 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2332 // to remaining_bytes.
2333 remaining_bytes->insert(remaining_bytes->end(), current, last);
2334 return current - first;
2335 } else {
2336 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2337 // trailing bytes with no lead byte, so return the entire buffer.
2338 break;
2339 }
2340 } else {
2341 // Trailing byte, so keep going backwards looking for the lead byte.
2342 }
2343 }
2344
2345 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2346 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2347 // so that they can be processed.
2348 return last - first;
2349}
2350
2351}
2352
2353// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2354// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2355// This matches the behavior of Linux.
Spencer Lowf373c352015-11-15 16:29:36 -08002356
2357// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2358static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2359 HANDLE console) {
Josh Gaoe7daf572016-09-21 12:37:10 -07002360 static std::mutex& console_output_buffer_lock = *new std::mutex();
2361 static auto& console_output_buffer = *new std::vector<char>();
2362
Spencer Lowf373c352015-11-15 16:29:36 -08002363 const int saved_errno = errno;
2364 std::vector<char> combined_buffer;
2365
2366 // Complete UTF-8 sequences that should be immediately written to the console.
2367 const char* utf8;
2368 size_t utf8_size;
2369
Josh Gaoe7daf572016-09-21 12:37:10 -07002370 {
2371 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2372 if (console_output_buffer.empty()) {
2373 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2374 // common case with plain ASCII), parse buf directly.
2375 utf8 = buf;
2376 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2377 } else {
2378 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2379 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2380 // combined_buffer, then parse it all together.
2381 combined_buffer.swap(console_output_buffer);
2382 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowf373c352015-11-15 16:29:36 -08002383
Josh Gaoe7daf572016-09-21 12:37:10 -07002384 utf8 = combined_buffer.data();
2385 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2386 &console_output_buffer);
2387 }
Spencer Lowf373c352015-11-15 16:29:36 -08002388 }
Spencer Lowf373c352015-11-15 16:29:36 -08002389
2390 std::wstring utf16;
2391
2392 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2393 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2394 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002395 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002396 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002397
2398 // Note that this does not do \n => \r\n translation because that
2399 // doesn't seem necessary for the Windows console. For the Windows
2400 // console \r moves to the beginning of the line and \n moves to a new
2401 // line.
2402
2403 // Flush any stream buffering so that our output is afterwards which
2404 // makes sense because our call is afterwards.
2405 (void)fflush(stream);
2406
2407 // Write UTF-16 to the console.
2408 DWORD written = 0;
Spencer Lowf373c352015-11-15 16:29:36 -08002409 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Low6815c072015-05-11 01:08:48 -07002410 errno = EIO;
2411 return -1;
2412 }
2413
Spencer Lowf373c352015-11-15 16:29:36 -08002414 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2415 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2416 // matches the Linux behavior.
2417 errno = saved_errno;
2418 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002419}
2420
2421// Function prototype because attributes cannot be placed on func definitions.
2422static int _console_vfprintf(const HANDLE console, FILE* stream,
2423 const char *format, va_list ap)
2424 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2425
2426// Internal function to format a UTF-8 string and write it to a Win32 console.
2427// Returns -1 on error.
2428static int _console_vfprintf(const HANDLE console, FILE* stream,
2429 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002430 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002431 std::string output_utf8;
2432
2433 // Format the string.
2434 // This could throw std::bad_alloc.
2435 android::base::StringAppendV(&output_utf8, format, ap);
2436
Spencer Lowf373c352015-11-15 16:29:36 -08002437 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2438 console);
2439 if (result != -1) {
2440 errno = saved_errno;
2441 } else {
2442 // If -1 was returned, errno has been set.
2443 }
2444 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002445}
2446
2447// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2448// Windows console.
2449int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2450 const HANDLE console = _get_console_handle(stream);
2451
2452 // If there is an associated Win32 console, write to it specially,
2453 // otherwise defer to the regular C Runtime, passing it UTF-8.
2454 if (console != NULL) {
2455 return _console_vfprintf(console, stream, format, ap);
2456 } else {
2457 // If vfprintf is a macro, undefine it, so we can call the real
2458 // C Runtime API.
2459#pragma push_macro("vfprintf")
2460#undef vfprintf
2461 return vfprintf(stream, format, ap);
2462#pragma pop_macro("vfprintf")
2463 }
2464}
2465
Spencer Lowf373c352015-11-15 16:29:36 -08002466// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2467int adb_vprintf(const char *format, va_list ap) {
2468 return adb_vfprintf(stdout, format, ap);
2469}
2470
Spencer Low6815c072015-05-11 01:08:48 -07002471// Version of fprintf() that takes UTF-8 and can write Unicode to a
2472// Windows console.
2473int adb_fprintf(FILE *stream, const char *format, ...) {
2474 va_list ap;
2475 va_start(ap, format);
2476 const int result = adb_vfprintf(stream, format, ap);
2477 va_end(ap);
2478
2479 return result;
2480}
2481
2482// Version of printf() that takes UTF-8 and can write Unicode to a
2483// Windows console.
2484int adb_printf(const char *format, ...) {
2485 va_list ap;
2486 va_start(ap, format);
2487 const int result = adb_vfprintf(stdout, format, ap);
2488 va_end(ap);
2489
2490 return result;
2491}
2492
2493// Version of fputs() that takes UTF-8 and can write Unicode to a
2494// Windows console.
2495int adb_fputs(const char* buf, FILE* stream) {
2496 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2497 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002498 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002499 return adb_fprintf(stream, "%s", buf);
2500}
2501
2502// Version of fputc() that takes UTF-8 and can write Unicode to a
2503// Windows console.
2504int adb_fputc(int ch, FILE* stream) {
2505 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002506 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002507 return EOF;
2508 }
2509 // For success, fputc returns the char, cast to unsigned char, then to int.
2510 return static_cast<unsigned char>(ch);
2511}
2512
Spencer Lowf373c352015-11-15 16:29:36 -08002513// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2514int adb_putchar(int ch) {
2515 return adb_fputc(ch, stdout);
2516}
2517
2518// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2519int adb_puts(const char* buf) {
2520 // adb_printf returns -1 on error, which is conveniently the same as EOF
2521 // which puts (and hence adb_puts) should return on error.
2522 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2523 return adb_printf("%s\n", buf);
2524}
2525
Spencer Low6815c072015-05-11 01:08:48 -07002526// Internal function to write UTF-8 to a Win32 console. Returns the number of
2527// items (of length size) written. On error, returns a short item count or 0.
2528static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2529 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002530 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2531 console);
Spencer Low6815c072015-05-11 01:08:48 -07002532 if (result == -1) {
2533 return 0;
2534 }
2535 return result / size;
2536}
2537
2538// Version of fwrite() that takes UTF-8 and can write Unicode to a
2539// Windows console.
2540size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2541 const HANDLE console = _get_console_handle(stream);
2542
2543 // If there is an associated Win32 console, write to it specially,
2544 // otherwise defer to the regular C Runtime, passing it UTF-8.
2545 if (console != NULL) {
2546 return _console_fwrite(ptr, size, nmemb, stream, console);
2547 } else {
2548 // If fwrite is a macro, undefine it, so we can call the real
2549 // C Runtime API.
2550#pragma push_macro("fwrite")
2551#undef fwrite
2552 return fwrite(ptr, size, nmemb, stream);
2553#pragma pop_macro("fwrite")
2554 }
2555}
2556
2557// Version of fopen() that takes a UTF-8 filename and can access a file with
2558// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002559FILE* adb_fopen(const char* path, const char* mode) {
2560 std::wstring path_wide;
2561 if (!android::base::UTF8ToWide(path, &path_wide)) {
2562 return nullptr;
2563 }
2564
2565 std::wstring mode_wide;
2566 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2567 return nullptr;
2568 }
2569
2570 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002571}
2572
Spencer Low50740f52015-09-08 17:13:04 -07002573// Return a lowercase version of the argument. Uses C Runtime tolower() on
2574// each byte which is not UTF-8 aware, and theoretically uses the current C
2575// Runtime locale (which in practice is not changed, so this becomes a ASCII
2576// conversion).
2577static std::string ToLower(const std::string& anycase) {
2578 // copy string
2579 std::string str(anycase);
2580 // transform the copy
2581 std::transform(str.begin(), str.end(), str.begin(), tolower);
2582 return str;
2583}
2584
2585extern "C" int main(int argc, char** argv);
2586
2587// Link with -municode to cause this wmain() to be used as the program
2588// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2589// regular main() with UTF-8 args.
2590extern "C" int wmain(int argc, wchar_t **argv) {
2591 // Convert args from UTF-16 to UTF-8 and pass that to main().
2592 NarrowArgs narrow_args(argc, argv);
2593 return main(argc, narrow_args.data());
2594}
2595
Spencer Low6815c072015-05-11 01:08:48 -07002596// Shadow UTF-8 environment variable name/value pairs that are created from
2597// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07002598// currently updated if putenv, setenv, unsetenv are called. Note that no
2599// thread synchronization is done, but we're called early enough in
2600// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002601static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002602
2603// Make sure that shadow UTF-8 environment variables are setup.
2604static void _ensure_env_setup() {
2605 // If some name/value pairs exist, then we've already done the setup below.
2606 if (g_environ_utf8.size() != 0) {
2607 return;
2608 }
2609
Spencer Low50740f52015-09-08 17:13:04 -07002610 if (_wenviron == nullptr) {
2611 // If _wenviron is null, then -municode probably wasn't used. That
2612 // linker flag will cause the entry point to setup _wenviron. It will
2613 // also require an implementation of wmain() (which we provide above).
2614 fatal("_wenviron is not set, did you link with -municode?");
2615 }
2616
Spencer Low6815c072015-05-11 01:08:48 -07002617 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2618 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2619 // to use the D() macro here because that tracing only works if the
2620 // ADB_TRACE environment variable is setup, but that env var can't be read
2621 // until this code completes.
2622 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2623 wchar_t* const equal = wcschr(*env, L'=');
2624 if (equal == nullptr) {
2625 // Malformed environment variable with no equal sign. Shouldn't
2626 // really happen, but we should be resilient to this.
2627 continue;
2628 }
2629
Spencer Low50f5bf12015-11-12 15:20:15 -08002630 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2631 // var because the program might never even read this particular variable.
2632 std::string name_utf8;
2633 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2634 continue;
2635 }
2636
Spencer Low50740f52015-09-08 17:13:04 -07002637 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002638 name_utf8 = ToLower(name_utf8);
2639
2640 std::string value_utf8;
2641 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2642 continue;
2643 }
2644
2645 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002646
Spencer Low50740f52015-09-08 17:13:04 -07002647 // Don't overwrite a previus env var with the same name. In reality,
2648 // the system probably won't let two env vars with the same name exist
2649 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002650 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002651 }
2652}
2653
2654// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002655// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002656char* adb_getenv(const char* name) {
2657 _ensure_env_setup();
2658
Spencer Low50740f52015-09-08 17:13:04 -07002659 // Case-insensitive search by searching for lowercase name in a map of
2660 // lowercase names.
2661 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002662 if (it == g_environ_utf8.end()) {
2663 return nullptr;
2664 }
2665
2666 return it->second;
2667}
2668
2669// Version of getcwd() that returns the current working directory in UTF-8.
2670char* adb_getcwd(char* buf, int size) {
2671 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2672 if (wbuf == nullptr) {
2673 return nullptr;
2674 }
2675
Spencer Low50f5bf12015-11-12 15:20:15 -08002676 std::string buf_utf8;
2677 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002678 free(wbuf);
2679 wbuf = nullptr;
2680
Spencer Low50f5bf12015-11-12 15:20:15 -08002681 if (!narrow_result) {
2682 return nullptr;
2683 }
2684
Spencer Low6815c072015-05-11 01:08:48 -07002685 // If size was specified, make sure all the chars will fit.
2686 if (size != 0) {
2687 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2688 errno = ERANGE;
2689 return nullptr;
2690 }
2691 }
2692
2693 // If buf was not specified, allocate storage.
2694 if (buf == nullptr) {
2695 if (size == 0) {
2696 size = buf_utf8.length() + 1;
2697 }
2698 buf = reinterpret_cast<char*>(malloc(size));
2699 if (buf == nullptr) {
2700 return nullptr;
2701 }
2702 }
2703
2704 // Destination buffer was allocated with enough space, or we've already
2705 // checked an existing buffer size for enough space.
2706 strcpy(buf, buf_utf8.c_str());
2707
2708 return buf;
2709}