blob: 5fda27b8aa6de67d6d3cfb8ce53bd751c07d3cb1 [file] [log] [blame]
Dan Albert33134262015-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 Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
30#include <string>
Spencer Lowcf4ff642015-05-11 01:08:48 -070031#include <unordered_map>
Josh Gao3777d2e2016-02-16 17:34:53 -080032#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070033
Elliott Hughesd48dbd82015-07-24 11:35:40 -070034#include <cutils/sockets.h>
35
David Pursell5f787ed2016-01-27 08:52:53 -080036#include <android-base/errors.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080037#include <android-base/logging.h>
38#include <android-base/stringprintf.h>
39#include <android-base/strings.h>
40#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070041
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#include "adb.h"
Josh Gao3777d2e2016-02-16 17:34:53 -080043#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080044
45extern void fatal(const char *fmt, ...);
46
Elliott Hughesa2f2e562015-04-16 16:47:02 -070047/* forward declarations */
48
49typedef const struct FHClassRec_* FHClass;
50typedef struct FHRec_* FH;
51typedef struct EventHookRec_* EventHook;
52
53typedef struct FHClassRec_ {
54 void (*_fh_init)(FH);
55 int (*_fh_close)(FH);
56 int (*_fh_lseek)(FH, int, int);
57 int (*_fh_read)(FH, void*, int);
58 int (*_fh_write)(FH, const void*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070059} FHClassRec;
60
61static void _fh_file_init(FH);
62static int _fh_file_close(FH);
63static int _fh_file_lseek(FH, int, int);
64static int _fh_file_read(FH, void*, int);
65static int _fh_file_write(FH, const void*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070066
67static const FHClassRec _fh_file_class = {
68 _fh_file_init,
69 _fh_file_close,
70 _fh_file_lseek,
71 _fh_file_read,
72 _fh_file_write,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070073};
74
75static void _fh_socket_init(FH);
76static int _fh_socket_close(FH);
77static int _fh_socket_lseek(FH, int, int);
78static int _fh_socket_read(FH, void*, int);
79static int _fh_socket_write(FH, const void*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070080
81static const FHClassRec _fh_socket_class = {
82 _fh_socket_init,
83 _fh_socket_close,
84 _fh_socket_lseek,
85 _fh_socket_read,
86 _fh_socket_write,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070087};
88
Josh Gao56e9bb92016-01-15 15:17:37 -080089#define assert(cond) \
90 do { \
91 if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \
92 } while (0)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080093
Spencer Low2122c7a2015-08-26 18:46:09 -070094void handle_deleter::operator()(HANDLE h) {
95 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
96 // implying that NULL is a valid handle, but this is probably impossible.
97 // Other APIs like CreateEvent() are documented to return NULL on error,
98 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
99 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
100 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
101 // only need to check for INVALID_HANDLE_VALUE.
102 if (h != INVALID_HANDLE_VALUE) {
103 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700104 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800105 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700106 }
107 }
108}
109
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800110/**************************************************************************/
111/**************************************************************************/
112/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800113/***** common file descriptor handling *****/
114/***** *****/
115/**************************************************************************/
116/**************************************************************************/
117
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800118typedef struct FHRec_
119{
120 FHClass clazz;
121 int used;
122 int eof;
123 union {
124 HANDLE handle;
125 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800126 } u;
127
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800128 int mask;
129
130 char name[32];
131
132} FHRec;
133
134#define fh_handle u.handle
135#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800136
Josh Gaob6232b92016-02-17 16:45:39 -0800137#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700138#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800139
140static adb_mutex_t _win32_lock;
141static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700142static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800143
144static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700145_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800146{
147 FH f;
148
149 fd -= WIN32_FH_BASE;
150
Spencer Lowc3211552015-07-24 15:38:19 -0700151 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700152 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700153 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800154 errno = EBADF;
155 return NULL;
156 }
157
158 f = &_win32_fhs[fd];
159
160 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700161 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700162 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800163 errno = EBADF;
164 return NULL;
165 }
166
167 return f;
168}
169
170
171static int
172_fh_to_int( FH f )
173{
174 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
175 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
176
177 return -1;
178}
179
180static FH
181_fh_alloc( FHClass clazz )
182{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800183 FH f = NULL;
184
185 adb_mutex_lock( &_win32_lock );
186
Josh Gaob6232b92016-02-17 16:45:39 -0800187 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
188 if (_win32_fhs[i].clazz == NULL) {
189 f = &_win32_fhs[i];
190 _win32_fh_next = i + 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800191 goto Exit;
192 }
193 }
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700194 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowc3211552015-07-24 15:38:19 -0700195 errno = EMFILE; // Too many open files
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800196Exit:
197 if (f) {
Spencer Lowc3211552015-07-24 15:38:19 -0700198 f->clazz = clazz;
199 f->used = 1;
200 f->eof = 0;
201 f->name[0] = '\0';
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800202 clazz->_fh_init(f);
203 }
204 adb_mutex_unlock( &_win32_lock );
205 return f;
206}
207
208
209static int
210_fh_close( FH f )
211{
Spencer Lowc3211552015-07-24 15:38:19 -0700212 // Use lock so that closing only happens once and so that _fh_alloc can't
213 // allocate a FH that we're in the middle of closing.
214 adb_mutex_lock(&_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800215
216 int offset = f - _win32_fhs;
217 if (_win32_fh_next > offset) {
218 _win32_fh_next = offset;
219 }
220
Spencer Lowc3211552015-07-24 15:38:19 -0700221 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800222 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700223 f->name[0] = '\0';
224 f->eof = 0;
225 f->used = 0;
226 f->clazz = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800227 }
Spencer Lowc3211552015-07-24 15:38:19 -0700228 adb_mutex_unlock(&_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800229 return 0;
230}
231
Spencer Low5200c662015-07-30 23:07:55 -0700232// Deleter for unique_fh.
233class fh_deleter {
234 public:
235 void operator()(struct FHRec_* fh) {
236 // We're called from a destructor and destructors should not overwrite
237 // errno because callers may do:
238 // errno = EBLAH;
239 // return -1; // calls destructor, which should not overwrite errno
240 const int saved_errno = errno;
241 _fh_close(fh);
242 errno = saved_errno;
243 }
244};
245
246// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
247typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
248
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800249/**************************************************************************/
250/**************************************************************************/
251/***** *****/
252/***** file-based descriptor handling *****/
253/***** *****/
254/**************************************************************************/
255/**************************************************************************/
256
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700257static void _fh_file_init( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 f->fh_handle = INVALID_HANDLE_VALUE;
259}
260
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700261static int _fh_file_close( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 CloseHandle( f->fh_handle );
263 f->fh_handle = INVALID_HANDLE_VALUE;
264 return 0;
265}
266
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700267static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800268 DWORD read_bytes;
269
270 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700271 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272 errno = EIO;
273 return -1;
274 } else if (read_bytes < (DWORD)len) {
275 f->eof = 1;
276 }
277 return (int)read_bytes;
278}
279
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700280static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281 DWORD wrote_bytes;
282
283 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700284 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800285 errno = EIO;
286 return -1;
287 } else if (wrote_bytes < (DWORD)len) {
288 f->eof = 1;
289 }
290 return (int)wrote_bytes;
291}
292
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700293static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800294 DWORD method;
295 DWORD result;
296
297 switch (origin)
298 {
299 case SEEK_SET: method = FILE_BEGIN; break;
300 case SEEK_CUR: method = FILE_CURRENT; break;
301 case SEEK_END: method = FILE_END; break;
302 default:
303 errno = EINVAL;
304 return -1;
305 }
306
307 result = SetFilePointer( f->fh_handle, pos, NULL, method );
308 if (result == INVALID_SET_FILE_POINTER) {
309 errno = EIO;
310 return -1;
311 } else {
312 f->eof = 0;
313 }
314 return (int)result;
315}
316
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800317
318/**************************************************************************/
319/**************************************************************************/
320/***** *****/
321/***** file-based descriptor handling *****/
322/***** *****/
323/**************************************************************************/
324/**************************************************************************/
325
326int adb_open(const char* path, int options)
327{
328 FH f;
329
330 DWORD desiredAccess = 0;
331 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
332
333 switch (options) {
334 case O_RDONLY:
335 desiredAccess = GENERIC_READ;
336 break;
337 case O_WRONLY:
338 desiredAccess = GENERIC_WRITE;
339 break;
340 case O_RDWR:
341 desiredAccess = GENERIC_READ | GENERIC_WRITE;
342 break;
343 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700344 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800345 errno = EINVAL;
346 return -1;
347 }
348
349 f = _fh_alloc( &_fh_file_class );
350 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351 return -1;
352 }
353
Spencer Lowd21dc822015-11-12 15:20:15 -0800354 std::wstring path_wide;
355 if (!android::base::UTF8ToWide(path, &path_wide)) {
356 return -1;
357 }
358 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700359 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800360
361 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700362 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700364 D( "adb_open: could not open '%s': ", path );
365 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800366 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700367 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800368 errno = ENOENT;
369 return -1;
370
371 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700372 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800373 errno = ENOTDIR;
374 return -1;
375
376 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800377 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800378 errno = ENOENT;
379 return -1;
380 }
381 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800382
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800383 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700384 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800385 return _fh_to_int(f);
386}
387
388/* ignore mode on Win32 */
389int adb_creat(const char* path, int mode)
390{
391 FH f;
392
393 f = _fh_alloc( &_fh_file_class );
394 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800395 return -1;
396 }
397
Spencer Lowd21dc822015-11-12 15:20:15 -0800398 std::wstring path_wide;
399 if (!android::base::UTF8ToWide(path, &path_wide)) {
400 return -1;
401 }
402 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700403 FILE_SHARE_READ | FILE_SHARE_WRITE,
404 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
405 NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800406
407 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700408 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700410 D( "adb_creat: could not open '%s': ", path );
411 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800412 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700413 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800414 errno = ENOENT;
415 return -1;
416
417 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700418 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419 errno = ENOTDIR;
420 return -1;
421
422 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800423 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424 errno = ENOENT;
425 return -1;
426 }
427 }
428 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700429 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800430 return _fh_to_int(f);
431}
432
433
434int adb_read(int fd, void* buf, int len)
435{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700436 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800437
438 if (f == NULL) {
439 return -1;
440 }
441
442 return f->clazz->_fh_read( f, buf, len );
443}
444
445
446int adb_write(int fd, const void* buf, int len)
447{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700448 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800449
450 if (f == NULL) {
451 return -1;
452 }
453
454 return f->clazz->_fh_write(f, buf, len);
455}
456
457
458int adb_lseek(int fd, int pos, int where)
459{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700460 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800461
462 if (!f) {
463 return -1;
464 }
465
466 return f->clazz->_fh_lseek(f, pos, where);
467}
468
469
470int adb_close(int fd)
471{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700472 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473
474 if (!f) {
475 return -1;
476 }
477
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700478 D( "adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 _fh_close(f);
480 return 0;
481}
482
Spencer Low0a796002015-10-18 16:45:09 -0700483// Overrides strerror() to handle error codes not supported by the Windows C
484// Runtime (MSVCRT.DLL).
485char* adb_strerror(int err) {
486 // sysdeps.h defines strerror to adb_strerror, but in this function, we
487 // want to call the real C Runtime strerror().
488#pragma push_macro("strerror")
489#undef strerror
490 const int saved_err = errno; // Save because we overwrite it later.
491
492 // Lookup the string for an unknown error.
493 char* errmsg = strerror(-1);
Elliott Hughes6d929972015-10-27 13:40:35 -0700494 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low0a796002015-10-18 16:45:09 -0700495
496 // Lookup the string for this error to see if the C Runtime has it.
497 errmsg = strerror(err);
Elliott Hughes6d929972015-10-27 13:40:35 -0700498 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low0a796002015-10-18 16:45:09 -0700499 // The CRT returned an error message and it is different than the error
500 // message for an unknown error, so it is probably valid, so use it.
501 } else {
502 // Check if we have a string for this error code.
503 const char* custom_msg = nullptr;
504 switch (err) {
505#pragma push_macro("ERR")
506#undef ERR
507#define ERR(errnum, desc) case errnum: custom_msg = desc; break
508 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
509 // Note that these cannot be longer than 94 characters because we
510 // pass this to _strerror() which has that requirement.
511 ERR(ECONNRESET, "Connection reset by peer");
512 ERR(EHOSTUNREACH, "No route to host");
513 ERR(ENETDOWN, "Network is down");
514 ERR(ENETRESET, "Network dropped connection because of reset");
515 ERR(ENOBUFS, "No buffer space available");
516 ERR(ENOPROTOOPT, "Protocol not available");
517 ERR(ENOTCONN, "Transport endpoint is not connected");
518 ERR(ENOTSOCK, "Socket operation on non-socket");
519 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
520#pragma pop_macro("ERR")
521 }
522
523 if (custom_msg != nullptr) {
524 // Use _strerror() to write our string into the writable per-thread
525 // buffer used by strerror()/_strerror(). _strerror() appends the
526 // msg for the current value of errno, so set errno to a consistent
527 // value for every call so that our code-path is always the same.
528 errno = 0;
529 errmsg = _strerror(custom_msg);
530 const size_t custom_msg_len = strlen(custom_msg);
531 // Just in case _strerror() returned a read-only string, check if
532 // the returned string starts with our custom message because that
533 // implies that the string is not read-only.
534 if ((errmsg != nullptr) &&
535 !strncmp(custom_msg, errmsg, custom_msg_len)) {
536 // _strerror() puts other text after our custom message, so
537 // remove that by terminating after our message.
538 errmsg[custom_msg_len] = '\0';
539 } else {
540 // For some reason nullptr was returned or a pointer to a
541 // read-only string was returned, so fallback to whatever
542 // strerror() can muster (probably "Unknown error" or some
543 // generic CRT error string).
544 errmsg = strerror(err);
545 }
546 } else {
547 // We don't have a custom message, so use whatever strerror(err)
548 // returned earlier.
549 }
550 }
551
552 errno = saved_err; // restore
553
554 return errmsg;
555#pragma pop_macro("strerror")
556}
557
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558/**************************************************************************/
559/**************************************************************************/
560/***** *****/
561/***** socket-based file descriptors *****/
562/***** *****/
563/**************************************************************************/
564/**************************************************************************/
565
Spencer Lowf055c192015-01-25 14:40:16 -0800566#undef setsockopt
567
Spencer Low5200c662015-07-30 23:07:55 -0700568static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700569 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
570 // lot of POSIX and socket error codes, some of the resulting error codes
571 // are mapped to strings by adb_strerror() above.
Spencer Low5200c662015-07-30 23:07:55 -0700572 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800573 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700574 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
575 // case WSAEINTR: errno = EINTR; break;
576 case WSAEFAULT: errno = EFAULT; break;
577 case WSAEINVAL: errno = EINVAL; break;
578 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700579 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
580 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
581 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800582 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700583 case WSAENOTSOCK: errno = ENOTSOCK; break;
584 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
585 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
586 case WSAENETDOWN: errno = ENETDOWN; break;
587 case WSAENETRESET: errno = ENETRESET; break;
588 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
589 // to use EPIPE for these situations and there are some callers that look
590 // for EPIPE.
591 case WSAECONNABORTED: errno = EPIPE; break;
592 case WSAECONNRESET: errno = ECONNRESET; break;
593 case WSAENOBUFS: errno = ENOBUFS; break;
594 case WSAENOTCONN: errno = ENOTCONN; break;
595 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
596 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
597 // considerations: Reportedly send() can return zero on timeout, and POSIX
598 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
599 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
600 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800601 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700603 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700604 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800605 }
606}
607
Josh Gao3777d2e2016-02-16 17:34:53 -0800608extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
609 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
610 int skipped = 0;
611 std::vector<WSAPOLLFD> sockets;
612 std::vector<adb_pollfd*> original;
613 for (size_t i = 0; i < nfds; ++i) {
614 FH fh = _fh_from_int(fds[i].fd, __func__);
615 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
616 D("adb_poll received bad FD %d", fds[i].fd);
617 fds[i].revents = POLLNVAL;
618 ++skipped;
619 } else {
620 WSAPOLLFD wsapollfd = {
621 .fd = fh->u.socket,
622 .events = static_cast<short>(fds[i].events)
623 };
624 sockets.push_back(wsapollfd);
625 original.push_back(&fds[i]);
626 }
Spencer Low5200c662015-07-30 23:07:55 -0700627 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800628
629 if (sockets.empty()) {
630 return skipped;
631 }
632
633 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
634 if (result == SOCKET_ERROR) {
635 _socket_set_errno(WSAGetLastError());
636 return -1;
637 }
638
639 // Map the results back onto the original set.
640 for (size_t i = 0; i < sockets.size(); ++i) {
641 original[i]->revents = sockets[i].revents;
642 }
643
644 // WSAPoll appears to return the number of unique FDs with avaiable events, instead of how many
645 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
646 // to do. Ignore its result and calculate the proper return value.
647 result = 0;
648 for (size_t i = 0; i < nfds; ++i) {
649 if (fds[i].revents != 0) {
650 ++result;
651 }
652 }
653 return result;
654}
655
656static void _fh_socket_init(FH f) {
657 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658 f->mask = 0;
659}
660
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700661static int _fh_socket_close( FH f ) {
Spencer Low5200c662015-07-30 23:07:55 -0700662 if (f->fh_socket != INVALID_SOCKET) {
663 /* gently tell any peer that we're closing the socket */
664 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
665 // If the socket is not connected, this returns an error. We want to
666 // minimize logging spam, so don't log these errors for now.
667#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700668 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800669 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700670#endif
671 }
672 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800673 // Don't set errno here, since adb_close will ignore it.
674 const DWORD err = WSAGetLastError();
675 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700676 }
677 f->fh_socket = INVALID_SOCKET;
678 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679 f->mask = 0;
680 return 0;
681}
682
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700683static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800684 errno = EPIPE;
685 return -1;
686}
687
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700688static int _fh_socket_read(FH f, void* buf, int len) {
689 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800690 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700691 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700692 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
693 // that to reduce spam and confusion.
694 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700695 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800696 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700697 }
Spencer Low5200c662015-07-30 23:07:55 -0700698 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800699 result = -1;
700 }
701 return result;
702}
703
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700704static int _fh_socket_write(FH f, const void* buf, int len) {
705 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800706 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700707 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700708 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
709 // that to reduce spam and confusion.
710 if (err != WSAEWOULDBLOCK) {
711 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800712 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700713 }
Spencer Low5200c662015-07-30 23:07:55 -0700714 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700716 } else {
717 // According to https://code.google.com/p/chromium/issues/detail?id=27870
718 // Winsock Layered Service Providers may cause this.
719 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
720 << f->name << ", but " << result
721 << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800722 }
723 return result;
724}
725
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726/**************************************************************************/
727/**************************************************************************/
728/***** *****/
729/***** replacement for libs/cutils/socket_xxxx.c *****/
730/***** *****/
731/**************************************************************************/
732/**************************************************************************/
733
734#include <winsock2.h>
735
736static int _winsock_init;
737
738static void
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739_init_winsock( void )
740{
Spencer Low5200c662015-07-30 23:07:55 -0700741 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Low87e97ee2015-08-12 18:19:16 -0700742 // to WSAStartup() which offers no real benefit.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800743 if (!_winsock_init) {
744 WSADATA wsaData;
745 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
746 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800747 fatal("adb: could not initialize Winsock: %s",
748 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800749 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800750 _winsock_init = 1;
Spencer Low87e97ee2015-08-12 18:19:16 -0700751
752 // Note that we do not call atexit() to register WSACleanup to be called
753 // at normal process termination because:
754 // 1) When exit() is called, there are still threads actively using
755 // Winsock because we don't cleanly shutdown all threads, so it
756 // doesn't make sense to call WSACleanup() and may cause problems
757 // with those threads.
758 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
759 // calls WSACleanup() which tries to unload a DLL, which tries to
760 // grab the LoaderLock. This conflicts with the device_poll_thread
761 // which holds the LoaderLock because AdbWinApi.dll calls
762 // setupapi.dll which tries to load wintrust.dll which tries to load
763 // crypt32.dll which calls atexit() which tries to acquire the C
764 // Runtime lock that the other thread holds.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800765 }
766}
767
Spencer Low677fb432015-09-29 15:05:29 -0700768// Map a socket type to an explicit socket protocol instead of using the socket
769// protocol of 0. Explicit socket protocols are used by most apps and we should
770// do the same to reduce the chance of exercising uncommon code-paths that might
771// have problems or that might load different Winsock service providers that
772// have problems.
773static int GetSocketProtocolFromSocketType(int type) {
774 switch (type) {
775 case SOCK_STREAM:
776 return IPPROTO_TCP;
777 case SOCK_DGRAM:
778 return IPPROTO_UDP;
779 default:
780 LOG(FATAL) << "Unknown socket type: " << type;
781 return 0;
782 }
783}
784
Spencer Low5200c662015-07-30 23:07:55 -0700785int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800787 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800788
Josh Gao6487e742016-02-18 13:43:55 -0800789 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700790 if (!f) {
791 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800792 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700793 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800794
Josh Gao6487e742016-02-18 13:43:55 -0800795 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800796
797 memset(&addr, 0, sizeof(addr));
798 addr.sin_family = AF_INET;
799 addr.sin_port = htons(port);
800 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
801
Spencer Low677fb432015-09-29 15:05:29 -0700802 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800803 if (s == INVALID_SOCKET) {
804 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700805 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800806 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700807 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800808 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700809 return -1;
810 }
811 f->fh_socket = s;
812
Josh Gao6487e742016-02-18 13:43:55 -0800813 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700814 // Save err just in case inet_ntoa() or ntohs() changes the last error.
815 const DWORD err = WSAGetLastError();
816 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800817 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
818 android::base::SystemErrorCodeToString(err).c_str());
819 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
820 error->c_str());
821 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 return -1;
823 }
824
Spencer Low5200c662015-07-30 23:07:55 -0700825 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800826 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
827 port);
828 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700829 f.release();
830 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800831}
832
833#define LISTEN_BACKLOG 4
834
Spencer Low5200c662015-07-30 23:07:55 -0700835// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800836static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800837 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800838 SOCKET s;
839 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800840
Josh Gao6487e742016-02-18 13:43:55 -0800841 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800842 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700843 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844 return -1;
845 }
846
Josh Gao6487e742016-02-18 13:43:55 -0800847 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848
849 memset(&addr, 0, sizeof(addr));
850 addr.sin_family = AF_INET;
851 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700852 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853
Spencer Low5200c662015-07-30 23:07:55 -0700854 // TODO: Consider using dual-stack socket that can simultaneously listen on
855 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700856 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700857 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800858 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700859 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800860 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700861 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800862 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700863 return -1;
864 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800865
866 f->fh_socket = s;
867
Spencer Lowbf7c6052015-08-11 16:45:32 -0700868 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
869 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800870 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800871 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
872 const DWORD err = WSAGetLastError();
873 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
874 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700875 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800876 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700877 return -1;
878 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800879
Josh Gao6487e742016-02-18 13:43:55 -0800880 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700881 // Save err just in case inet_ntoa() or ntohs() changes the last error.
882 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800883 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
884 ntohs(addr.sin_port),
885 android::base::SystemErrorCodeToString(err).c_str());
886 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
887 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800888 return -1;
889 }
890 if (type == SOCK_STREAM) {
Spencer Low5200c662015-07-30 23:07:55 -0700891 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800892 const DWORD err = WSAGetLastError();
893 *error = android::base::StringPrintf(
894 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
895 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
896 error->c_str());
897 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800898 return -1;
899 }
900 }
Spencer Low5200c662015-07-30 23:07:55 -0700901 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800902 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
903 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
904 port);
905 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700906 f.release();
907 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800908}
909
Spencer Low5200c662015-07-30 23:07:55 -0700910int network_loopback_server(int port, int type, std::string* error) {
911 return _network_server(port, type, INADDR_LOOPBACK, error);
912}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800913
Spencer Low5200c662015-07-30 23:07:55 -0700914int network_inaddr_any_server(int port, int type, std::string* error) {
915 return _network_server(port, type, INADDR_ANY, error);
916}
917
918int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
919 unique_fh f(_fh_alloc(&_fh_socket_class));
920 if (!f) {
921 *error = strerror(errno);
922 return -1;
923 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800924
Elliott Hughes381cfa92015-07-23 17:12:58 -0700925 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800926
Spencer Low5200c662015-07-30 23:07:55 -0700927 struct addrinfo hints;
928 memset(&hints, 0, sizeof(hints));
929 hints.ai_family = AF_UNSPEC;
930 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700931 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700932
933 char port_str[16];
934 snprintf(port_str, sizeof(port_str), "%d", port);
935
936 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700937
938#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800939// TODO: When the Android SDK tools increases the Windows system
940// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700941#else
Josh Gao6487e742016-02-18 13:43:55 -0800942// Otherwise, keep using getaddrinfo(), or do runtime API detection
943// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700944#endif
Spencer Low5200c662015-07-30 23:07:55 -0700945 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800946 const DWORD err = WSAGetLastError();
947 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
948 host.c_str(), port_str,
949 android::base::SystemErrorCodeToString(err).c_str());
950
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700951 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800952 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800953 return -1;
954 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700955 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700956 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800957
Spencer Low5200c662015-07-30 23:07:55 -0700958 // TODO: Try all the addresses if there's more than one? This just uses
959 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
960 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800961 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
962 if (s == INVALID_SOCKET) {
963 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700964 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800965 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700966 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800967 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800968 return -1;
969 }
970 f->fh_socket = s;
971
Spencer Low5200c662015-07-30 23:07:55 -0700972 // TODO: Implement timeouts for Windows. Seems like the default in theory
973 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800974 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700975 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800976 const DWORD err = WSAGetLastError();
977 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
978 android::base::SystemErrorCodeToString(err).c_str());
979 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
980 port_str, error->c_str());
981 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800982 return -1;
983 }
984
Spencer Low5200c662015-07-30 23:07:55 -0700985 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800986 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
987 port);
988 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
989 fd);
Spencer Low5200c662015-07-30 23:07:55 -0700990 f.release();
991 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800992}
993
994#undef accept
995int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
996{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700997 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200998
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800999 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001000 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -07001001 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001002 return -1;
1003 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001004
Spencer Low5200c662015-07-30 23:07:55 -07001005 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001006 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001007 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1008 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001009 return -1;
1010 }
1011
1012 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1013 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001014 const DWORD err = WSAGetLastError();
Spencer Low5200c662015-07-30 23:07:55 -07001015 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursell5f787ed2016-01-27 08:52:53 -08001016 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low5200c662015-07-30 23:07:55 -07001017 _socket_set_errno( err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 return -1;
1019 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001020
Spencer Low5200c662015-07-30 23:07:55 -07001021 const int fd = _fh_to_int(fh.get());
1022 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001023 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low5200c662015-07-30 23:07:55 -07001024 fh.release();
1025 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001026}
1027
1028
Spencer Lowf055c192015-01-25 14:40:16 -08001029int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001030{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001031 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001032
Spencer Lowf055c192015-01-25 14:40:16 -08001033 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001034 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001035 errno = EBADF;
1036 return -1;
1037 }
Spencer Low677fb432015-09-29 15:05:29 -07001038
1039 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1040 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1041 // auto-tuning.
1042
Spencer Low5200c662015-07-30 23:07:55 -07001043 int result = setsockopt( fh->fh_socket, level, optname,
1044 reinterpret_cast<const char*>(optval), optlen );
1045 if ( result == SOCKET_ERROR ) {
1046 const DWORD err = WSAGetLastError();
David Pursell5f787ed2016-01-27 08:52:53 -08001047 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1048 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001049 _socket_set_errno( err );
1050 result = -1;
1051 }
1052 return result;
1053}
1054
Josh Gao3777d2e2016-02-16 17:34:53 -08001055int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1056 FH fh = _fh_from_int(fd, __func__);
1057
1058 if (!fh || fh->clazz != &_fh_socket_class) {
1059 D("adb_getsockname: invalid fd %d", fd);
1060 errno = EBADF;
1061 return -1;
1062 }
1063
Josh Gao59901912016-08-23 15:28:43 -07001064 int result = (getsockname)(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001065 if (result == SOCKET_ERROR) {
1066 const DWORD err = WSAGetLastError();
1067 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1068 android::base::SystemErrorCodeToString(err).c_str());
1069 _socket_set_errno(err);
1070 result = -1;
1071 }
1072 return result;
1073}
Spencer Low5200c662015-07-30 23:07:55 -07001074
David Purselleaae97e2016-04-07 11:25:48 -07001075int adb_socket_get_local_port(int fd) {
1076 sockaddr_storage addr_storage;
1077 socklen_t addr_len = sizeof(addr_storage);
1078
1079 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1080 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1081 return -1;
1082 }
1083
1084 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1085 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1086 errno = ECONNABORTED;
1087 return -1;
1088 }
1089
1090 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1091}
1092
Spencer Low5200c662015-07-30 23:07:55 -07001093int adb_shutdown(int fd)
1094{
1095 FH f = _fh_from_int(fd, __func__);
1096
1097 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001098 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001099 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001100 return -1;
1101 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001102
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001103 D( "adb_shutdown: %s", f->name);
Spencer Low5200c662015-07-30 23:07:55 -07001104 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1105 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001106 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001107 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001108 _socket_set_errno(err);
1109 return -1;
1110 }
1111 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001112}
1113
Josh Gao3777d2e2016-02-16 17:34:53 -08001114// Emulate socketpair(2) by binding and connecting to a socket.
1115int adb_socketpair(int sv[2]) {
1116 int server = -1;
1117 int client = -1;
1118 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001119 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001120 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001121
Josh Gao59901912016-08-23 15:28:43 -07001122 struct sockaddr_storage peer_addr = {};
1123 struct sockaddr_storage client_addr = {};
1124 socklen_t peer_socklen = sizeof(peer_addr);
1125 socklen_t client_socklen = sizeof(client_addr);
1126
Josh Gao3777d2e2016-02-16 17:34:53 -08001127 server = network_loopback_server(0, SOCK_STREAM, &error);
1128 if (server < 0) {
1129 D("adb_socketpair: failed to create server: %s", error.c_str());
1130 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001131 }
1132
David Purselleaae97e2016-04-07 11:25:48 -07001133 local_port = adb_socket_get_local_port(server);
1134 if (local_port < 0) {
1135 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001136 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001137 }
David Purselleaae97e2016-04-07 11:25:48 -07001138 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001139
David Purselleaae97e2016-04-07 11:25:48 -07001140 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001141 if (client < 0) {
1142 D("adb_socketpair: failed to connect client: %s", error.c_str());
1143 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001144 }
1145
Josh Gao59901912016-08-23 15:28:43 -07001146 // Make sure that the peer that connected to us and the client are the same.
1147 accepted = adb_socket_accept(server, reinterpret_cast<sockaddr*>(&peer_addr), &peer_socklen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001148 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001149 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001150 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001151 }
Josh Gao59901912016-08-23 15:28:43 -07001152
1153 if (adb_getsockname(client, reinterpret_cast<sockaddr*>(&client_addr), &client_socklen) != 0) {
1154 D("adb_socketpair: failed to getpeername: %s", strerror(errno));
1155 goto fail;
1156 }
1157
1158 if (peer_socklen != client_socklen) {
1159 D("adb_socketpair: client and peer sockaddrs have different lengths");
1160 errno = EIO;
1161 goto fail;
1162 }
1163
1164 if (memcmp(&peer_addr, &client_addr, peer_socklen) != 0) {
1165 D("adb_socketpair: client and peer sockaddrs don't match");
1166 errno = EIO;
1167 goto fail;
1168 }
1169
Josh Gao3777d2e2016-02-16 17:34:53 -08001170 adb_close(server);
Josh Gao59901912016-08-23 15:28:43 -07001171
Josh Gao3777d2e2016-02-16 17:34:53 -08001172 sv[0] = client;
1173 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001174 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001175
Josh Gao3777d2e2016-02-16 17:34:53 -08001176fail:
1177 if (server >= 0) {
1178 adb_close(server);
1179 }
1180 if (client >= 0) {
1181 adb_close(client);
1182 }
1183 if (accepted >= 0) {
1184 adb_close(accepted);
1185 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001186 return -1;
1187}
1188
Josh Gao3777d2e2016-02-16 17:34:53 -08001189bool set_file_block_mode(int fd, bool block) {
1190 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001191
Josh Gao3777d2e2016-02-16 17:34:53 -08001192 if (!fh || !fh->used) {
1193 errno = EBADF;
1194 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001195 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001196
Josh Gao3777d2e2016-02-16 17:34:53 -08001197 if (fh->clazz == &_fh_socket_class) {
1198 u_long x = !block;
1199 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
1200 _socket_set_errno(WSAGetLastError());
1201 return false;
1202 }
1203 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001204 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001205 errno = ENOTSOCK;
1206 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001207 }
1208}
1209
David Pursellbfd95032016-02-22 14:27:23 -08001210bool set_tcp_keepalive(int fd, int interval_sec) {
1211 FH fh = _fh_from_int(fd, __func__);
1212
1213 if (!fh || fh->clazz != &_fh_socket_class) {
1214 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1215 errno = EBADF;
1216 return false;
1217 }
1218
1219 tcp_keepalive keepalive;
1220 keepalive.onoff = (interval_sec > 0);
1221 keepalive.keepalivetime = interval_sec * 1000;
1222 keepalive.keepaliveinterval = interval_sec * 1000;
1223
1224 DWORD bytes_returned = 0;
1225 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1226 &bytes_returned, nullptr, nullptr) != 0) {
1227 const DWORD err = WSAGetLastError();
1228 D("set_tcp_keepalive(%d) failed: %s", fd,
1229 android::base::SystemErrorCodeToString(err).c_str());
1230 _socket_set_errno(err);
1231 return false;
1232 }
1233
1234 return true;
1235}
1236
Spencer Lowa30b79a2015-11-15 16:29:36 -08001237static adb_mutex_t g_console_output_buffer_lock;
1238
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001239void
1240adb_sysdeps_init( void )
1241{
1242#define ADB_MUTEX(x) InitializeCriticalSection( & x );
1243#include "mutex_list.h"
1244 InitializeCriticalSection( &_win32_lock );
Spencer Lowa30b79a2015-11-15 16:29:36 -08001245 InitializeCriticalSection( &g_console_output_buffer_lock );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001246}
1247
Spencer Low50184062015-03-01 15:06:21 -08001248/**************************************************************************/
1249/**************************************************************************/
1250/***** *****/
1251/***** Console Window Terminal Emulation *****/
1252/***** *****/
1253/**************************************************************************/
1254/**************************************************************************/
1255
1256// This reads input from a Win32 console window and translates it into Unix
1257// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1258// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1259// is emulated instead of xterm because it is probably more popular than xterm:
1260// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1261// supports modern fonts, etc. It seems best to emulate the terminal that most
1262// Android developers use because they'll fix apps (the shell, etc.) to keep
1263// working with that terminal's emulation.
1264//
1265// The point of this emulation is not to be perfect or to solve all issues with
1266// console windows on Windows, but to be better than the original code which
1267// just called read() (which called ReadFile(), which called ReadConsoleA())
1268// which did not support Ctrl-C, tab completion, shell input line editing
1269// keys, server echo, and more.
1270//
1271// This implementation reconfigures the console with SetConsoleMode(), then
1272// calls ReadConsoleInput() to get raw input which it remaps to Unix
1273// terminal-style sequences which is returned via unix_read() which is used
1274// by the 'adb shell' command.
1275//
1276// Code organization:
1277//
David Pursellc5b8ad82015-10-28 14:29:51 -07001278// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001279// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1280// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1281// * _console_read() is the main code of the emulation.
1282
David Pursellc5b8ad82015-10-28 14:29:51 -07001283// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1284// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1285// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1286static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1287 // First check isatty(); this is very fast and eliminates most non-console
1288 // FDs, but returns 1 for both consoles and character devices like NUL.
1289#pragma push_macro("isatty")
1290#undef isatty
1291 if (!isatty(fd)) {
1292 return nullptr;
1293 }
1294#pragma pop_macro("isatty")
1295
1296 // To differentiate between character devices and consoles we need to get
1297 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1298 // GENERIC_READ permissions.
1299 const intptr_t intptr_handle = _get_osfhandle(fd);
1300 if (intptr_handle == -1) {
1301 return nullptr;
1302 }
1303 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1304 DWORD temp_mode = 0;
1305 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1306 return nullptr;
1307 }
1308
1309 return handle;
1310}
1311
1312// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1313static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001314 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1315 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001316 const int fd = fileno(stream);
1317 if (fd < 0) {
1318 return nullptr;
1319 }
1320 return _get_console_handle(fd);
1321}
1322
1323int unix_isatty(int fd) {
1324 return _get_console_handle(fd) ? 1 : 0;
1325}
Spencer Low50184062015-03-01 15:06:21 -08001326
Spencer Low32762f42015-11-10 19:17:16 -08001327// Get the next KEY_EVENT_RECORD that should be processed.
1328static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001329 for (;;) {
1330 DWORD read_count = 0;
1331 memset(input_record, 0, sizeof(*input_record));
1332 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001333 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001334 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001335 errno = EIO;
1336 return false;
1337 }
1338
1339 if (read_count == 0) { // should be impossible
1340 fatal("ReadConsoleInputA returned 0");
1341 }
1342
1343 if (read_count != 1) { // should be impossible
1344 fatal("ReadConsoleInputA did not return one input record");
1345 }
1346
Spencer Low2e02dc62015-11-07 17:34:39 -08001347 // If the console window is resized, emulate SIGWINCH by breaking out
1348 // of read() with errno == EINTR. Note that there is no event on
1349 // vertical resize because we don't give the console our own custom
1350 // screen buffer (with CreateConsoleScreenBuffer() +
1351 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1352 // supports scrollback, but doesn't seem to raise an event for vertical
1353 // window resize.
1354 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1355 errno = EINTR;
1356 return false;
1357 }
1358
Spencer Low50184062015-03-01 15:06:21 -08001359 if ((input_record->EventType == KEY_EVENT) &&
1360 (input_record->Event.KeyEvent.bKeyDown)) {
1361 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1362 fatal("ReadConsoleInputA returned a key event with zero repeat"
1363 " count");
1364 }
1365
1366 // Got an interesting INPUT_RECORD, so return
1367 return true;
1368 }
1369 }
1370}
1371
Spencer Low50184062015-03-01 15:06:21 -08001372static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1373 return (control_key_state & SHIFT_PRESSED) != 0;
1374}
1375
1376static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1377 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1378}
1379
1380static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1381 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1382}
1383
1384static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1385 return (control_key_state & NUMLOCK_ON) != 0;
1386}
1387
1388static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1389 return (control_key_state & CAPSLOCK_ON) != 0;
1390}
1391
1392static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1393 return (control_key_state & ENHANCED_KEY) != 0;
1394}
1395
1396// Constants from MSDN for ToAscii().
1397static const BYTE TOASCII_KEY_OFF = 0x00;
1398static const BYTE TOASCII_KEY_DOWN = 0x80;
1399static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1400
1401// Given a key event, ignore a modifier key and return the character that was
1402// entered without the modifier. Writes to *ch and returns the number of bytes
1403// written.
1404static size_t _get_char_ignoring_modifier(char* const ch,
1405 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1406 const WORD modifier) {
1407 // If there is no character from Windows, try ignoring the specified
1408 // modifier and look for a character. Note that if AltGr is being used,
1409 // there will be a character from Windows.
1410 if (key_event->uChar.AsciiChar == '\0') {
1411 // Note that we read the control key state from the passed in argument
1412 // instead of from key_event since the argument has been normalized.
1413 if (((modifier == VK_SHIFT) &&
1414 _is_shift_pressed(control_key_state)) ||
1415 ((modifier == VK_CONTROL) &&
1416 _is_ctrl_pressed(control_key_state)) ||
1417 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1418
1419 BYTE key_state[256] = {0};
1420 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1421 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1422 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1423 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1424 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1425 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1426 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1427 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1428
1429 // cause this modifier to be ignored
1430 key_state[modifier] = TOASCII_KEY_OFF;
1431
1432 WORD translated = 0;
1433 if (ToAscii(key_event->wVirtualKeyCode,
1434 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1435 // Ignoring the modifier, we found a character.
1436 *ch = (CHAR)translated;
1437 return 1;
1438 }
1439 }
1440 }
1441
1442 // Just use whatever Windows told us originally.
1443 *ch = key_event->uChar.AsciiChar;
1444
1445 // If the character from Windows is NULL, return a size of zero.
1446 return (*ch == '\0') ? 0 : 1;
1447}
1448
1449// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1450// but taking into account the shift key. This is because for a sequence like
1451// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1452// we want to find the character ')'.
1453//
1454// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1455// because it is the default key-sequence to switch the input language.
1456// This is configurable in the Region and Language control panel.
1457static __inline__ size_t _get_non_control_char(char* const ch,
1458 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1459 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1460 VK_CONTROL);
1461}
1462
1463// Get without Alt.
1464static __inline__ size_t _get_non_alt_char(char* const ch,
1465 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1466 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1467 VK_MENU);
1468}
1469
1470// Ignore the control key, find the character from Windows, and apply any
1471// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1472// *pch and returns number of bytes written.
1473static size_t _get_control_character(char* const pch,
1474 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1475 const size_t len = _get_non_control_char(pch, key_event,
1476 control_key_state);
1477
1478 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1479 char ch = *pch;
1480 switch (ch) {
1481 case '2':
1482 case '@':
1483 case '`':
1484 ch = '\0';
1485 break;
1486 case '3':
1487 case '[':
1488 case '{':
1489 ch = '\x1b';
1490 break;
1491 case '4':
1492 case '\\':
1493 case '|':
1494 ch = '\x1c';
1495 break;
1496 case '5':
1497 case ']':
1498 case '}':
1499 ch = '\x1d';
1500 break;
1501 case '6':
1502 case '^':
1503 case '~':
1504 ch = '\x1e';
1505 break;
1506 case '7':
1507 case '-':
1508 case '_':
1509 ch = '\x1f';
1510 break;
1511 case '8':
1512 ch = '\x7f';
1513 break;
1514 case '/':
1515 if (!_is_alt_pressed(control_key_state)) {
1516 ch = '\x1f';
1517 }
1518 break;
1519 case '?':
1520 if (!_is_alt_pressed(control_key_state)) {
1521 ch = '\x7f';
1522 }
1523 break;
1524 }
1525 *pch = ch;
1526 }
1527
1528 return len;
1529}
1530
1531static DWORD _normalize_altgr_control_key_state(
1532 const KEY_EVENT_RECORD* const key_event) {
1533 DWORD control_key_state = key_event->dwControlKeyState;
1534
1535 // If we're in an AltGr situation where the AltGr key is down (depending on
1536 // the keyboard layout, that might be the physical right alt key which
1537 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1538 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1539 // a character (which indicates that there was an AltGr mapping), then act
1540 // as if alt and control are not really down for the purposes of modifiers.
1541 // This makes it so that if the user with, say, a German keyboard layout
1542 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1543 // output the key and we don't see the Alt and Ctrl keys.
1544 if (_is_ctrl_pressed(control_key_state) &&
1545 _is_alt_pressed(control_key_state)
1546 && (key_event->uChar.AsciiChar != '\0')) {
1547 // Try to remove as few bits as possible to improve our chances of
1548 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1549 // Left-Alt + Right-Ctrl + AltGr.
1550 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1551 // Remove Right-Alt.
1552 control_key_state &= ~RIGHT_ALT_PRESSED;
1553 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1554 // pressed, Left-Ctrl is almost always set, except if the user
1555 // presses Right-Ctrl, then AltGr (in that specific order) for
1556 // whatever reason. At any rate, make sure the bit is not set.
1557 control_key_state &= ~LEFT_CTRL_PRESSED;
1558 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1559 // Remove Left-Alt.
1560 control_key_state &= ~LEFT_ALT_PRESSED;
1561 // Whichever Ctrl key is down, remove it from the state. We only
1562 // remove one key, to improve our chances of detecting the
1563 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1564 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1565 // Remove Left-Ctrl.
1566 control_key_state &= ~LEFT_CTRL_PRESSED;
1567 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1568 // Remove Right-Ctrl.
1569 control_key_state &= ~RIGHT_CTRL_PRESSED;
1570 }
1571 }
1572
1573 // Note that this logic isn't 100% perfect because Windows doesn't
1574 // allow us to detect all combinations because a physical AltGr key
1575 // press shows up as two bits, plus some combinations are ambiguous
1576 // about what is actually physically pressed.
1577 }
1578
1579 return control_key_state;
1580}
1581
1582// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1583// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1584// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1585// appropriately.
1586static DWORD _normalize_keypad_control_key_state(const WORD vk,
1587 const DWORD control_key_state) {
1588 if (!_is_numlock_on(control_key_state)) {
1589 return control_key_state;
1590 }
1591 if (!_is_enhanced_key(control_key_state)) {
1592 switch (vk) {
1593 case VK_INSERT: // 0
1594 case VK_DELETE: // .
1595 case VK_END: // 1
1596 case VK_DOWN: // 2
1597 case VK_NEXT: // 3
1598 case VK_LEFT: // 4
1599 case VK_CLEAR: // 5
1600 case VK_RIGHT: // 6
1601 case VK_HOME: // 7
1602 case VK_UP: // 8
1603 case VK_PRIOR: // 9
1604 return control_key_state | SHIFT_PRESSED;
1605 }
1606 }
1607
1608 return control_key_state;
1609}
1610
1611static const char* _get_keypad_sequence(const DWORD control_key_state,
1612 const char* const normal, const char* const shifted) {
1613 if (_is_shift_pressed(control_key_state)) {
1614 // Shift is pressed and NumLock is off
1615 return shifted;
1616 } else {
1617 // Shift is not pressed and NumLock is off, or,
1618 // Shift is pressed and NumLock is on, in which case we want the
1619 // NumLock and Shift to neutralize each other, thus, we want the normal
1620 // sequence.
1621 return normal;
1622 }
1623 // If Shift is not pressed and NumLock is on, a different virtual key code
1624 // is returned by Windows, which can be taken care of by a different case
1625 // statement in _console_read().
1626}
1627
1628// Write sequence to buf and return the number of bytes written.
1629static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1630 DWORD control_key_state, const char* const normal) {
1631 // Copy the base sequence into buf.
1632 const size_t len = strlen(normal);
1633 memcpy(buf, normal, len);
1634
1635 int code = 0;
1636
1637 control_key_state = _normalize_keypad_control_key_state(vk,
1638 control_key_state);
1639
1640 if (_is_shift_pressed(control_key_state)) {
1641 code |= 0x1;
1642 }
1643 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1644 code |= 0x2;
1645 }
1646 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1647 code |= 0x4;
1648 }
1649 // If some modifier was held down, then we need to insert the modifier code
1650 if (code != 0) {
1651 if (len == 0) {
1652 // Should be impossible because caller should pass a string of
1653 // non-zero length.
1654 return 0;
1655 }
1656 size_t index = len - 1;
1657 const char lastChar = buf[index];
1658 if (lastChar != '~') {
1659 buf[index++] = '1';
1660 }
1661 buf[index++] = ';'; // modifier separator
1662 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1663 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1664 buf[index++] = '1' + code;
1665 buf[index++] = lastChar; // move ~ (or other last char) to the end
1666 return index;
1667 }
1668 return len;
1669}
1670
1671// Write sequence to buf and return the number of bytes written.
1672static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1673 const DWORD control_key_state, const char* const normal,
1674 const char shifted) {
1675 if (_is_shift_pressed(control_key_state)) {
1676 // Shift is pressed and NumLock is off
1677 if (shifted != '\0') {
1678 buf[0] = shifted;
1679 return sizeof(buf[0]);
1680 } else {
1681 return 0;
1682 }
1683 } else {
1684 // Shift is not pressed and NumLock is off, or,
1685 // Shift is pressed and NumLock is on, in which case we want the
1686 // NumLock and Shift to neutralize each other, thus, we want the normal
1687 // sequence.
1688 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1689 }
1690 // If Shift is not pressed and NumLock is on, a different virtual key code
1691 // is returned by Windows, which can be taken care of by a different case
1692 // statement in _console_read().
1693}
1694
1695// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1696// Standard German. Figure this out at runtime so we know what to output for
1697// Shift-VK_DELETE.
1698static char _get_decimal_char() {
1699 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1700}
1701
1702// Prefix the len bytes in buf with the escape character, and then return the
1703// new buffer length.
1704size_t _escape_prefix(char* const buf, const size_t len) {
1705 // If nothing to prefix, don't do anything. We might be called with
1706 // len == 0, if alt was held down with a dead key which produced nothing.
1707 if (len == 0) {
1708 return 0;
1709 }
1710
1711 memmove(&buf[1], buf, len);
1712 buf[0] = '\x1b';
1713 return len + 1;
1714}
1715
Spencer Low32762f42015-11-10 19:17:16 -08001716// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001717static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001718
1719// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1720// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001721static int _console_read(const HANDLE console, void* buf, size_t len) {
1722 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001723 // Read of zero bytes should not block waiting for something from the console.
1724 if (len == 0) {
1725 return 0;
1726 }
1727
1728 // Flush as much as possible from input buffer.
1729 if (!g_console_input_buffer.empty()) {
1730 const int bytes_read = std::min(len, g_console_input_buffer.size());
1731 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1732 const auto begin = g_console_input_buffer.begin();
1733 g_console_input_buffer.erase(begin, begin + bytes_read);
1734 return bytes_read;
1735 }
1736
1737 // Read from the actual console. This may block until input.
1738 INPUT_RECORD input_record;
1739 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001740 return -1;
1741 }
1742
Spencer Low32762f42015-11-10 19:17:16 -08001743 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001744 const WORD vk = key_event->wVirtualKeyCode;
1745 const CHAR ch = key_event->uChar.AsciiChar;
1746 const DWORD control_key_state = _normalize_altgr_control_key_state(
1747 key_event);
1748
1749 // The following emulation code should write the output sequence to
1750 // either seqstr or to seqbuf and seqbuflen.
1751 const char* seqstr = NULL; // NULL terminated C-string
1752 // Enough space for max sequence string below, plus modifiers and/or
1753 // escape prefix.
1754 char seqbuf[16];
1755 size_t seqbuflen = 0; // Space used in seqbuf.
1756
1757#define MATCH(vk, normal) \
1758 case (vk): \
1759 { \
1760 seqstr = (normal); \
1761 } \
1762 break;
1763
1764 // Modifier keys should affect the output sequence.
1765#define MATCH_MODIFIER(vk, normal) \
1766 case (vk): \
1767 { \
1768 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1769 control_key_state, (normal)); \
1770 } \
1771 break;
1772
1773 // The shift key should affect the output sequence.
1774#define MATCH_KEYPAD(vk, normal, shifted) \
1775 case (vk): \
1776 { \
1777 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1778 (shifted)); \
1779 } \
1780 break;
1781
1782 // The shift key and other modifier keys should affect the output
1783 // sequence.
1784#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1785 case (vk): \
1786 { \
1787 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1788 control_key_state, (normal), (shifted)); \
1789 } \
1790 break;
1791
1792#define ESC "\x1b"
1793#define CSI ESC "["
1794#define SS3 ESC "O"
1795
1796 // Only support normal mode, not application mode.
1797
1798 // Enhanced keys:
1799 // * 6-pack: insert, delete, home, end, page up, page down
1800 // * cursor keys: up, down, right, left
1801 // * keypad: divide, enter
1802 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1803 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1804 if (_is_enhanced_key(control_key_state)) {
1805 switch (vk) {
1806 case VK_RETURN: // Enter key on keypad
1807 if (_is_ctrl_pressed(control_key_state)) {
1808 seqstr = "\n";
1809 } else {
1810 seqstr = "\r";
1811 }
1812 break;
1813
1814 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1815 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1816
1817 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1818 // will be fixed soon to match xterm which sends CSI "F" and
1819 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1820 MATCH(VK_END, CSI "F");
1821 MATCH(VK_HOME, CSI "H");
1822
1823 MATCH_MODIFIER(VK_LEFT, CSI "D");
1824 MATCH_MODIFIER(VK_UP, CSI "A");
1825 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1826 MATCH_MODIFIER(VK_DOWN, CSI "B");
1827
1828 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1829 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1830
1831 MATCH(VK_DIVIDE, "/");
1832 }
1833 } else { // Non-enhanced keys:
1834 switch (vk) {
1835 case VK_BACK: // backspace
1836 if (_is_alt_pressed(control_key_state)) {
1837 seqstr = ESC "\x7f";
1838 } else {
1839 seqstr = "\x7f";
1840 }
1841 break;
1842
1843 case VK_TAB:
1844 if (_is_shift_pressed(control_key_state)) {
1845 seqstr = CSI "Z";
1846 } else {
1847 seqstr = "\t";
1848 }
1849 break;
1850
1851 // Number 5 key in keypad when NumLock is off, or if NumLock is
1852 // on and Shift is down.
1853 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1854
1855 case VK_RETURN: // Enter key on main keyboard
1856 if (_is_alt_pressed(control_key_state)) {
1857 seqstr = ESC "\n";
1858 } else if (_is_ctrl_pressed(control_key_state)) {
1859 seqstr = "\n";
1860 } else {
1861 seqstr = "\r";
1862 }
1863 break;
1864
1865 // VK_ESCAPE: Don't do any special handling. The OS uses many
1866 // of the sequences with Escape and many of the remaining
1867 // sequences don't produce bKeyDown messages, only !bKeyDown
1868 // for whatever reason.
1869
1870 case VK_SPACE:
1871 if (_is_alt_pressed(control_key_state)) {
1872 seqstr = ESC " ";
1873 } else if (_is_ctrl_pressed(control_key_state)) {
1874 seqbuf[0] = '\0'; // NULL char
1875 seqbuflen = 1;
1876 } else {
1877 seqstr = " ";
1878 }
1879 break;
1880
1881 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1882 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1883
1884 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1885 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1886
1887 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1888 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1889 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1890 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1891
1892 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1893 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1894 _get_decimal_char());
1895
1896 case 0x30: // 0
1897 case 0x31: // 1
1898 case 0x39: // 9
1899 case VK_OEM_1: // ;:
1900 case VK_OEM_PLUS: // =+
1901 case VK_OEM_COMMA: // ,<
1902 case VK_OEM_PERIOD: // .>
1903 case VK_OEM_7: // '"
1904 case VK_OEM_102: // depends on keyboard, could be <> or \|
1905 case VK_OEM_2: // /?
1906 case VK_OEM_3: // `~
1907 case VK_OEM_4: // [{
1908 case VK_OEM_5: // \|
1909 case VK_OEM_6: // ]}
1910 {
1911 seqbuflen = _get_control_character(seqbuf, key_event,
1912 control_key_state);
1913
1914 if (_is_alt_pressed(control_key_state)) {
1915 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1916 }
1917 }
1918 break;
1919
1920 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001921 case 0x33: // 3
1922 case 0x34: // 4
1923 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001924 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001925 case 0x37: // 7
1926 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001927 case VK_OEM_MINUS: // -_
1928 {
1929 seqbuflen = _get_control_character(seqbuf, key_event,
1930 control_key_state);
1931
1932 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1933 // prefix with escape.
1934 if (_is_alt_pressed(control_key_state) &&
1935 !(_is_ctrl_pressed(control_key_state) &&
1936 !_is_shift_pressed(control_key_state))) {
1937 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1938 }
1939 }
1940 break;
1941
Spencer Low50184062015-03-01 15:06:21 -08001942 case 0x41: // a
1943 case 0x42: // b
1944 case 0x43: // c
1945 case 0x44: // d
1946 case 0x45: // e
1947 case 0x46: // f
1948 case 0x47: // g
1949 case 0x48: // h
1950 case 0x49: // i
1951 case 0x4a: // j
1952 case 0x4b: // k
1953 case 0x4c: // l
1954 case 0x4d: // m
1955 case 0x4e: // n
1956 case 0x4f: // o
1957 case 0x50: // p
1958 case 0x51: // q
1959 case 0x52: // r
1960 case 0x53: // s
1961 case 0x54: // t
1962 case 0x55: // u
1963 case 0x56: // v
1964 case 0x57: // w
1965 case 0x58: // x
1966 case 0x59: // y
1967 case 0x5a: // z
1968 {
1969 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1970 control_key_state);
1971
1972 // If Alt is pressed, then prefix with escape.
1973 if (_is_alt_pressed(control_key_state)) {
1974 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1975 }
1976 }
1977 break;
1978
1979 // These virtual key codes are generated by the keys on the
1980 // keypad *when NumLock is on* and *Shift is up*.
1981 MATCH(VK_NUMPAD0, "0");
1982 MATCH(VK_NUMPAD1, "1");
1983 MATCH(VK_NUMPAD2, "2");
1984 MATCH(VK_NUMPAD3, "3");
1985 MATCH(VK_NUMPAD4, "4");
1986 MATCH(VK_NUMPAD5, "5");
1987 MATCH(VK_NUMPAD6, "6");
1988 MATCH(VK_NUMPAD7, "7");
1989 MATCH(VK_NUMPAD8, "8");
1990 MATCH(VK_NUMPAD9, "9");
1991
1992 MATCH(VK_MULTIPLY, "*");
1993 MATCH(VK_ADD, "+");
1994 MATCH(VK_SUBTRACT, "-");
1995 // VK_DECIMAL is generated by the . key on the keypad *when
1996 // NumLock is on* and *Shift is up* and the sequence is not
1997 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1998 // Windows Security screen to come up).
1999 case VK_DECIMAL:
2000 // U.S. English uses '.', Germany German uses ','.
2001 seqbuflen = _get_non_control_char(seqbuf, key_event,
2002 control_key_state);
2003 break;
2004
2005 MATCH_MODIFIER(VK_F1, SS3 "P");
2006 MATCH_MODIFIER(VK_F2, SS3 "Q");
2007 MATCH_MODIFIER(VK_F3, SS3 "R");
2008 MATCH_MODIFIER(VK_F4, SS3 "S");
2009 MATCH_MODIFIER(VK_F5, CSI "15~");
2010 MATCH_MODIFIER(VK_F6, CSI "17~");
2011 MATCH_MODIFIER(VK_F7, CSI "18~");
2012 MATCH_MODIFIER(VK_F8, CSI "19~");
2013 MATCH_MODIFIER(VK_F9, CSI "20~");
2014 MATCH_MODIFIER(VK_F10, CSI "21~");
2015 MATCH_MODIFIER(VK_F11, CSI "23~");
2016 MATCH_MODIFIER(VK_F12, CSI "24~");
2017
2018 MATCH_MODIFIER(VK_F13, CSI "25~");
2019 MATCH_MODIFIER(VK_F14, CSI "26~");
2020 MATCH_MODIFIER(VK_F15, CSI "28~");
2021 MATCH_MODIFIER(VK_F16, CSI "29~");
2022 MATCH_MODIFIER(VK_F17, CSI "31~");
2023 MATCH_MODIFIER(VK_F18, CSI "32~");
2024 MATCH_MODIFIER(VK_F19, CSI "33~");
2025 MATCH_MODIFIER(VK_F20, CSI "34~");
2026
2027 // MATCH_MODIFIER(VK_F21, ???);
2028 // MATCH_MODIFIER(VK_F22, ???);
2029 // MATCH_MODIFIER(VK_F23, ???);
2030 // MATCH_MODIFIER(VK_F24, ???);
2031 }
2032 }
2033
2034#undef MATCH
2035#undef MATCH_MODIFIER
2036#undef MATCH_KEYPAD
2037#undef MATCH_MODIFIER_KEYPAD
2038#undef ESC
2039#undef CSI
2040#undef SS3
2041
2042 const char* out;
2043 size_t outlen;
2044
2045 // Check for output in any of:
2046 // * seqstr is set (and strlen can be used to determine the length).
2047 // * seqbuf and seqbuflen are set
2048 // Fallback to ch from Windows.
2049 if (seqstr != NULL) {
2050 out = seqstr;
2051 outlen = strlen(seqstr);
2052 } else if (seqbuflen > 0) {
2053 out = seqbuf;
2054 outlen = seqbuflen;
2055 } else if (ch != '\0') {
2056 // Use whatever Windows told us it is.
2057 seqbuf[0] = ch;
2058 seqbuflen = 1;
2059 out = seqbuf;
2060 outlen = seqbuflen;
2061 } else {
2062 // No special handling for the virtual key code and Windows isn't
2063 // telling us a character code, then we don't know how to translate
2064 // the key press.
2065 //
2066 // Consume the input and 'continue' to cause us to get a new key
2067 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002068 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002069 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002070 continue;
2071 }
2072
Spencer Low32762f42015-11-10 19:17:16 -08002073 // put output wRepeatCount times into g_console_input_buffer
2074 while (key_event->wRepeatCount-- > 0) {
2075 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002076 }
2077
Spencer Low32762f42015-11-10 19:17:16 -08002078 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002079 }
2080}
2081
2082static DWORD _old_console_mode; // previous GetConsoleMode() result
2083static HANDLE _console_handle; // when set, console mode should be restored
2084
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002085void stdin_raw_init() {
2086 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002087 if (in == nullptr) {
2088 return;
2089 }
Spencer Low50184062015-03-01 15:06:21 -08002090
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002091 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2092 // calling the process Ctrl-C routine (configured by
2093 // SetConsoleCtrlHandler()).
2094 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2095 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2096 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002097 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2098 ENABLE_LINE_INPUT |
2099 ENABLE_ECHO_INPUT);
2100 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2101 new_console_mode |= ENABLE_WINDOW_INPUT;
2102
2103 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002104 // This really should not fail.
2105 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002106 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002107 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002108
2109 // Once this is set, it means that stdin has been configured for
2110 // reading from and that the old console mode should be restored later.
2111 _console_handle = in;
2112
2113 // Note that we don't need to configure C Runtime line-ending
2114 // translation because _console_read() does not call the C Runtime to
2115 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002116}
2117
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002118void stdin_raw_restore() {
2119 if (_console_handle != NULL) {
2120 const HANDLE in = _console_handle;
2121 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002122
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002123 if (!SetConsoleMode(in, _old_console_mode)) {
2124 // This really should not fail.
2125 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002126 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002127 }
2128 }
2129}
2130
Spencer Low2e02dc62015-11-07 17:34:39 -08002131// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2132int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08002133 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2134 // If it is a request to read from stdin, and stdin_raw_init() has been
2135 // called, and it successfully configured the console, then read from
2136 // the console using Win32 console APIs and partially emulate a unix
2137 // terminal.
2138 return _console_read(_console_handle, buf, len);
2139 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002140 // On older versions of Windows (definitely 7, definitely not 10),
2141 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002142 // we need to limit the read size.
2143 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002144 len = 4096;
2145 }
Spencer Low50184062015-03-01 15:06:21 -08002146 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002147 // can do LF/CR translation (which is overridable with _setmode()).
2148 // Undefine the macro that is set in sysdeps.h which bans calls to
2149 // plain read() in favor of unix_read() or adb_read().
2150#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002151#undef read
2152 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002153#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002154 }
2155}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002156
2157/**************************************************************************/
2158/**************************************************************************/
2159/***** *****/
2160/***** Unicode support *****/
2161/***** *****/
2162/**************************************************************************/
2163/**************************************************************************/
2164
2165// This implements support for using files with Unicode filenames and for
2166// outputting Unicode text to a Win32 console window. This is inspired from
2167// http://utf8everywhere.org/.
2168//
2169// Background
2170// ----------
2171//
2172// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2173// filenames to APIs such as open(). This works because filenames are largely
2174// opaque 'cookies' (perhaps excluding path separators).
2175//
2176// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2177// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2178// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2179// CreateFile() API is really just a macro that adds the W/A based on whether
2180// the UNICODE preprocessor symbol is defined).
2181//
2182// Options
2183// -------
2184//
2185// Thus, to write a portable program, there are a few options:
2186//
2187// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2188// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2189// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2190// open() API.
2191//
2192// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2193// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2194// potentially touching a lot of code.
2195//
2196// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2197// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2198// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2199// or C Runtime API.
2200//
2201// The Choice
2202// ----------
2203//
Spencer Lowd21dc822015-11-12 15:20:15 -08002204// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2205// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002206// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002207// args that are passed to main() at the beginning of program startup. We also use
2208// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002209// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2210//
2211// Unicode console output
2212// ----------------------
2213//
2214// The way to output Unicode to a Win32 console window is to call
2215// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002216// such as Lucida Console or Consolas, and in the case of East Asian languages
2217// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2218// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2219// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002220//
2221// The problem is getting the C Runtime to make fprintf and related APIs call
2222// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2223// promising, but the various modes have issues:
2224//
2225// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2226// UTF-16 do not display properly.
2227// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2228// totally wrong.
2229// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2230// handler to be called (upon a later I/O call), aborting the process.
2231// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2232// to output nothing.
2233//
2234// So the only solution is to write our own adb_fprintf() that converts UTF-8
2235// to UTF-16 and then calls WriteConsoleW().
2236
2237
Spencer Lowcf4ff642015-05-11 01:08:48 -07002238// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2239// be passed to main().
2240NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2241 narrow_args = new char*[argc + 1];
2242
2243 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002244 std::string arg_narrow;
2245 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2246 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2247 }
2248 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002249 }
2250 narrow_args[argc] = nullptr; // terminate
2251}
2252
2253NarrowArgs::~NarrowArgs() {
2254 if (narrow_args != nullptr) {
2255 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2256 free(*argp);
2257 }
2258 delete[] narrow_args;
2259 narrow_args = nullptr;
2260 }
2261}
2262
2263int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002264 std::wstring path_wide;
2265 if (!android::base::UTF8ToWide(path, &path_wide)) {
2266 return -1;
2267 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002268 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002269 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002270 } else {
2271 int mode;
2272 va_list args;
2273 va_start(args, options);
2274 mode = va_arg(args, int);
2275 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002276 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002277 }
2278}
2279
Spencer Lowcf4ff642015-05-11 01:08:48 -07002280// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002281DIR* adb_opendir(const char* path) {
2282 std::wstring path_wide;
2283 if (!android::base::UTF8ToWide(path, &path_wide)) {
2284 return nullptr;
2285 }
2286
Spencer Lowcf4ff642015-05-11 01:08:48 -07002287 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2288 // the fields, but right now all the callers treat the structure as
2289 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002290 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002291}
2292
2293// Version of readdir() that returns UTF-8 paths.
2294struct dirent* adb_readdir(DIR* dir) {
2295 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2296 struct _wdirent* const went = _wreaddir(wdir);
2297 if (went == nullptr) {
2298 return nullptr;
2299 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002300
Spencer Lowcf4ff642015-05-11 01:08:48 -07002301 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002302 std::string name_utf8;
2303 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2304 return nullptr;
2305 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002306
2307 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2308 // space for UTF-16 wchar_t's) with UTF-8 char's.
2309 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2310
2311 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2312 // Name too big to fit in existing buffer.
2313 errno = ENOMEM;
2314 return nullptr;
2315 }
2316
2317 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2318 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2319 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2320 // bigger than the caller expects because they expect a dirent structure
2321 // which has a smaller d_name field. Ignore this since the caller should be
2322 // resilient.
2323
2324 // Rewrite the UTF-16 d_name field to UTF-8.
2325 strcpy(ent->d_name, name_utf8.c_str());
2326
2327 return ent;
2328}
2329
2330// Version of closedir() to go with our version of adb_opendir().
2331int adb_closedir(DIR* dir) {
2332 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2333}
2334
2335// Version of unlink() that takes a UTF-8 path.
2336int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002337 std::wstring wpath;
2338 if (!android::base::UTF8ToWide(path, &wpath)) {
2339 return -1;
2340 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002341
2342 int rc = _wunlink(wpath.c_str());
2343
2344 if (rc == -1 && errno == EACCES) {
2345 /* unlink returns EACCES when the file is read-only, so we first */
2346 /* try to make it writable, then unlink again... */
2347 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2348 if (rc == 0)
2349 rc = _wunlink(wpath.c_str());
2350 }
2351 return rc;
2352}
2353
2354// Version of mkdir() that takes a UTF-8 path.
2355int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002356 std::wstring path_wide;
2357 if (!android::base::UTF8ToWide(path, &path_wide)) {
2358 return -1;
2359 }
2360
2361 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002362}
2363
2364// Version of utime() that takes a UTF-8 path.
2365int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002366 std::wstring path_wide;
2367 if (!android::base::UTF8ToWide(path, &path_wide)) {
2368 return -1;
2369 }
2370
Spencer Lowcf4ff642015-05-11 01:08:48 -07002371 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2372 "utimbuf and _utimbuf should be the same size because they both "
2373 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002374 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002375}
2376
2377// Version of chmod() that takes a UTF-8 path.
2378int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002379 std::wstring path_wide;
2380 if (!android::base::UTF8ToWide(path, &path_wide)) {
2381 return -1;
2382 }
2383
2384 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002385}
2386
Spencer Lowa30b79a2015-11-15 16:29:36 -08002387// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2388static inline size_t utf8_codepoint_len(uint8_t ch) {
2389 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2390}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002391
Spencer Lowa30b79a2015-11-15 16:29:36 -08002392namespace internal {
2393
2394// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2395// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2396// remaining_bytes.
2397size_t ParseCompleteUTF8(const char* const first, const char* const last,
2398 std::vector<char>* const remaining_bytes) {
2399 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2400 // Current_after points one byte past the current byte to be examined.
2401 for (const char* current_after = last; current_after != first; --current_after) {
2402 const char* const current = current_after - 1;
2403 const char ch = *current;
2404 const char kHighBit = 0x80u;
2405 const char kTwoHighestBits = 0xC0u;
2406 if ((ch & kHighBit) == 0) { // high bit not set
2407 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2408 // bytes with no leading byte, so return the entire buffer.
2409 break;
2410 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2411 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2412 const size_t bytes_available = last - current;
2413 if (bytes_available < utf8_codepoint_len(ch)) {
2414 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2415 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2416 // to remaining_bytes.
2417 remaining_bytes->insert(remaining_bytes->end(), current, last);
2418 return current - first;
2419 } else {
2420 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2421 // trailing bytes with no lead byte, so return the entire buffer.
2422 break;
2423 }
2424 } else {
2425 // Trailing byte, so keep going backwards looking for the lead byte.
2426 }
2427 }
2428
2429 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2430 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2431 // so that they can be processed.
2432 return last - first;
2433}
2434
2435}
2436
2437// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2438// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2439// This matches the behavior of Linux.
2440// Protected by g_console_output_buffer_lock.
2441static auto& g_console_output_buffer = *new std::vector<char>();
2442
2443// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2444static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2445 HANDLE console) {
2446 const int saved_errno = errno;
2447 std::vector<char> combined_buffer;
2448
2449 // Complete UTF-8 sequences that should be immediately written to the console.
2450 const char* utf8;
2451 size_t utf8_size;
2452
2453 adb_mutex_lock(&g_console_output_buffer_lock);
2454 if (g_console_output_buffer.empty()) {
2455 // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2456 // common case with plain ASCII), parse buf directly.
2457 utf8 = buf;
2458 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
2459 } else {
2460 // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2461 // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
2462 // combined_buffer, then parse it all together.
2463 combined_buffer.swap(g_console_output_buffer);
2464 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
2465
2466 utf8 = combined_buffer.data();
2467 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2468 &g_console_output_buffer);
2469 }
2470 adb_mutex_unlock(&g_console_output_buffer_lock);
2471
2472 std::wstring utf16;
2473
2474 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2475 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2476 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002477 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002478 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002479
2480 // Note that this does not do \n => \r\n translation because that
2481 // doesn't seem necessary for the Windows console. For the Windows
2482 // console \r moves to the beginning of the line and \n moves to a new
2483 // line.
2484
2485 // Flush any stream buffering so that our output is afterwards which
2486 // makes sense because our call is afterwards.
2487 (void)fflush(stream);
2488
2489 // Write UTF-16 to the console.
2490 DWORD written = 0;
Spencer Lowa30b79a2015-11-15 16:29:36 -08002491 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002492 errno = EIO;
2493 return -1;
2494 }
2495
Spencer Lowa30b79a2015-11-15 16:29:36 -08002496 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2497 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2498 // matches the Linux behavior.
2499 errno = saved_errno;
2500 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002501}
2502
2503// Function prototype because attributes cannot be placed on func definitions.
2504static int _console_vfprintf(const HANDLE console, FILE* stream,
2505 const char *format, va_list ap)
2506 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2507
2508// Internal function to format a UTF-8 string and write it to a Win32 console.
2509// Returns -1 on error.
2510static int _console_vfprintf(const HANDLE console, FILE* stream,
2511 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002512 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002513 std::string output_utf8;
2514
2515 // Format the string.
2516 // This could throw std::bad_alloc.
2517 android::base::StringAppendV(&output_utf8, format, ap);
2518
Spencer Lowa30b79a2015-11-15 16:29:36 -08002519 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2520 console);
2521 if (result != -1) {
2522 errno = saved_errno;
2523 } else {
2524 // If -1 was returned, errno has been set.
2525 }
2526 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002527}
2528
2529// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2530// Windows console.
2531int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2532 const HANDLE console = _get_console_handle(stream);
2533
2534 // If there is an associated Win32 console, write to it specially,
2535 // otherwise defer to the regular C Runtime, passing it UTF-8.
2536 if (console != NULL) {
2537 return _console_vfprintf(console, stream, format, ap);
2538 } else {
2539 // If vfprintf is a macro, undefine it, so we can call the real
2540 // C Runtime API.
2541#pragma push_macro("vfprintf")
2542#undef vfprintf
2543 return vfprintf(stream, format, ap);
2544#pragma pop_macro("vfprintf")
2545 }
2546}
2547
Spencer Lowa30b79a2015-11-15 16:29:36 -08002548// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2549int adb_vprintf(const char *format, va_list ap) {
2550 return adb_vfprintf(stdout, format, ap);
2551}
2552
Spencer Lowcf4ff642015-05-11 01:08:48 -07002553// Version of fprintf() that takes UTF-8 and can write Unicode to a
2554// Windows console.
2555int adb_fprintf(FILE *stream, const char *format, ...) {
2556 va_list ap;
2557 va_start(ap, format);
2558 const int result = adb_vfprintf(stream, format, ap);
2559 va_end(ap);
2560
2561 return result;
2562}
2563
2564// Version of printf() that takes UTF-8 and can write Unicode to a
2565// Windows console.
2566int adb_printf(const char *format, ...) {
2567 va_list ap;
2568 va_start(ap, format);
2569 const int result = adb_vfprintf(stdout, format, ap);
2570 va_end(ap);
2571
2572 return result;
2573}
2574
2575// Version of fputs() that takes UTF-8 and can write Unicode to a
2576// Windows console.
2577int adb_fputs(const char* buf, FILE* stream) {
2578 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2579 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002580 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002581 return adb_fprintf(stream, "%s", buf);
2582}
2583
2584// Version of fputc() that takes UTF-8 and can write Unicode to a
2585// Windows console.
2586int adb_fputc(int ch, FILE* stream) {
2587 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002588 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002589 return EOF;
2590 }
2591 // For success, fputc returns the char, cast to unsigned char, then to int.
2592 return static_cast<unsigned char>(ch);
2593}
2594
Spencer Lowa30b79a2015-11-15 16:29:36 -08002595// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2596int adb_putchar(int ch) {
2597 return adb_fputc(ch, stdout);
2598}
2599
2600// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2601int adb_puts(const char* buf) {
2602 // adb_printf returns -1 on error, which is conveniently the same as EOF
2603 // which puts (and hence adb_puts) should return on error.
2604 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2605 return adb_printf("%s\n", buf);
2606}
2607
Spencer Lowcf4ff642015-05-11 01:08:48 -07002608// Internal function to write UTF-8 to a Win32 console. Returns the number of
2609// items (of length size) written. On error, returns a short item count or 0.
2610static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2611 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002612 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2613 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002614 if (result == -1) {
2615 return 0;
2616 }
2617 return result / size;
2618}
2619
2620// Version of fwrite() that takes UTF-8 and can write Unicode to a
2621// Windows console.
2622size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2623 const HANDLE console = _get_console_handle(stream);
2624
2625 // If there is an associated Win32 console, write to it specially,
2626 // otherwise defer to the regular C Runtime, passing it UTF-8.
2627 if (console != NULL) {
2628 return _console_fwrite(ptr, size, nmemb, stream, console);
2629 } else {
2630 // If fwrite is a macro, undefine it, so we can call the real
2631 // C Runtime API.
2632#pragma push_macro("fwrite")
2633#undef fwrite
2634 return fwrite(ptr, size, nmemb, stream);
2635#pragma pop_macro("fwrite")
2636 }
2637}
2638
2639// Version of fopen() that takes a UTF-8 filename and can access a file with
2640// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002641FILE* adb_fopen(const char* path, const char* mode) {
2642 std::wstring path_wide;
2643 if (!android::base::UTF8ToWide(path, &path_wide)) {
2644 return nullptr;
2645 }
2646
2647 std::wstring mode_wide;
2648 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2649 return nullptr;
2650 }
2651
2652 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002653}
2654
Spencer Lowe6ae5732015-09-08 17:13:04 -07002655// Return a lowercase version of the argument. Uses C Runtime tolower() on
2656// each byte which is not UTF-8 aware, and theoretically uses the current C
2657// Runtime locale (which in practice is not changed, so this becomes a ASCII
2658// conversion).
2659static std::string ToLower(const std::string& anycase) {
2660 // copy string
2661 std::string str(anycase);
2662 // transform the copy
2663 std::transform(str.begin(), str.end(), str.begin(), tolower);
2664 return str;
2665}
2666
2667extern "C" int main(int argc, char** argv);
2668
2669// Link with -municode to cause this wmain() to be used as the program
2670// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2671// regular main() with UTF-8 args.
2672extern "C" int wmain(int argc, wchar_t **argv) {
2673 // Convert args from UTF-16 to UTF-8 and pass that to main().
2674 NarrowArgs narrow_args(argc, argv);
2675 return main(argc, narrow_args.data());
2676}
2677
Spencer Lowcf4ff642015-05-11 01:08:48 -07002678// Shadow UTF-8 environment variable name/value pairs that are created from
2679// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002680// currently updated if putenv, setenv, unsetenv are called. Note that no
2681// thread synchronization is done, but we're called early enough in
2682// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002683static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002684
2685// Make sure that shadow UTF-8 environment variables are setup.
2686static void _ensure_env_setup() {
2687 // If some name/value pairs exist, then we've already done the setup below.
2688 if (g_environ_utf8.size() != 0) {
2689 return;
2690 }
2691
Spencer Lowe6ae5732015-09-08 17:13:04 -07002692 if (_wenviron == nullptr) {
2693 // If _wenviron is null, then -municode probably wasn't used. That
2694 // linker flag will cause the entry point to setup _wenviron. It will
2695 // also require an implementation of wmain() (which we provide above).
2696 fatal("_wenviron is not set, did you link with -municode?");
2697 }
2698
Spencer Lowcf4ff642015-05-11 01:08:48 -07002699 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2700 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2701 // to use the D() macro here because that tracing only works if the
2702 // ADB_TRACE environment variable is setup, but that env var can't be read
2703 // until this code completes.
2704 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2705 wchar_t* const equal = wcschr(*env, L'=');
2706 if (equal == nullptr) {
2707 // Malformed environment variable with no equal sign. Shouldn't
2708 // really happen, but we should be resilient to this.
2709 continue;
2710 }
2711
Spencer Lowd21dc822015-11-12 15:20:15 -08002712 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2713 // var because the program might never even read this particular variable.
2714 std::string name_utf8;
2715 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2716 continue;
2717 }
2718
Spencer Lowe6ae5732015-09-08 17:13:04 -07002719 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002720 name_utf8 = ToLower(name_utf8);
2721
2722 std::string value_utf8;
2723 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2724 continue;
2725 }
2726
2727 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002728
Spencer Lowe6ae5732015-09-08 17:13:04 -07002729 // Don't overwrite a previus env var with the same name. In reality,
2730 // the system probably won't let two env vars with the same name exist
2731 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002732 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002733 }
2734}
2735
2736// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002737// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002738char* adb_getenv(const char* name) {
2739 _ensure_env_setup();
2740
Spencer Lowe6ae5732015-09-08 17:13:04 -07002741 // Case-insensitive search by searching for lowercase name in a map of
2742 // lowercase names.
2743 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002744 if (it == g_environ_utf8.end()) {
2745 return nullptr;
2746 }
2747
2748 return it->second;
2749}
2750
2751// Version of getcwd() that returns the current working directory in UTF-8.
2752char* adb_getcwd(char* buf, int size) {
2753 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2754 if (wbuf == nullptr) {
2755 return nullptr;
2756 }
2757
Spencer Lowd21dc822015-11-12 15:20:15 -08002758 std::string buf_utf8;
2759 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002760 free(wbuf);
2761 wbuf = nullptr;
2762
Spencer Lowd21dc822015-11-12 15:20:15 -08002763 if (!narrow_result) {
2764 return nullptr;
2765 }
2766
Spencer Lowcf4ff642015-05-11 01:08:48 -07002767 // If size was specified, make sure all the chars will fit.
2768 if (size != 0) {
2769 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2770 errno = ERANGE;
2771 return nullptr;
2772 }
2773 }
2774
2775 // If buf was not specified, allocate storage.
2776 if (buf == nullptr) {
2777 if (size == 0) {
2778 size = buf_utf8.length() + 1;
2779 }
2780 buf = reinterpret_cast<char*>(malloc(size));
2781 if (buf == nullptr) {
2782 return nullptr;
2783 }
2784 }
2785
2786 // Destination buffer was allocated with enough space, or we've already
2787 // checked an existing buffer size for enough space.
2788 strcpy(buf, buf_utf8.c_str());
2789
2790 return buf;
2791}