blob: 1f6ea3fc83e34e7b54c1246d914a220364e5fda5 [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albertdb6fe642015-03-19 15:21:08 -070018
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
Spencer Low50740f52015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low753d4852015-07-30 23:07:55 -070029#include <memory>
30#include <string>
Spencer Low6815c072015-05-11 01:08:48 -070031#include <unordered_map>
Spencer Low753d4852015-07-30 23:07:55 -070032
Elliott Hughesfe447512015-07-24 11:35:40 -070033#include <cutils/sockets.h>
34
Elliott Hughesf55ead92015-12-04 22:00:26 -080035#include <android-base/logging.h>
36#include <android-base/stringprintf.h>
37#include <android-base/strings.h>
38#include <android-base/utf8.h>
Spencer Low753d4852015-07-30 23:07:55 -070039
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080040#include "adb.h"
41
42extern void fatal(const char *fmt, ...);
43
Elliott Hughes6a096932015-04-16 16:47:02 -070044/* forward declarations */
45
46typedef const struct FHClassRec_* FHClass;
47typedef struct FHRec_* FH;
48typedef struct EventHookRec_* EventHook;
49
50typedef struct FHClassRec_ {
51 void (*_fh_init)(FH);
52 int (*_fh_close)(FH);
53 int (*_fh_lseek)(FH, int, int);
54 int (*_fh_read)(FH, void*, int);
55 int (*_fh_write)(FH, const void*, int);
56 void (*_fh_hook)(FH, int, EventHook);
57} FHClassRec;
58
59static void _fh_file_init(FH);
60static int _fh_file_close(FH);
61static int _fh_file_lseek(FH, int, int);
62static int _fh_file_read(FH, void*, int);
63static int _fh_file_write(FH, const void*, int);
64static void _fh_file_hook(FH, int, EventHook);
65
66static const FHClassRec _fh_file_class = {
67 _fh_file_init,
68 _fh_file_close,
69 _fh_file_lseek,
70 _fh_file_read,
71 _fh_file_write,
72 _fh_file_hook
73};
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);
80static void _fh_socket_hook(FH, int, EventHook);
81
82static const FHClassRec _fh_socket_class = {
83 _fh_socket_init,
84 _fh_socket_close,
85 _fh_socket_lseek,
86 _fh_socket_read,
87 _fh_socket_write,
88 _fh_socket_hook
89};
90
Josh Gao2930cdc2016-01-15 15:17:37 -080091#define assert(cond) \
92 do { \
93 if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \
94 } while (0)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080095
Spencer Low753d4852015-07-30 23:07:55 -070096std::string SystemErrorCodeToString(const DWORD error_code) {
97 const int kErrorMessageBufferSize = 256;
Spencer Lowcc467f12015-08-02 18:13:54 -070098 WCHAR msgbuf[kErrorMessageBufferSize];
Spencer Low753d4852015-07-30 23:07:55 -070099 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
Spencer Lowcc467f12015-08-02 18:13:54 -0700100 DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf,
Spencer Low753d4852015-07-30 23:07:55 -0700101 arraysize(msgbuf), nullptr);
102 if (len == 0) {
103 return android::base::StringPrintf(
104 "Error (%lu) while retrieving error. (%lu)", GetLastError(),
105 error_code);
106 }
107
Spencer Lowcc467f12015-08-02 18:13:54 -0700108 // Convert UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -0800109 std::string msg;
110 if (!android::base::WideToUTF8(msgbuf, &msg)) {
111 return android::base::StringPrintf(
112 "Error (%d) converting from UTF-16 to UTF-8 while retrieving error. (%lu)", errno,
113 error_code);
114 }
115
Spencer Low753d4852015-07-30 23:07:55 -0700116 // Messages returned by the system end with line breaks.
117 msg = android::base::Trim(msg);
118 // There are many Windows error messages compared to POSIX, so include the
119 // numeric error code for easier, quicker, accurate identification. Use
120 // decimal instead of hex because there are decimal ranges like 10000-11999
121 // for Winsock.
122 android::base::StringAppendF(&msg, " (%lu)", error_code);
123 return msg;
124}
125
Spencer Low2bbb3a92015-08-26 18:46:09 -0700126void handle_deleter::operator()(HANDLE h) {
127 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
128 // implying that NULL is a valid handle, but this is probably impossible.
129 // Other APIs like CreateEvent() are documented to return NULL on error,
130 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
131 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
132 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
133 // only need to check for INVALID_HANDLE_VALUE.
134 if (h != INVALID_HANDLE_VALUE) {
135 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700136 D("CloseHandle(%p) failed: %s", h,
Spencer Low2bbb3a92015-08-26 18:46:09 -0700137 SystemErrorCodeToString(GetLastError()).c_str());
138 }
139 }
140}
141
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800142/**************************************************************************/
143/**************************************************************************/
144/***** *****/
145/***** replaces libs/cutils/load_file.c *****/
146/***** *****/
147/**************************************************************************/
148/**************************************************************************/
149
150void *load_file(const char *fn, unsigned *_sz)
151{
152 HANDLE file;
153 char *data;
154 DWORD file_size;
155
Spencer Low50f5bf12015-11-12 15:20:15 -0800156 std::wstring fn_wide;
157 if (!android::base::UTF8ToWide(fn, &fn_wide))
158 return NULL;
159
160 file = CreateFileW( fn_wide.c_str(),
Spencer Low6815c072015-05-11 01:08:48 -0700161 GENERIC_READ,
162 FILE_SHARE_READ,
163 NULL,
164 OPEN_EXISTING,
165 0,
166 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800167
168 if (file == INVALID_HANDLE_VALUE)
169 return NULL;
170
171 file_size = GetFileSize( file, NULL );
172 data = NULL;
173
174 if (file_size > 0) {
175 data = (char*) malloc( file_size + 1 );
176 if (data == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -0700177 D("load_file: could not allocate %ld bytes", file_size );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800178 file_size = 0;
179 } else {
180 DWORD out_bytes;
181
182 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
183 out_bytes != file_size )
184 {
Yabin Cui815ad882015-09-02 17:44:28 -0700185 D("load_file: could not read %ld bytes from '%s'", file_size, fn);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800186 free(data);
187 data = NULL;
188 file_size = 0;
189 }
190 }
191 }
192 CloseHandle( file );
193
194 *_sz = (unsigned) file_size;
195 return data;
196}
197
198/**************************************************************************/
199/**************************************************************************/
200/***** *****/
201/***** common file descriptor handling *****/
202/***** *****/
203/**************************************************************************/
204/**************************************************************************/
205
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800206/* used to emulate unix-domain socket pairs */
207typedef struct SocketPairRec_* SocketPair;
208
209typedef struct FHRec_
210{
211 FHClass clazz;
212 int used;
213 int eof;
214 union {
215 HANDLE handle;
216 SOCKET socket;
217 SocketPair pair;
218 } u;
219
220 HANDLE event;
221 int mask;
222
223 char name[32];
224
225} FHRec;
226
227#define fh_handle u.handle
228#define fh_socket u.socket
229#define fh_pair u.pair
230
231#define WIN32_FH_BASE 100
232
233#define WIN32_MAX_FHS 128
234
235static adb_mutex_t _win32_lock;
236static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700237static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800238
239static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700240_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800241{
242 FH f;
243
244 fd -= WIN32_FH_BASE;
245
Spencer Lowb732a372015-07-24 15:38:19 -0700246 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui815ad882015-09-02 17:44:28 -0700247 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700248 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800249 errno = EBADF;
250 return NULL;
251 }
252
253 f = &_win32_fhs[fd];
254
255 if (f->used == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700256 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700257 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800258 errno = EBADF;
259 return NULL;
260 }
261
262 return f;
263}
264
265
266static int
267_fh_to_int( FH f )
268{
269 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
270 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
271
272 return -1;
273}
274
275static FH
276_fh_alloc( FHClass clazz )
277{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800278 FH f = NULL;
279
280 adb_mutex_lock( &_win32_lock );
281
Spencer Lowb732a372015-07-24 15:38:19 -0700282 // Search entire array, starting from _win32_fh_next.
283 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
284 // Keep incrementing _win32_fh_next to avoid giving out an index that
285 // was recently closed, to try to avoid use-after-free.
286 const int index = _win32_fh_next++;
287 // Handle wrap-around of _win32_fh_next.
288 if (_win32_fh_next == WIN32_MAX_FHS) {
289 _win32_fh_next = 0;
290 }
291 if (_win32_fhs[index].clazz == NULL) {
292 f = &_win32_fhs[index];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800293 goto Exit;
294 }
295 }
Yabin Cui815ad882015-09-02 17:44:28 -0700296 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowb732a372015-07-24 15:38:19 -0700297 errno = EMFILE; // Too many open files
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800298Exit:
299 if (f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700300 f->clazz = clazz;
301 f->used = 1;
302 f->eof = 0;
303 f->name[0] = '\0';
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800304 clazz->_fh_init(f);
305 }
306 adb_mutex_unlock( &_win32_lock );
307 return f;
308}
309
310
311static int
312_fh_close( FH f )
313{
Spencer Lowb732a372015-07-24 15:38:19 -0700314 // Use lock so that closing only happens once and so that _fh_alloc can't
315 // allocate a FH that we're in the middle of closing.
316 adb_mutex_lock(&_win32_lock);
317 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800318 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700319 f->name[0] = '\0';
320 f->eof = 0;
321 f->used = 0;
322 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800323 }
Spencer Lowb732a372015-07-24 15:38:19 -0700324 adb_mutex_unlock(&_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800325 return 0;
326}
327
Spencer Low753d4852015-07-30 23:07:55 -0700328// Deleter for unique_fh.
329class fh_deleter {
330 public:
331 void operator()(struct FHRec_* fh) {
332 // We're called from a destructor and destructors should not overwrite
333 // errno because callers may do:
334 // errno = EBLAH;
335 // return -1; // calls destructor, which should not overwrite errno
336 const int saved_errno = errno;
337 _fh_close(fh);
338 errno = saved_errno;
339 }
340};
341
342// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
343typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
344
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800345/**************************************************************************/
346/**************************************************************************/
347/***** *****/
348/***** file-based descriptor handling *****/
349/***** *****/
350/**************************************************************************/
351/**************************************************************************/
352
Elliott Hughes6a096932015-04-16 16:47:02 -0700353static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800354 f->fh_handle = INVALID_HANDLE_VALUE;
355}
356
Elliott Hughes6a096932015-04-16 16:47:02 -0700357static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800358 CloseHandle( f->fh_handle );
359 f->fh_handle = INVALID_HANDLE_VALUE;
360 return 0;
361}
362
Elliott Hughes6a096932015-04-16 16:47:02 -0700363static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800364 DWORD read_bytes;
365
366 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700367 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800368 errno = EIO;
369 return -1;
370 } else if (read_bytes < (DWORD)len) {
371 f->eof = 1;
372 }
373 return (int)read_bytes;
374}
375
Elliott Hughes6a096932015-04-16 16:47:02 -0700376static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800377 DWORD wrote_bytes;
378
379 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700380 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800381 errno = EIO;
382 return -1;
383 } else if (wrote_bytes < (DWORD)len) {
384 f->eof = 1;
385 }
386 return (int)wrote_bytes;
387}
388
Elliott Hughes6a096932015-04-16 16:47:02 -0700389static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800390 DWORD method;
391 DWORD result;
392
393 switch (origin)
394 {
395 case SEEK_SET: method = FILE_BEGIN; break;
396 case SEEK_CUR: method = FILE_CURRENT; break;
397 case SEEK_END: method = FILE_END; break;
398 default:
399 errno = EINVAL;
400 return -1;
401 }
402
403 result = SetFilePointer( f->fh_handle, pos, NULL, method );
404 if (result == INVALID_SET_FILE_POINTER) {
405 errno = EIO;
406 return -1;
407 } else {
408 f->eof = 0;
409 }
410 return (int)result;
411}
412
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800413
414/**************************************************************************/
415/**************************************************************************/
416/***** *****/
417/***** file-based descriptor handling *****/
418/***** *****/
419/**************************************************************************/
420/**************************************************************************/
421
422int adb_open(const char* path, int options)
423{
424 FH f;
425
426 DWORD desiredAccess = 0;
427 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
428
429 switch (options) {
430 case O_RDONLY:
431 desiredAccess = GENERIC_READ;
432 break;
433 case O_WRONLY:
434 desiredAccess = GENERIC_WRITE;
435 break;
436 case O_RDWR:
437 desiredAccess = GENERIC_READ | GENERIC_WRITE;
438 break;
439 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700440 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800441 errno = EINVAL;
442 return -1;
443 }
444
445 f = _fh_alloc( &_fh_file_class );
446 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800447 return -1;
448 }
449
Spencer Low50f5bf12015-11-12 15:20:15 -0800450 std::wstring path_wide;
451 if (!android::base::UTF8ToWide(path, &path_wide)) {
452 return -1;
453 }
454 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Low6815c072015-05-11 01:08:48 -0700455 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800456
457 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700458 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800459 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700460 D( "adb_open: could not open '%s': ", path );
461 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800462 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700463 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800464 errno = ENOENT;
465 return -1;
466
467 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700468 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800469 errno = ENOTDIR;
470 return -1;
471
472 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700473 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700474 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800475 errno = ENOENT;
476 return -1;
477 }
478 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800479
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800480 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700481 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800482 return _fh_to_int(f);
483}
484
485/* ignore mode on Win32 */
486int adb_creat(const char* path, int mode)
487{
488 FH f;
489
490 f = _fh_alloc( &_fh_file_class );
491 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800492 return -1;
493 }
494
Spencer Low50f5bf12015-11-12 15:20:15 -0800495 std::wstring path_wide;
496 if (!android::base::UTF8ToWide(path, &path_wide)) {
497 return -1;
498 }
499 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Low6815c072015-05-11 01:08:48 -0700500 FILE_SHARE_READ | FILE_SHARE_WRITE,
501 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
502 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800503
504 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700505 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800506 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700507 D( "adb_creat: could not open '%s': ", path );
508 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800509 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700510 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800511 errno = ENOENT;
512 return -1;
513
514 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700515 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800516 errno = ENOTDIR;
517 return -1;
518
519 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700520 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700521 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800522 errno = ENOENT;
523 return -1;
524 }
525 }
526 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700527 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800528 return _fh_to_int(f);
529}
530
531
532int adb_read(int fd, void* buf, int len)
533{
Spencer Low3a2421b2015-05-22 20:09:06 -0700534 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800535
536 if (f == NULL) {
537 return -1;
538 }
539
540 return f->clazz->_fh_read( f, buf, len );
541}
542
543
544int adb_write(int fd, const void* buf, int len)
545{
Spencer Low3a2421b2015-05-22 20:09:06 -0700546 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800547
548 if (f == NULL) {
549 return -1;
550 }
551
552 return f->clazz->_fh_write(f, buf, len);
553}
554
555
556int adb_lseek(int fd, int pos, int where)
557{
Spencer Low3a2421b2015-05-22 20:09:06 -0700558 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800559
560 if (!f) {
561 return -1;
562 }
563
564 return f->clazz->_fh_lseek(f, pos, where);
565}
566
567
568int adb_close(int fd)
569{
Spencer Low3a2421b2015-05-22 20:09:06 -0700570 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800571
572 if (!f) {
573 return -1;
574 }
575
Yabin Cui815ad882015-09-02 17:44:28 -0700576 D( "adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800577 _fh_close(f);
578 return 0;
579}
580
Spencer Low028e1592015-10-18 16:45:09 -0700581// Overrides strerror() to handle error codes not supported by the Windows C
582// Runtime (MSVCRT.DLL).
583char* adb_strerror(int err) {
584 // sysdeps.h defines strerror to adb_strerror, but in this function, we
585 // want to call the real C Runtime strerror().
586#pragma push_macro("strerror")
587#undef strerror
588 const int saved_err = errno; // Save because we overwrite it later.
589
590 // Lookup the string for an unknown error.
591 char* errmsg = strerror(-1);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700592 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low028e1592015-10-18 16:45:09 -0700593
594 // Lookup the string for this error to see if the C Runtime has it.
595 errmsg = strerror(err);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700596 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low028e1592015-10-18 16:45:09 -0700597 // The CRT returned an error message and it is different than the error
598 // message for an unknown error, so it is probably valid, so use it.
599 } else {
600 // Check if we have a string for this error code.
601 const char* custom_msg = nullptr;
602 switch (err) {
603#pragma push_macro("ERR")
604#undef ERR
605#define ERR(errnum, desc) case errnum: custom_msg = desc; break
606 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
607 // Note that these cannot be longer than 94 characters because we
608 // pass this to _strerror() which has that requirement.
609 ERR(ECONNRESET, "Connection reset by peer");
610 ERR(EHOSTUNREACH, "No route to host");
611 ERR(ENETDOWN, "Network is down");
612 ERR(ENETRESET, "Network dropped connection because of reset");
613 ERR(ENOBUFS, "No buffer space available");
614 ERR(ENOPROTOOPT, "Protocol not available");
615 ERR(ENOTCONN, "Transport endpoint is not connected");
616 ERR(ENOTSOCK, "Socket operation on non-socket");
617 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
618#pragma pop_macro("ERR")
619 }
620
621 if (custom_msg != nullptr) {
622 // Use _strerror() to write our string into the writable per-thread
623 // buffer used by strerror()/_strerror(). _strerror() appends the
624 // msg for the current value of errno, so set errno to a consistent
625 // value for every call so that our code-path is always the same.
626 errno = 0;
627 errmsg = _strerror(custom_msg);
628 const size_t custom_msg_len = strlen(custom_msg);
629 // Just in case _strerror() returned a read-only string, check if
630 // the returned string starts with our custom message because that
631 // implies that the string is not read-only.
632 if ((errmsg != nullptr) &&
633 !strncmp(custom_msg, errmsg, custom_msg_len)) {
634 // _strerror() puts other text after our custom message, so
635 // remove that by terminating after our message.
636 errmsg[custom_msg_len] = '\0';
637 } else {
638 // For some reason nullptr was returned or a pointer to a
639 // read-only string was returned, so fallback to whatever
640 // strerror() can muster (probably "Unknown error" or some
641 // generic CRT error string).
642 errmsg = strerror(err);
643 }
644 } else {
645 // We don't have a custom message, so use whatever strerror(err)
646 // returned earlier.
647 }
648 }
649
650 errno = saved_err; // restore
651
652 return errmsg;
653#pragma pop_macro("strerror")
654}
655
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800656/**************************************************************************/
657/**************************************************************************/
658/***** *****/
659/***** socket-based file descriptors *****/
660/***** *****/
661/**************************************************************************/
662/**************************************************************************/
663
Spencer Low31aafa62015-01-25 14:40:16 -0800664#undef setsockopt
665
Spencer Low753d4852015-07-30 23:07:55 -0700666static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700667 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
668 // lot of POSIX and socket error codes, some of the resulting error codes
669 // are mapped to strings by adb_strerror() above.
Spencer Low753d4852015-07-30 23:07:55 -0700670 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800671 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700672 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
673 // case WSAEINTR: errno = EINTR; break;
674 case WSAEFAULT: errno = EFAULT; break;
675 case WSAEINVAL: errno = EINVAL; break;
676 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700677 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
678 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
679 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800680 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700681 case WSAENOTSOCK: errno = ENOTSOCK; break;
682 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
683 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
684 case WSAENETDOWN: errno = ENETDOWN; break;
685 case WSAENETRESET: errno = ENETRESET; break;
686 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
687 // to use EPIPE for these situations and there are some callers that look
688 // for EPIPE.
689 case WSAECONNABORTED: errno = EPIPE; break;
690 case WSAECONNRESET: errno = ECONNRESET; break;
691 case WSAENOBUFS: errno = ENOBUFS; break;
692 case WSAENOTCONN: errno = ENOTCONN; break;
693 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
694 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
695 // considerations: Reportedly send() can return zero on timeout, and POSIX
696 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
697 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
698 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800699 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800700 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700701 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700702 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800703 }
704}
705
Elliott Hughes6a096932015-04-16 16:47:02 -0700706static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800707 f->fh_socket = INVALID_SOCKET;
708 f->event = WSACreateEvent();
Spencer Low753d4852015-07-30 23:07:55 -0700709 if (f->event == WSA_INVALID_EVENT) {
Yabin Cui815ad882015-09-02 17:44:28 -0700710 D("WSACreateEvent failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700711 SystemErrorCodeToString(WSAGetLastError()).c_str());
712
713 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
714 // on failure, instead of NULL which is what Windows really returns on
715 // error. It might be better to change all the other code to look for
716 // NULL, but that is a much riskier change.
717 f->event = INVALID_HANDLE_VALUE;
718 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800719 f->mask = 0;
720}
721
Elliott Hughes6a096932015-04-16 16:47:02 -0700722static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700723 if (f->fh_socket != INVALID_SOCKET) {
724 /* gently tell any peer that we're closing the socket */
725 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
726 // If the socket is not connected, this returns an error. We want to
727 // minimize logging spam, so don't log these errors for now.
728#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700729 D("socket shutdown failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700730 SystemErrorCodeToString(WSAGetLastError()).c_str());
731#endif
732 }
733 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Yabin Cui815ad882015-09-02 17:44:28 -0700734 D("closesocket failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700735 SystemErrorCodeToString(WSAGetLastError()).c_str());
736 }
737 f->fh_socket = INVALID_SOCKET;
738 }
739 if (f->event != NULL) {
740 if (!CloseHandle(f->event)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700741 D("CloseHandle failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700742 SystemErrorCodeToString(GetLastError()).c_str());
743 }
744 f->event = NULL;
745 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800746 f->mask = 0;
747 return 0;
748}
749
Elliott Hughes6a096932015-04-16 16:47:02 -0700750static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800751 errno = EPIPE;
752 return -1;
753}
754
Elliott Hughes6a096932015-04-16 16:47:02 -0700755static int _fh_socket_read(FH f, void* buf, int len) {
756 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800757 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700758 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700759 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
760 // that to reduce spam and confusion.
761 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700762 D("recv fd %d failed: %s", _fh_to_int(f),
Spencer Low32625852015-08-11 16:45:32 -0700763 SystemErrorCodeToString(err).c_str());
764 }
Spencer Low753d4852015-07-30 23:07:55 -0700765 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800766 result = -1;
767 }
768 return result;
769}
770
Elliott Hughes6a096932015-04-16 16:47:02 -0700771static int _fh_socket_write(FH f, const void* buf, int len) {
772 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800773 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700774 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700775 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
776 // that to reduce spam and confusion.
777 if (err != WSAEWOULDBLOCK) {
778 D("send fd %d failed: %s", _fh_to_int(f),
779 SystemErrorCodeToString(err).c_str());
780 }
Spencer Low753d4852015-07-30 23:07:55 -0700781 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800782 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700783 } else {
784 // According to https://code.google.com/p/chromium/issues/detail?id=27870
785 // Winsock Layered Service Providers may cause this.
786 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
787 << f->name << ", but " << result
788 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800789 }
790 return result;
791}
792
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800793/**************************************************************************/
794/**************************************************************************/
795/***** *****/
796/***** replacement for libs/cutils/socket_xxxx.c *****/
797/***** *****/
798/**************************************************************************/
799/**************************************************************************/
800
801#include <winsock2.h>
802
803static int _winsock_init;
804
805static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800806_init_winsock( void )
807{
Spencer Low753d4852015-07-30 23:07:55 -0700808 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700809 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800810 if (!_winsock_init) {
811 WSADATA wsaData;
812 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
813 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700814 fatal( "adb: could not initialize Winsock: %s",
815 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800816 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800817 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700818
819 // Note that we do not call atexit() to register WSACleanup to be called
820 // at normal process termination because:
821 // 1) When exit() is called, there are still threads actively using
822 // Winsock because we don't cleanly shutdown all threads, so it
823 // doesn't make sense to call WSACleanup() and may cause problems
824 // with those threads.
825 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
826 // calls WSACleanup() which tries to unload a DLL, which tries to
827 // grab the LoaderLock. This conflicts with the device_poll_thread
828 // which holds the LoaderLock because AdbWinApi.dll calls
829 // setupapi.dll which tries to load wintrust.dll which tries to load
830 // crypt32.dll which calls atexit() which tries to acquire the C
831 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800832 }
833}
834
Spencer Lowc7c45612015-09-29 15:05:29 -0700835// Map a socket type to an explicit socket protocol instead of using the socket
836// protocol of 0. Explicit socket protocols are used by most apps and we should
837// do the same to reduce the chance of exercising uncommon code-paths that might
838// have problems or that might load different Winsock service providers that
839// have problems.
840static int GetSocketProtocolFromSocketType(int type) {
841 switch (type) {
842 case SOCK_STREAM:
843 return IPPROTO_TCP;
844 case SOCK_DGRAM:
845 return IPPROTO_UDP;
846 default:
847 LOG(FATAL) << "Unknown socket type: " << type;
848 return 0;
849 }
850}
851
Spencer Low753d4852015-07-30 23:07:55 -0700852int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800853 struct sockaddr_in addr;
854 SOCKET s;
855
Spencer Low753d4852015-07-30 23:07:55 -0700856 unique_fh f(_fh_alloc(&_fh_socket_class));
857 if (!f) {
858 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800859 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700860 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800861
862 if (!_winsock_init)
863 _init_winsock();
864
865 memset(&addr, 0, sizeof(addr));
866 addr.sin_family = AF_INET;
867 addr.sin_port = htons(port);
868 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
869
Spencer Lowc7c45612015-09-29 15:05:29 -0700870 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800871 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700872 *error = android::base::StringPrintf("cannot create socket: %s",
873 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700874 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700875 return -1;
876 }
877 f->fh_socket = s;
878
879 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700880 // Save err just in case inet_ntoa() or ntohs() changes the last error.
881 const DWORD err = WSAGetLastError();
882 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
883 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
884 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700885 D("could not connect to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700886 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800887 return -1;
888 }
889
Spencer Low753d4852015-07-30 23:07:55 -0700890 const int fd = _fh_to_int(f.get());
891 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
892 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700893 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700894 fd );
895 f.release();
896 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800897}
898
899#define LISTEN_BACKLOG 4
900
Spencer Low753d4852015-07-30 23:07:55 -0700901// interface_address is INADDR_LOOPBACK or INADDR_ANY.
902static int _network_server(int port, int type, u_long interface_address,
903 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800904 struct sockaddr_in addr;
905 SOCKET s;
906 int n;
907
Spencer Low753d4852015-07-30 23:07:55 -0700908 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800909 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700910 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800911 return -1;
912 }
913
914 if (!_winsock_init)
915 _init_winsock();
916
917 memset(&addr, 0, sizeof(addr));
918 addr.sin_family = AF_INET;
919 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700920 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800921
Spencer Low753d4852015-07-30 23:07:55 -0700922 // TODO: Consider using dual-stack socket that can simultaneously listen on
923 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700924 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700925 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700926 *error = android::base::StringPrintf("cannot create socket: %s",
927 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700928 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700929 return -1;
930 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800931
932 f->fh_socket = s;
933
Spencer Low32625852015-08-11 16:45:32 -0700934 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
935 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800936 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700937 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
938 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700939 *error = android::base::StringPrintf(
940 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
941 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700942 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700943 return -1;
944 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800945
Spencer Low32625852015-08-11 16:45:32 -0700946 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
947 // Save err just in case inet_ntoa() or ntohs() changes the last error.
948 const DWORD err = WSAGetLastError();
949 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
950 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
951 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700952 D("could not bind to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700953 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800954 return -1;
955 }
956 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700957 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700958 *error = android::base::StringPrintf("cannot listen on socket: %s",
959 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700960 D("could not listen on %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700961 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800962 return -1;
963 }
964 }
Spencer Low753d4852015-07-30 23:07:55 -0700965 const int fd = _fh_to_int(f.get());
966 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
967 interface_address == INADDR_LOOPBACK ? "lo" : "any",
968 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700969 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700970 fd );
971 f.release();
972 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800973}
974
Spencer Low753d4852015-07-30 23:07:55 -0700975int network_loopback_server(int port, int type, std::string* error) {
976 return _network_server(port, type, INADDR_LOOPBACK, error);
977}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800978
Spencer Low753d4852015-07-30 23:07:55 -0700979int network_inaddr_any_server(int port, int type, std::string* error) {
980 return _network_server(port, type, INADDR_ANY, error);
981}
982
983int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
984 unique_fh f(_fh_alloc(&_fh_socket_class));
985 if (!f) {
986 *error = strerror(errno);
987 return -1;
988 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800989
Elliott Hughes43df1092015-07-23 17:12:58 -0700990 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800991
Spencer Low753d4852015-07-30 23:07:55 -0700992 struct addrinfo hints;
993 memset(&hints, 0, sizeof(hints));
994 hints.ai_family = AF_UNSPEC;
995 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700996 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700997
998 char port_str[16];
999 snprintf(port_str, sizeof(port_str), "%d", port);
1000
1001 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -07001002
1003#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
1004 // TODO: When the Android SDK tools increases the Windows system
Spencer Low50f5bf12015-11-12 15:20:15 -08001005 // requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -07001006#else
1007 // Otherwise, keep using getaddrinfo(), or do runtime API detection
1008 // with GetProcAddress("GetAddrInfoW").
1009#endif
Spencer Low753d4852015-07-30 23:07:55 -07001010 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -07001011 *error = android::base::StringPrintf(
1012 "cannot resolve host '%s' and port %s: %s", host.c_str(),
1013 port_str, SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001014 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001015 return -1;
1016 }
Spencer Low753d4852015-07-30 23:07:55 -07001017 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
1018 addrinfo(addrinfo_ptr, freeaddrinfo);
1019 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001020
Spencer Low753d4852015-07-30 23:07:55 -07001021 // TODO: Try all the addresses if there's more than one? This just uses
1022 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
1023 // which tries all addresses, takes a timeout and more.
1024 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
1025 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001026 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -07001027 *error = android::base::StringPrintf("cannot create socket: %s",
1028 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001029 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001030 return -1;
1031 }
1032 f->fh_socket = s;
1033
Spencer Low753d4852015-07-30 23:07:55 -07001034 // TODO: Implement timeouts for Windows. Seems like the default in theory
1035 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
1036 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -07001037 // TODO: Use WSAAddressToString or inet_ntop on address.
1038 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
1039 host.c_str(), port_str,
1040 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001041 D("could not connect to %s:%s:%s: %s",
Spencer Low753d4852015-07-30 23:07:55 -07001042 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
1043 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001044 return -1;
1045 }
1046
Spencer Low753d4852015-07-30 23:07:55 -07001047 const int fd = _fh_to_int(f.get());
1048 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
1049 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -07001050 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low753d4852015-07-30 23:07:55 -07001051 type != SOCK_STREAM ? "udp" : "tcp", fd );
1052 f.release();
1053 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001054}
1055
1056#undef accept
1057int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
1058{
Spencer Low3a2421b2015-05-22 20:09:06 -07001059 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001060
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001061 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001062 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -07001063 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001064 return -1;
1065 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001066
Spencer Low753d4852015-07-30 23:07:55 -07001067 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001068 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -07001069 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1070 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001071 return -1;
1072 }
1073
1074 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1075 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001076 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -07001077 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
1078 " failed: " + SystemErrorCodeToString(err);
1079 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001080 return -1;
1081 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001082
Spencer Low753d4852015-07-30 23:07:55 -07001083 const int fd = _fh_to_int(fh.get());
1084 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -07001085 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -07001086 fh.release();
1087 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001088}
1089
1090
Spencer Low31aafa62015-01-25 14:40:16 -08001091int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001092{
Spencer Low3a2421b2015-05-22 20:09:06 -07001093 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001094
Spencer Low31aafa62015-01-25 14:40:16 -08001095 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001096 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001097 errno = EBADF;
1098 return -1;
1099 }
Spencer Lowc7c45612015-09-29 15:05:29 -07001100
1101 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1102 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1103 // auto-tuning.
1104
Spencer Low753d4852015-07-30 23:07:55 -07001105 int result = setsockopt( fh->fh_socket, level, optname,
1106 reinterpret_cast<const char*>(optval), optlen );
1107 if ( result == SOCKET_ERROR ) {
1108 const DWORD err = WSAGetLastError();
1109 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
1110 "failed: %s\n", fd, level, optname,
1111 SystemErrorCodeToString(err).c_str() );
1112 _socket_set_errno( err );
1113 result = -1;
1114 }
1115 return result;
1116}
1117
1118
1119int adb_shutdown(int fd)
1120{
1121 FH f = _fh_from_int(fd, __func__);
1122
1123 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001124 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001125 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001126 return -1;
1127 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001128
Yabin Cui815ad882015-09-02 17:44:28 -07001129 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001130 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1131 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001132 D("socket shutdown fd %d failed: %s", fd,
Spencer Low753d4852015-07-30 23:07:55 -07001133 SystemErrorCodeToString(err).c_str());
1134 _socket_set_errno(err);
1135 return -1;
1136 }
1137 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001138}
1139
1140/**************************************************************************/
1141/**************************************************************************/
1142/***** *****/
1143/***** emulated socketpairs *****/
1144/***** *****/
1145/**************************************************************************/
1146/**************************************************************************/
1147
1148/* we implement socketpairs directly in use space for the following reasons:
1149 * - it avoids copying data from/to the Nt kernel
1150 * - it allows us to implement fdevent hooks easily and cheaply, something
1151 * that is not possible with standard Win32 pipes !!
1152 *
1153 * basically, we use two circular buffers, each one corresponding to a given
1154 * direction.
1155 *
1156 * each buffer is implemented as two regions:
1157 *
1158 * region A which is (a_start,a_end)
1159 * region B which is (0, b_end) with b_end <= a_start
1160 *
1161 * an empty buffer has: a_start = a_end = b_end = 0
1162 *
1163 * a_start is the pointer where we start reading data
1164 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
1165 * then you start writing at b_end
1166 *
1167 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
1168 *
1169 * there is room when b_end < a_start || a_end < BUFER_SIZE
1170 *
1171 * when reading, a_start is incremented, it a_start meets a_end, then
1172 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1173 */
1174
1175#define BIP_BUFFER_SIZE 4096
1176
1177#if 0
1178#include <stdio.h>
1179# define BIPD(x) D x
1180# define BIPDUMP bip_dump_hex
1181
1182static void bip_dump_hex( const unsigned char* ptr, size_t len )
1183{
1184 int nn, len2 = len;
1185
1186 if (len2 > 8) len2 = 8;
1187
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001188 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001189 printf("%02x", ptr[nn]);
1190 printf(" ");
1191
1192 for (nn = 0; nn < len2; nn++) {
1193 int c = ptr[nn];
1194 if (c < 32 || c > 127)
1195 c = '.';
1196 printf("%c", c);
1197 }
1198 printf("\n");
1199 fflush(stdout);
1200}
1201
1202#else
1203# define BIPD(x) do {} while (0)
1204# define BIPDUMP(p,l) BIPD(p)
1205#endif
1206
1207typedef struct BipBufferRec_
1208{
1209 int a_start;
1210 int a_end;
1211 int b_end;
1212 int fdin;
1213 int fdout;
1214 int closed;
1215 int can_write; /* boolean */
1216 HANDLE evt_write; /* event signaled when one can write to a buffer */
1217 int can_read; /* boolean */
1218 HANDLE evt_read; /* event signaled when one can read from a buffer */
1219 CRITICAL_SECTION lock;
1220 unsigned char buff[ BIP_BUFFER_SIZE ];
1221
1222} BipBufferRec, *BipBuffer;
1223
1224static void
1225bip_buffer_init( BipBuffer buffer )
1226{
Yabin Cui815ad882015-09-02 17:44:28 -07001227 D( "bit_buffer_init %p", buffer );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001228 buffer->a_start = 0;
1229 buffer->a_end = 0;
1230 buffer->b_end = 0;
1231 buffer->can_write = 1;
1232 buffer->can_read = 0;
1233 buffer->fdin = 0;
1234 buffer->fdout = 0;
1235 buffer->closed = 0;
1236 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1237 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1238 InitializeCriticalSection( &buffer->lock );
1239}
1240
1241static void
1242bip_buffer_close( BipBuffer bip )
1243{
1244 bip->closed = 1;
1245
1246 if (!bip->can_read) {
1247 SetEvent( bip->evt_read );
1248 }
1249 if (!bip->can_write) {
1250 SetEvent( bip->evt_write );
1251 }
1252}
1253
1254static void
1255bip_buffer_done( BipBuffer bip )
1256{
Yabin Cui815ad882015-09-02 17:44:28 -07001257 BIPD(( "bip_buffer_done: %d->%d", bip->fdin, bip->fdout ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001258 CloseHandle( bip->evt_read );
1259 CloseHandle( bip->evt_write );
1260 DeleteCriticalSection( &bip->lock );
1261}
1262
1263static int
1264bip_buffer_write( BipBuffer bip, const void* src, int len )
1265{
1266 int avail, count = 0;
1267
1268 if (len <= 0)
1269 return 0;
1270
Yabin Cui815ad882015-09-02 17:44:28 -07001271 BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001272 BIPDUMP( src, len );
1273
David Pursell7616ae12015-09-11 16:06:59 -07001274 if (bip->closed) {
1275 errno = EPIPE;
1276 return -1;
1277 }
1278
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001279 EnterCriticalSection( &bip->lock );
1280
1281 while (!bip->can_write) {
1282 int ret;
1283 LeaveCriticalSection( &bip->lock );
1284
1285 if (bip->closed) {
1286 errno = EPIPE;
1287 return -1;
1288 }
1289 /* spinlocking here is probably unfair, but let's live with it */
1290 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1291 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
Yabin Cui815ad882015-09-02 17:44:28 -07001292 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001293 return 0;
1294 }
1295 if (bip->closed) {
1296 errno = EPIPE;
1297 return -1;
1298 }
1299 EnterCriticalSection( &bip->lock );
1300 }
1301
Yabin Cui815ad882015-09-02 17:44:28 -07001302 BIPD(( "bip_buffer_write: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001303
1304 avail = BIP_BUFFER_SIZE - bip->a_end;
1305 if (avail > 0)
1306 {
1307 /* we can append to region A */
1308 if (avail > len)
1309 avail = len;
1310
1311 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001312 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001313 count += avail;
1314 len -= avail;
1315
1316 bip->a_end += avail;
1317 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1318 bip->can_write = 0;
1319 ResetEvent( bip->evt_write );
1320 goto Exit;
1321 }
1322 }
1323
1324 if (len == 0)
1325 goto Exit;
1326
1327 avail = bip->a_start - bip->b_end;
1328 assert( avail > 0 ); /* since can_write is TRUE */
1329
1330 if (avail > len)
1331 avail = len;
1332
1333 memcpy( bip->buff + bip->b_end, src, avail );
1334 count += avail;
1335 bip->b_end += avail;
1336
1337 if (bip->b_end == bip->a_start) {
1338 bip->can_write = 0;
1339 ResetEvent( bip->evt_write );
1340 }
1341
1342Exit:
1343 assert( count > 0 );
1344
1345 if ( !bip->can_read ) {
1346 bip->can_read = 1;
1347 SetEvent( bip->evt_read );
1348 }
1349
Yabin Cui815ad882015-09-02 17:44:28 -07001350 BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001351 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1352 LeaveCriticalSection( &bip->lock );
1353
1354 return count;
1355 }
1356
1357static int
1358bip_buffer_read( BipBuffer bip, void* dst, int len )
1359{
1360 int avail, count = 0;
1361
1362 if (len <= 0)
1363 return 0;
1364
Yabin Cui815ad882015-09-02 17:44:28 -07001365 BIPD(( "bip_buffer_read: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001366
1367 EnterCriticalSection( &bip->lock );
1368 while ( !bip->can_read )
1369 {
1370#if 0
1371 LeaveCriticalSection( &bip->lock );
1372 errno = EAGAIN;
1373 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001374#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001375 int ret;
1376 LeaveCriticalSection( &bip->lock );
1377
1378 if (bip->closed) {
1379 errno = EPIPE;
1380 return -1;
1381 }
1382
1383 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1384 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
Yabin Cui815ad882015-09-02 17:44:28 -07001385 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001386 return 0;
1387 }
1388 if (bip->closed) {
1389 errno = EPIPE;
1390 return -1;
1391 }
1392 EnterCriticalSection( &bip->lock );
1393#endif
1394 }
1395
Yabin Cui815ad882015-09-02 17:44:28 -07001396 BIPD(( "bip_buffer_read: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001397
1398 avail = bip->a_end - bip->a_start;
1399 assert( avail > 0 ); /* since can_read is TRUE */
1400
1401 if (avail > len)
1402 avail = len;
1403
1404 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001405 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001406 count += avail;
1407 len -= avail;
1408
1409 bip->a_start += avail;
1410 if (bip->a_start < bip->a_end)
1411 goto Exit;
1412
1413 bip->a_start = 0;
1414 bip->a_end = bip->b_end;
1415 bip->b_end = 0;
1416
1417 avail = bip->a_end;
1418 if (avail > 0) {
1419 if (avail > len)
1420 avail = len;
1421 memcpy( dst, bip->buff, avail );
1422 count += avail;
1423 bip->a_start += avail;
1424
1425 if ( bip->a_start < bip->a_end )
1426 goto Exit;
1427
1428 bip->a_start = bip->a_end = 0;
1429 }
1430
1431 bip->can_read = 0;
1432 ResetEvent( bip->evt_read );
1433
1434Exit:
1435 assert( count > 0 );
1436
1437 if (!bip->can_write ) {
1438 bip->can_write = 1;
1439 SetEvent( bip->evt_write );
1440 }
1441
1442 BIPDUMP( (const unsigned char*)dst - count, count );
Yabin Cui815ad882015-09-02 17:44:28 -07001443 BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001444 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1445 LeaveCriticalSection( &bip->lock );
1446
1447 return count;
1448}
1449
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001450typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001451{
1452 BipBufferRec a2b_bip;
1453 BipBufferRec b2a_bip;
1454 FH a_fd;
1455 int used;
1456
1457} SocketPairRec;
1458
1459void _fh_socketpair_init( FH f )
1460{
1461 f->fh_pair = NULL;
1462}
1463
1464static int
1465_fh_socketpair_close( FH f )
1466{
1467 if ( f->fh_pair ) {
1468 SocketPair pair = f->fh_pair;
1469
1470 if ( f == pair->a_fd ) {
1471 pair->a_fd = NULL;
1472 }
1473
1474 bip_buffer_close( &pair->b2a_bip );
1475 bip_buffer_close( &pair->a2b_bip );
1476
1477 if ( --pair->used == 0 ) {
1478 bip_buffer_done( &pair->b2a_bip );
1479 bip_buffer_done( &pair->a2b_bip );
1480 free( pair );
1481 }
1482 f->fh_pair = NULL;
1483 }
1484 return 0;
1485}
1486
1487static int
1488_fh_socketpair_lseek( FH f, int pos, int origin )
1489{
1490 errno = ESPIPE;
1491 return -1;
1492}
1493
1494static int
1495_fh_socketpair_read( FH f, void* buf, int len )
1496{
1497 SocketPair pair = f->fh_pair;
1498 BipBuffer bip;
1499
1500 if (!pair)
1501 return -1;
1502
1503 if ( f == pair->a_fd )
1504 bip = &pair->b2a_bip;
1505 else
1506 bip = &pair->a2b_bip;
1507
1508 return bip_buffer_read( bip, buf, len );
1509}
1510
1511static int
1512_fh_socketpair_write( FH f, const void* buf, int len )
1513{
1514 SocketPair pair = f->fh_pair;
1515 BipBuffer bip;
1516
1517 if (!pair)
1518 return -1;
1519
1520 if ( f == pair->a_fd )
1521 bip = &pair->a2b_bip;
1522 else
1523 bip = &pair->b2a_bip;
1524
1525 return bip_buffer_write( bip, buf, len );
1526}
1527
1528
1529static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1530
1531static const FHClassRec _fh_socketpair_class =
1532{
1533 _fh_socketpair_init,
1534 _fh_socketpair_close,
1535 _fh_socketpair_lseek,
1536 _fh_socketpair_read,
1537 _fh_socketpair_write,
1538 _fh_socketpair_hook
1539};
1540
1541
Elliott Hughes6a096932015-04-16 16:47:02 -07001542int adb_socketpair(int sv[2]) {
1543 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001544
Spencer Low753d4852015-07-30 23:07:55 -07001545 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1546 if (!fa) {
1547 return -1;
1548 }
1549 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1550 if (!fb) {
1551 return -1;
1552 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001553
Elliott Hughes6a096932015-04-16 16:47:02 -07001554 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001555 if (pair == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001556 D("adb_socketpair: not enough memory to allocate pipes" );
Spencer Low753d4852015-07-30 23:07:55 -07001557 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001558 }
1559
1560 bip_buffer_init( &pair->a2b_bip );
1561 bip_buffer_init( &pair->b2a_bip );
1562
1563 fa->fh_pair = pair;
1564 fb->fh_pair = pair;
1565 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001566 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001567
Spencer Low753d4852015-07-30 23:07:55 -07001568 sv[0] = _fh_to_int(fa.get());
1569 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001570
1571 pair->a2b_bip.fdin = sv[0];
1572 pair->a2b_bip.fdout = sv[1];
1573 pair->b2a_bip.fdin = sv[1];
1574 pair->b2a_bip.fdout = sv[0];
1575
1576 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1577 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
Yabin Cui815ad882015-09-02 17:44:28 -07001578 D( "adb_socketpair: returns (%d, %d)", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001579 fa.release();
1580 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001581 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001582}
1583
1584/**************************************************************************/
1585/**************************************************************************/
1586/***** *****/
1587/***** fdevents emulation *****/
1588/***** *****/
1589/***** this is a very simple implementation, we rely on the fact *****/
1590/***** that ADB doesn't use FDE_ERROR. *****/
1591/***** *****/
1592/**************************************************************************/
1593/**************************************************************************/
1594
Josh Gao2930cdc2016-01-15 15:17:37 -08001595#define FATAL(fmt, ...) fatal("%s: " fmt, __FUNCTION__, ##__VA_ARGS__)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001596
1597#if DEBUG
1598static void dump_fde(fdevent *fde, const char *info)
1599{
1600 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1601 fde->state & FDE_READ ? 'R' : ' ',
1602 fde->state & FDE_WRITE ? 'W' : ' ',
1603 fde->state & FDE_ERROR ? 'E' : ' ',
1604 info);
1605}
1606#else
1607#define dump_fde(fde, info) do { } while(0)
1608#endif
1609
1610#define FDE_EVENTMASK 0x00ff
1611#define FDE_STATEMASK 0xff00
1612
1613#define FDE_ACTIVE 0x0100
1614#define FDE_PENDING 0x0200
1615#define FDE_CREATED 0x0400
1616
1617static void fdevent_plist_enqueue(fdevent *node);
1618static void fdevent_plist_remove(fdevent *node);
1619static fdevent *fdevent_plist_dequeue(void);
1620
1621static fdevent list_pending = {
1622 .next = &list_pending,
1623 .prev = &list_pending,
1624};
1625
1626static fdevent **fd_table = 0;
1627static int fd_table_max = 0;
1628
1629typedef struct EventLooperRec_* EventLooper;
1630
1631typedef struct EventHookRec_
1632{
1633 EventHook next;
1634 FH fh;
1635 HANDLE h;
1636 int wanted; /* wanted event flags */
1637 int ready; /* ready event flags */
1638 void* aux;
1639 void (*prepare)( EventHook hook );
1640 int (*start) ( EventHook hook );
1641 void (*stop) ( EventHook hook );
1642 int (*check) ( EventHook hook );
1643 int (*peek) ( EventHook hook );
1644} EventHookRec;
1645
1646static EventHook _free_hooks;
1647
1648static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001649event_hook_alloc(FH fh) {
1650 EventHook hook = _free_hooks;
1651 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001652 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001653 } else {
1654 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001655 if (hook == NULL)
1656 fatal( "could not allocate event hook\n" );
1657 }
1658 hook->next = NULL;
1659 hook->fh = fh;
1660 hook->wanted = 0;
1661 hook->ready = 0;
1662 hook->h = INVALID_HANDLE_VALUE;
1663 hook->aux = NULL;
1664
1665 hook->prepare = NULL;
1666 hook->start = NULL;
1667 hook->stop = NULL;
1668 hook->check = NULL;
1669 hook->peek = NULL;
1670
1671 return hook;
1672}
1673
1674static void
1675event_hook_free( EventHook hook )
1676{
1677 hook->fh = NULL;
1678 hook->wanted = 0;
1679 hook->ready = 0;
1680 hook->next = _free_hooks;
1681 _free_hooks = hook;
1682}
1683
1684
1685static void
1686event_hook_signal( EventHook hook )
1687{
1688 FH f = hook->fh;
1689 int fd = _fh_to_int(f);
1690 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1691
1692 if (fde != NULL && fde->fd == fd) {
1693 if ((fde->state & FDE_PENDING) == 0) {
1694 fde->state |= FDE_PENDING;
1695 fdevent_plist_enqueue( fde );
1696 }
1697 fde->events |= hook->wanted;
1698 }
1699}
1700
1701
1702#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1703
1704typedef struct EventLooperRec_
1705{
1706 EventHook hooks;
1707 HANDLE htab[ MAX_LOOPER_HANDLES ];
1708 int htab_count;
1709
1710} EventLooperRec;
1711
1712static EventHook*
1713event_looper_find_p( EventLooper looper, FH fh )
1714{
1715 EventHook *pnode = &looper->hooks;
1716 EventHook node = *pnode;
1717 for (;;) {
1718 if ( node == NULL || node->fh == fh )
1719 break;
1720 pnode = &node->next;
1721 node = *pnode;
1722 }
1723 return pnode;
1724}
1725
1726static void
1727event_looper_hook( EventLooper looper, int fd, int events )
1728{
Spencer Low3a2421b2015-05-22 20:09:06 -07001729 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001730 EventHook *pnode;
1731 EventHook node;
1732
1733 if (f == NULL) /* invalid arg */ {
Yabin Cui815ad882015-09-02 17:44:28 -07001734 D("event_looper_hook: invalid fd=%d", fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001735 return;
1736 }
1737
1738 pnode = event_looper_find_p( looper, f );
1739 node = *pnode;
1740 if ( node == NULL ) {
1741 node = event_hook_alloc( f );
1742 node->next = *pnode;
1743 *pnode = node;
1744 }
1745
1746 if ( (node->wanted & events) != events ) {
1747 /* this should update start/stop/check/peek */
Yabin Cui815ad882015-09-02 17:44:28 -07001748 D("event_looper_hook: call hook for %d (new=%x, old=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001749 fd, node->wanted, events);
1750 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1751 node->wanted |= events;
1752 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07001753 D("event_looper_hook: ignoring events %x for %d wanted=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001754 events, fd, node->wanted);
1755 }
1756}
1757
1758static void
1759event_looper_unhook( EventLooper looper, int fd, int events )
1760{
Spencer Low3a2421b2015-05-22 20:09:06 -07001761 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001762 EventHook *pnode = event_looper_find_p( looper, fh );
1763 EventHook node = *pnode;
1764
1765 if (node != NULL) {
1766 int events2 = events & node->wanted;
1767 if ( events2 == 0 ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001768 D( "event_looper_unhook: events %x not registered for fd %d", events, fd );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001769 return;
1770 }
1771 node->wanted &= ~events2;
1772 if (!node->wanted) {
1773 *pnode = node->next;
1774 event_hook_free( node );
1775 }
1776 }
1777}
1778
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001779/*
1780 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1781 * handles to wait on.
1782 *
1783 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1784 * instance, this may happen if there are more than 64 processes running on a
1785 * device, or there are multiple devices connected (including the emulator) with
1786 * the combined number of running processes greater than 64. In this case using
1787 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1788 * because of the API limitations (64 handles max). So, we need to provide a way
1789 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1790 * easiest (and "Microsoft recommended") way to do that would be dividing the
1791 * handle array into chunks with the chunk size less than 64, and fire up as many
1792 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1793 * handles, and will report back to the caller which handle has been set.
1794 * Here is the implementation of that algorithm.
1795 */
1796
1797/* Number of handles to wait on in each wating thread. */
1798#define WAIT_ALL_CHUNK_SIZE 63
1799
1800/* Descriptor for a wating thread */
1801typedef struct WaitForAllParam {
1802 /* A handle to an event to signal when waiting is over. This handle is shared
1803 * accross all the waiting threads, so each waiting thread knows when any
1804 * other thread has exited, so it can exit too. */
1805 HANDLE main_event;
1806 /* Upon exit from a waiting thread contains the index of the handle that has
1807 * been signaled. The index is an absolute index of the signaled handle in
1808 * the original array. This pointer is shared accross all the waiting threads
1809 * and it's not guaranteed (due to a race condition) that when all the
1810 * waiting threads exit, the value contained here would indicate the first
1811 * handle that was signaled. This is fine, because the caller cares only
1812 * about any handle being signaled. It doesn't care about the order, nor
1813 * about the whole list of handles that were signaled. */
1814 LONG volatile *signaled_index;
1815 /* Array of handles to wait on in a waiting thread. */
1816 HANDLE* handles;
1817 /* Number of handles in 'handles' array to wait on. */
1818 int handles_count;
1819 /* Index inside the main array of the first handle in the 'handles' array. */
1820 int first_handle_index;
1821 /* Waiting thread handle. */
1822 HANDLE thread;
1823} WaitForAllParam;
1824
1825/* Waiting thread routine. */
1826static unsigned __stdcall
1827_in_waiter_thread(void* arg)
1828{
1829 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1830 int res;
1831 WaitForAllParam* const param = (WaitForAllParam*)arg;
1832
1833 /* We have to wait on the main_event in order to be notified when any of the
1834 * sibling threads is exiting. */
1835 wait_on[0] = param->main_event;
1836 /* The rest of the handles go behind the main event handle. */
1837 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1838
1839 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1840 if (res > 0 && res < (param->handles_count + 1)) {
1841 /* One of the original handles got signaled. Save its absolute index into
1842 * the output variable. */
1843 InterlockedCompareExchange(param->signaled_index,
1844 res - 1L + param->first_handle_index, -1L);
1845 }
1846
1847 /* Notify the caller (and the siblings) that the wait is over. */
1848 SetEvent(param->main_event);
1849
1850 _endthreadex(0);
1851 return 0;
1852}
1853
1854/* WaitForMultipeObjects fixer routine.
1855 * Param:
1856 * handles Array of handles to wait on.
1857 * handles_count Number of handles in the array.
1858 * Return:
1859 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1860 * WAIT_FAILED on an error.
1861 */
1862static int
1863_wait_for_all(HANDLE* handles, int handles_count)
1864{
1865 WaitForAllParam* threads;
1866 HANDLE main_event;
1867 int chunks, chunk, remains;
1868
1869 /* This variable is going to be accessed by several threads at the same time,
1870 * this is bound to fail randomly when the core is run on multi-core machines.
1871 * To solve this, we need to do the following (1 _and_ 2):
1872 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1873 * out the reads/writes in this function unexpectedly.
1874 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1875 * all accesses inside a critical section. But we can also use
1876 * InterlockedCompareExchange() which always provide a full memory barrier
1877 * on Win32.
1878 */
1879 volatile LONG sig_index = -1;
1880
1881 /* Calculate number of chunks, and allocate thread param array. */
1882 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1883 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1884 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1885 sizeof(WaitForAllParam));
1886 if (threads == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001887 D("Unable to allocate thread array for %d handles.", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001888 return (int)WAIT_FAILED;
1889 }
1890
1891 /* Create main event to wait on for all waiting threads. This is a "manualy
1892 * reset" event that will remain set once it was set. */
1893 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1894 if (main_event == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001895 D("Unable to create main event. Error: %ld", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001896 free(threads);
1897 return (int)WAIT_FAILED;
1898 }
1899
1900 /*
1901 * Initialize waiting thread parameters.
1902 */
1903
1904 for (chunk = 0; chunk < chunks; chunk++) {
1905 threads[chunk].main_event = main_event;
1906 threads[chunk].signaled_index = &sig_index;
1907 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1908 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1909 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1910 }
1911 if (remains) {
1912 threads[chunk].main_event = main_event;
1913 threads[chunk].signaled_index = &sig_index;
1914 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1915 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1916 threads[chunk].handles_count = remains;
1917 chunks++;
1918 }
1919
1920 /* Start the waiting threads. */
1921 for (chunk = 0; chunk < chunks; chunk++) {
1922 /* Note that using adb_thread_create is not appropriate here, since we
1923 * need a handle to wait on for thread termination. */
1924 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1925 &threads[chunk], 0, NULL);
1926 if (threads[chunk].thread == NULL) {
1927 /* Unable to create a waiter thread. Collapse. */
Yabin Cui815ad882015-09-02 17:44:28 -07001928 D("Unable to create a waiting thread %d of %d. errno=%d",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001929 chunk, chunks, errno);
1930 chunks = chunk;
1931 SetEvent(main_event);
1932 break;
1933 }
1934 }
1935
1936 /* Wait on any of the threads to get signaled. */
1937 WaitForSingleObject(main_event, INFINITE);
1938
1939 /* Wait on all the waiting threads to exit. */
1940 for (chunk = 0; chunk < chunks; chunk++) {
1941 WaitForSingleObject(threads[chunk].thread, INFINITE);
1942 CloseHandle(threads[chunk].thread);
1943 }
1944
1945 CloseHandle(main_event);
1946 free(threads);
1947
1948
1949 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1950 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1951}
1952
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001953static EventLooperRec win32_looper;
1954
1955static void fdevent_init(void)
1956{
1957 win32_looper.htab_count = 0;
1958 win32_looper.hooks = NULL;
1959}
1960
1961static void fdevent_connect(fdevent *fde)
1962{
1963 EventLooper looper = &win32_looper;
1964 int events = fde->state & FDE_EVENTMASK;
1965
1966 if (events != 0)
1967 event_looper_hook( looper, fde->fd, events );
1968}
1969
1970static void fdevent_disconnect(fdevent *fde)
1971{
1972 EventLooper looper = &win32_looper;
1973 int events = fde->state & FDE_EVENTMASK;
1974
1975 if (events != 0)
1976 event_looper_unhook( looper, fde->fd, events );
1977}
1978
1979static void fdevent_update(fdevent *fde, unsigned events)
1980{
1981 EventLooper looper = &win32_looper;
1982 unsigned events0 = fde->state & FDE_EVENTMASK;
1983
1984 if (events != events0) {
1985 int removes = events0 & ~events;
1986 int adds = events & ~events0;
1987 if (removes) {
Yabin Cui815ad882015-09-02 17:44:28 -07001988 D("fdevent_update: remove %x from %d", removes, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001989 event_looper_unhook( looper, fde->fd, removes );
1990 }
1991 if (adds) {
Yabin Cui815ad882015-09-02 17:44:28 -07001992 D("fdevent_update: add %x to %d", adds, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001993 event_looper_hook ( looper, fde->fd, adds );
1994 }
1995 }
1996}
1997
1998static void fdevent_process()
1999{
2000 EventLooper looper = &win32_looper;
2001 EventHook hook;
2002 int gotone = 0;
2003
2004 /* if we have at least one ready hook, execute it/them */
2005 for (hook = looper->hooks; hook; hook = hook->next) {
2006 hook->ready = 0;
2007 if (hook->prepare) {
2008 hook->prepare(hook);
2009 if (hook->ready != 0) {
2010 event_hook_signal( hook );
2011 gotone = 1;
2012 }
2013 }
2014 }
2015
2016 /* nothing's ready yet, so wait for something to happen */
2017 if (!gotone)
2018 {
2019 looper->htab_count = 0;
2020
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002021 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002022 {
2023 if (hook->start && !hook->start(hook)) {
Yabin Cui815ad882015-09-02 17:44:28 -07002024 D( "fdevent_process: error when starting a hook" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002025 return;
2026 }
2027 if (hook->h != INVALID_HANDLE_VALUE) {
2028 int nn;
2029
2030 for (nn = 0; nn < looper->htab_count; nn++)
2031 {
2032 if ( looper->htab[nn] == hook->h )
2033 goto DontAdd;
2034 }
2035 looper->htab[ looper->htab_count++ ] = hook->h;
2036 DontAdd:
2037 ;
2038 }
2039 }
2040
2041 if (looper->htab_count == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -07002042 D( "fdevent_process: nothing to wait for !!" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002043 return;
2044 }
2045
2046 do
2047 {
2048 int wait_ret;
2049
Yabin Cui815ad882015-09-02 17:44:28 -07002050 D( "adb_win32: waiting for %d events", looper->htab_count );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002051 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Yabin Cui815ad882015-09-02 17:44:28 -07002052 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.", looper->htab_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002053 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
2054 } else {
2055 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002056 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002057 if (wait_ret == (int)WAIT_FAILED) {
Yabin Cui815ad882015-09-02 17:44:28 -07002058 D( "adb_win32: wait failed, error %ld", GetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002059 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07002060 D( "adb_win32: got one (index %d)", wait_ret );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002061
2062 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
2063 * like mouse movements. we need to filter these with the "check" function
2064 */
2065 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
2066 {
2067 for (hook = looper->hooks; hook; hook = hook->next)
2068 {
2069 if ( looper->htab[wait_ret] == hook->h &&
2070 (!hook->check || hook->check(hook)) )
2071 {
Yabin Cui815ad882015-09-02 17:44:28 -07002072 D( "adb_win32: signaling %s for %x", hook->fh->name, hook->ready );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002073 event_hook_signal( hook );
2074 gotone = 1;
2075 break;
2076 }
2077 }
2078 }
2079 }
2080 }
2081 while (!gotone);
2082
2083 for (hook = looper->hooks; hook; hook = hook->next) {
2084 if (hook->stop)
2085 hook->stop( hook );
2086 }
2087 }
2088
2089 for (hook = looper->hooks; hook; hook = hook->next) {
2090 if (hook->peek && hook->peek(hook))
2091 event_hook_signal( hook );
2092 }
2093}
2094
2095
2096static void fdevent_register(fdevent *fde)
2097{
2098 int fd = fde->fd - WIN32_FH_BASE;
2099
2100 if(fd < 0) {
2101 FATAL("bogus negative fd (%d)\n", fde->fd);
2102 }
2103
2104 if(fd >= fd_table_max) {
2105 int oldmax = fd_table_max;
2106 if(fde->fd > 32000) {
2107 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
2108 }
2109 if(fd_table_max == 0) {
2110 fdevent_init();
2111 fd_table_max = 256;
2112 }
2113 while(fd_table_max <= fd) {
2114 fd_table_max *= 2;
2115 }
Elliott Hughes6a096932015-04-16 16:47:02 -07002116 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002117 if(fd_table == 0) {
2118 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
2119 }
2120 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
2121 }
2122
2123 fd_table[fd] = fde;
2124}
2125
2126static void fdevent_unregister(fdevent *fde)
2127{
2128 int fd = fde->fd - WIN32_FH_BASE;
2129
2130 if((fd < 0) || (fd >= fd_table_max)) {
2131 FATAL("fd out of range (%d)\n", fde->fd);
2132 }
2133
2134 if(fd_table[fd] != fde) {
2135 FATAL("fd_table out of sync");
2136 }
2137
2138 fd_table[fd] = 0;
2139
2140 if(!(fde->state & FDE_DONT_CLOSE)) {
2141 dump_fde(fde, "close");
2142 adb_close(fde->fd);
2143 }
2144}
2145
2146static void fdevent_plist_enqueue(fdevent *node)
2147{
2148 fdevent *list = &list_pending;
2149
2150 node->next = list;
2151 node->prev = list->prev;
2152 node->prev->next = node;
2153 list->prev = node;
2154}
2155
2156static void fdevent_plist_remove(fdevent *node)
2157{
2158 node->prev->next = node->next;
2159 node->next->prev = node->prev;
2160 node->next = 0;
2161 node->prev = 0;
2162}
2163
2164static fdevent *fdevent_plist_dequeue(void)
2165{
2166 fdevent *list = &list_pending;
2167 fdevent *node = list->next;
2168
2169 if(node == list) return 0;
2170
2171 list->next = node->next;
2172 list->next->prev = list;
2173 node->next = 0;
2174 node->prev = 0;
2175
2176 return node;
2177}
2178
2179fdevent *fdevent_create(int fd, fd_func func, void *arg)
2180{
2181 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2182 if(fde == 0) return 0;
2183 fdevent_install(fde, fd, func, arg);
2184 fde->state |= FDE_CREATED;
2185 return fde;
2186}
2187
2188void fdevent_destroy(fdevent *fde)
2189{
2190 if(fde == 0) return;
2191 if(!(fde->state & FDE_CREATED)) {
2192 FATAL("fde %p not created by fdevent_create()\n", fde);
2193 }
2194 fdevent_remove(fde);
2195}
2196
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002197void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002198{
2199 memset(fde, 0, sizeof(fdevent));
2200 fde->state = FDE_ACTIVE;
2201 fde->fd = fd;
2202 fde->func = func;
2203 fde->arg = arg;
2204
2205 fdevent_register(fde);
2206 dump_fde(fde, "connect");
2207 fdevent_connect(fde);
2208 fde->state |= FDE_ACTIVE;
2209}
2210
2211void fdevent_remove(fdevent *fde)
2212{
2213 if(fde->state & FDE_PENDING) {
2214 fdevent_plist_remove(fde);
2215 }
2216
2217 if(fde->state & FDE_ACTIVE) {
2218 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002219 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002220 fdevent_unregister(fde);
2221 }
2222
2223 fde->state = 0;
2224 fde->events = 0;
2225}
2226
2227
2228void fdevent_set(fdevent *fde, unsigned events)
2229{
2230 events &= FDE_EVENTMASK;
2231
2232 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2233
2234 if(fde->state & FDE_ACTIVE) {
2235 fdevent_update(fde, events);
2236 dump_fde(fde, "update");
2237 }
2238
2239 fde->state = (fde->state & FDE_STATEMASK) | events;
2240
2241 if(fde->state & FDE_PENDING) {
2242 /* if we're pending, make sure
2243 ** we don't signal an event that
2244 ** is no longer wanted.
2245 */
2246 fde->events &= (~events);
2247 if(fde->events == 0) {
2248 fdevent_plist_remove(fde);
2249 fde->state &= (~FDE_PENDING);
2250 }
2251 }
2252}
2253
2254void fdevent_add(fdevent *fde, unsigned events)
2255{
2256 fdevent_set(
2257 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2258}
2259
2260void fdevent_del(fdevent *fde, unsigned events)
2261{
2262 fdevent_set(
2263 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2264}
2265
2266void fdevent_loop()
2267{
2268 fdevent *fde;
2269
2270 for(;;) {
2271#if DEBUG
2272 fprintf(stderr,"--- ---- waiting for events\n");
2273#endif
2274 fdevent_process();
2275
2276 while((fde = fdevent_plist_dequeue())) {
2277 unsigned events = fde->events;
2278 fde->events = 0;
2279 fde->state &= (~FDE_PENDING);
2280 dump_fde(fde, "callback");
2281 fde->func(fde->fd, events, fde->arg);
2282 }
2283 }
2284}
2285
2286/** FILE EVENT HOOKS
2287 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002288
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002289static void _event_file_prepare( EventHook hook )
2290{
2291 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2292 /* we can always read/write */
2293 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2294 }
2295}
2296
2297static int _event_file_peek( EventHook hook )
2298{
2299 return (hook->wanted & (FDE_READ|FDE_WRITE));
2300}
2301
2302static void _fh_file_hook( FH f, int events, EventHook hook )
2303{
2304 hook->h = f->fh_handle;
2305 hook->prepare = _event_file_prepare;
2306 hook->peek = _event_file_peek;
2307}
2308
2309/** SOCKET EVENT HOOKS
2310 **/
2311
2312static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2313{
2314 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2315 if (hook->wanted & FDE_READ)
2316 hook->ready |= FDE_READ;
2317 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2318 hook->ready |= FDE_ERROR;
2319 }
2320 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2321 if (hook->wanted & FDE_WRITE)
2322 hook->ready |= FDE_WRITE;
2323 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2324 hook->ready |= FDE_ERROR;
2325 }
2326 if ( evts->lNetworkEvents & FD_OOB ) {
2327 if (hook->wanted & FDE_ERROR)
2328 hook->ready |= FDE_ERROR;
2329 }
2330}
2331
2332static void _event_socket_prepare( EventHook hook )
2333{
2334 WSANETWORKEVENTS evts;
2335
2336 /* look if some of the events we want already happened ? */
2337 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2338 _event_socket_verify( hook, &evts );
2339}
2340
2341static int _socket_wanted_to_flags( int wanted )
2342{
2343 int flags = 0;
2344 if (wanted & FDE_READ)
2345 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2346
2347 if (wanted & FDE_WRITE)
2348 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2349
2350 if (wanted & FDE_ERROR)
2351 flags |= FD_OOB;
2352
2353 return flags;
2354}
2355
2356static int _event_socket_start( EventHook hook )
2357{
2358 /* create an event which we're going to wait for */
2359 FH fh = hook->fh;
2360 long flags = _socket_wanted_to_flags( hook->wanted );
2361
2362 hook->h = fh->event;
2363 if (hook->h == INVALID_HANDLE_VALUE) {
Yabin Cui815ad882015-09-02 17:44:28 -07002364 D( "_event_socket_start: no event for %s", fh->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002365 return 0;
2366 }
2367
2368 if ( flags != fh->mask ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002369 D( "_event_socket_start: hooking %s for %x (flags %ld)", hook->fh->name, hook->wanted, flags );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002370 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002371 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d", hook->fh->name, WSAGetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002372 CloseHandle( hook->h );
2373 hook->h = INVALID_HANDLE_VALUE;
2374 exit(1);
2375 return 0;
2376 }
2377 fh->mask = flags;
2378 }
2379 return 1;
2380}
2381
2382static void _event_socket_stop( EventHook hook )
2383{
2384 hook->h = INVALID_HANDLE_VALUE;
2385}
2386
2387static int _event_socket_check( EventHook hook )
2388{
2389 int result = 0;
2390 FH fh = hook->fh;
2391 WSANETWORKEVENTS evts;
2392
2393 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2394 _event_socket_verify( hook, &evts );
2395 result = (hook->ready != 0);
2396 if (result) {
2397 ResetEvent( hook->h );
2398 }
2399 }
Yabin Cui815ad882015-09-02 17:44:28 -07002400 D( "_event_socket_check %s returns %d", fh->name, result );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002401 return result;
2402}
2403
2404static int _event_socket_peek( EventHook hook )
2405{
2406 WSANETWORKEVENTS evts;
2407 FH fh = hook->fh;
2408
2409 /* look if some of the events we want already happened ? */
2410 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2411 _event_socket_verify( hook, &evts );
2412 if (hook->ready)
2413 ResetEvent( hook->h );
2414 }
2415
2416 return hook->ready != 0;
2417}
2418
2419
2420
2421static void _fh_socket_hook( FH f, int events, EventHook hook )
2422{
2423 hook->prepare = _event_socket_prepare;
2424 hook->start = _event_socket_start;
2425 hook->stop = _event_socket_stop;
2426 hook->check = _event_socket_check;
2427 hook->peek = _event_socket_peek;
2428
Spencer Low753d4852015-07-30 23:07:55 -07002429 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002430 _event_socket_start( hook );
2431}
2432
2433/** SOCKETPAIR EVENT HOOKS
2434 **/
2435
2436static void _event_socketpair_prepare( EventHook hook )
2437{
2438 FH fh = hook->fh;
2439 SocketPair pair = fh->fh_pair;
2440 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2441 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2442
2443 if (hook->wanted & FDE_READ && rbip->can_read)
2444 hook->ready |= FDE_READ;
2445
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002446 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002447 hook->ready |= FDE_WRITE;
2448 }
2449
2450 static int _event_socketpair_start( EventHook hook )
2451 {
2452 FH fh = hook->fh;
2453 SocketPair pair = fh->fh_pair;
2454 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2455 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2456
2457 if (hook->wanted == FDE_READ)
2458 hook->h = rbip->evt_read;
2459
2460 else if (hook->wanted == FDE_WRITE)
2461 hook->h = wbip->evt_write;
2462
2463 else {
Yabin Cui815ad882015-09-02 17:44:28 -07002464 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002465 return 0;
2466 }
Yabin Cui815ad882015-09-02 17:44:28 -07002467 D( "_event_socketpair_start: hook %s for %x wanted=%x",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002468 hook->fh->name, _fh_to_int(fh), hook->wanted);
2469 return 1;
2470}
2471
2472static int _event_socketpair_peek( EventHook hook )
2473{
2474 _event_socketpair_prepare( hook );
2475 return hook->ready != 0;
2476}
2477
2478static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2479{
2480 hook->prepare = _event_socketpair_prepare;
2481 hook->start = _event_socketpair_start;
2482 hook->peek = _event_socketpair_peek;
2483}
2484
2485
Spencer Lowf373c352015-11-15 16:29:36 -08002486static adb_mutex_t g_console_output_buffer_lock;
2487
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002488void
2489adb_sysdeps_init( void )
2490{
2491#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2492#include "mutex_list.h"
2493 InitializeCriticalSection( &_win32_lock );
Spencer Lowf373c352015-11-15 16:29:36 -08002494 InitializeCriticalSection( &g_console_output_buffer_lock );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002495}
2496
Spencer Lowbeb61982015-03-01 15:06:21 -08002497/**************************************************************************/
2498/**************************************************************************/
2499/***** *****/
2500/***** Console Window Terminal Emulation *****/
2501/***** *****/
2502/**************************************************************************/
2503/**************************************************************************/
2504
2505// This reads input from a Win32 console window and translates it into Unix
2506// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2507// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2508// is emulated instead of xterm because it is probably more popular than xterm:
2509// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2510// supports modern fonts, etc. It seems best to emulate the terminal that most
2511// Android developers use because they'll fix apps (the shell, etc.) to keep
2512// working with that terminal's emulation.
2513//
2514// The point of this emulation is not to be perfect or to solve all issues with
2515// console windows on Windows, but to be better than the original code which
2516// just called read() (which called ReadFile(), which called ReadConsoleA())
2517// which did not support Ctrl-C, tab completion, shell input line editing
2518// keys, server echo, and more.
2519//
2520// This implementation reconfigures the console with SetConsoleMode(), then
2521// calls ReadConsoleInput() to get raw input which it remaps to Unix
2522// terminal-style sequences which is returned via unix_read() which is used
2523// by the 'adb shell' command.
2524//
2525// Code organization:
2526//
David Pursell58805362015-10-28 14:29:51 -07002527// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08002528// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2529// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2530// * _console_read() is the main code of the emulation.
2531
David Pursell58805362015-10-28 14:29:51 -07002532// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
2533// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
2534// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
2535static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
2536 // First check isatty(); this is very fast and eliminates most non-console
2537 // FDs, but returns 1 for both consoles and character devices like NUL.
2538#pragma push_macro("isatty")
2539#undef isatty
2540 if (!isatty(fd)) {
2541 return nullptr;
2542 }
2543#pragma pop_macro("isatty")
2544
2545 // To differentiate between character devices and consoles we need to get
2546 // the underlying HANDLE and use GetConsoleMode(), which is what requires
2547 // GENERIC_READ permissions.
2548 const intptr_t intptr_handle = _get_osfhandle(fd);
2549 if (intptr_handle == -1) {
2550 return nullptr;
2551 }
2552 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
2553 DWORD temp_mode = 0;
2554 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
2555 return nullptr;
2556 }
2557
2558 return handle;
2559}
2560
2561// Returns a console handle if |stream| is a console, otherwise returns nullptr.
2562static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08002563 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
2564 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07002565 const int fd = fileno(stream);
2566 if (fd < 0) {
2567 return nullptr;
2568 }
2569 return _get_console_handle(fd);
2570}
2571
2572int unix_isatty(int fd) {
2573 return _get_console_handle(fd) ? 1 : 0;
2574}
Spencer Lowbeb61982015-03-01 15:06:21 -08002575
Spencer Low9c8f7462015-11-10 19:17:16 -08002576// Get the next KEY_EVENT_RECORD that should be processed.
2577static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002578 for (;;) {
2579 DWORD read_count = 0;
2580 memset(input_record, 0, sizeof(*input_record));
2581 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08002582 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
2583 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002584 errno = EIO;
2585 return false;
2586 }
2587
2588 if (read_count == 0) { // should be impossible
2589 fatal("ReadConsoleInputA returned 0");
2590 }
2591
2592 if (read_count != 1) { // should be impossible
2593 fatal("ReadConsoleInputA did not return one input record");
2594 }
2595
2596 if ((input_record->EventType == KEY_EVENT) &&
2597 (input_record->Event.KeyEvent.bKeyDown)) {
2598 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2599 fatal("ReadConsoleInputA returned a key event with zero repeat"
2600 " count");
2601 }
2602
2603 // Got an interesting INPUT_RECORD, so return
2604 return true;
2605 }
2606 }
2607}
2608
Spencer Lowbeb61982015-03-01 15:06:21 -08002609static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2610 return (control_key_state & SHIFT_PRESSED) != 0;
2611}
2612
2613static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2614 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2615}
2616
2617static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2618 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2619}
2620
2621static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2622 return (control_key_state & NUMLOCK_ON) != 0;
2623}
2624
2625static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2626 return (control_key_state & CAPSLOCK_ON) != 0;
2627}
2628
2629static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2630 return (control_key_state & ENHANCED_KEY) != 0;
2631}
2632
2633// Constants from MSDN for ToAscii().
2634static const BYTE TOASCII_KEY_OFF = 0x00;
2635static const BYTE TOASCII_KEY_DOWN = 0x80;
2636static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2637
2638// Given a key event, ignore a modifier key and return the character that was
2639// entered without the modifier. Writes to *ch and returns the number of bytes
2640// written.
2641static size_t _get_char_ignoring_modifier(char* const ch,
2642 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2643 const WORD modifier) {
2644 // If there is no character from Windows, try ignoring the specified
2645 // modifier and look for a character. Note that if AltGr is being used,
2646 // there will be a character from Windows.
2647 if (key_event->uChar.AsciiChar == '\0') {
2648 // Note that we read the control key state from the passed in argument
2649 // instead of from key_event since the argument has been normalized.
2650 if (((modifier == VK_SHIFT) &&
2651 _is_shift_pressed(control_key_state)) ||
2652 ((modifier == VK_CONTROL) &&
2653 _is_ctrl_pressed(control_key_state)) ||
2654 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2655
2656 BYTE key_state[256] = {0};
2657 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2658 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2659 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2660 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2661 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2662 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2663 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2664 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2665
2666 // cause this modifier to be ignored
2667 key_state[modifier] = TOASCII_KEY_OFF;
2668
2669 WORD translated = 0;
2670 if (ToAscii(key_event->wVirtualKeyCode,
2671 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2672 // Ignoring the modifier, we found a character.
2673 *ch = (CHAR)translated;
2674 return 1;
2675 }
2676 }
2677 }
2678
2679 // Just use whatever Windows told us originally.
2680 *ch = key_event->uChar.AsciiChar;
2681
2682 // If the character from Windows is NULL, return a size of zero.
2683 return (*ch == '\0') ? 0 : 1;
2684}
2685
2686// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2687// but taking into account the shift key. This is because for a sequence like
2688// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2689// we want to find the character ')'.
2690//
2691// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2692// because it is the default key-sequence to switch the input language.
2693// This is configurable in the Region and Language control panel.
2694static __inline__ size_t _get_non_control_char(char* const ch,
2695 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2696 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2697 VK_CONTROL);
2698}
2699
2700// Get without Alt.
2701static __inline__ size_t _get_non_alt_char(char* const ch,
2702 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2703 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2704 VK_MENU);
2705}
2706
2707// Ignore the control key, find the character from Windows, and apply any
2708// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2709// *pch and returns number of bytes written.
2710static size_t _get_control_character(char* const pch,
2711 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2712 const size_t len = _get_non_control_char(pch, key_event,
2713 control_key_state);
2714
2715 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2716 char ch = *pch;
2717 switch (ch) {
2718 case '2':
2719 case '@':
2720 case '`':
2721 ch = '\0';
2722 break;
2723 case '3':
2724 case '[':
2725 case '{':
2726 ch = '\x1b';
2727 break;
2728 case '4':
2729 case '\\':
2730 case '|':
2731 ch = '\x1c';
2732 break;
2733 case '5':
2734 case ']':
2735 case '}':
2736 ch = '\x1d';
2737 break;
2738 case '6':
2739 case '^':
2740 case '~':
2741 ch = '\x1e';
2742 break;
2743 case '7':
2744 case '-':
2745 case '_':
2746 ch = '\x1f';
2747 break;
2748 case '8':
2749 ch = '\x7f';
2750 break;
2751 case '/':
2752 if (!_is_alt_pressed(control_key_state)) {
2753 ch = '\x1f';
2754 }
2755 break;
2756 case '?':
2757 if (!_is_alt_pressed(control_key_state)) {
2758 ch = '\x7f';
2759 }
2760 break;
2761 }
2762 *pch = ch;
2763 }
2764
2765 return len;
2766}
2767
2768static DWORD _normalize_altgr_control_key_state(
2769 const KEY_EVENT_RECORD* const key_event) {
2770 DWORD control_key_state = key_event->dwControlKeyState;
2771
2772 // If we're in an AltGr situation where the AltGr key is down (depending on
2773 // the keyboard layout, that might be the physical right alt key which
2774 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2775 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2776 // a character (which indicates that there was an AltGr mapping), then act
2777 // as if alt and control are not really down for the purposes of modifiers.
2778 // This makes it so that if the user with, say, a German keyboard layout
2779 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2780 // output the key and we don't see the Alt and Ctrl keys.
2781 if (_is_ctrl_pressed(control_key_state) &&
2782 _is_alt_pressed(control_key_state)
2783 && (key_event->uChar.AsciiChar != '\0')) {
2784 // Try to remove as few bits as possible to improve our chances of
2785 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2786 // Left-Alt + Right-Ctrl + AltGr.
2787 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2788 // Remove Right-Alt.
2789 control_key_state &= ~RIGHT_ALT_PRESSED;
2790 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2791 // pressed, Left-Ctrl is almost always set, except if the user
2792 // presses Right-Ctrl, then AltGr (in that specific order) for
2793 // whatever reason. At any rate, make sure the bit is not set.
2794 control_key_state &= ~LEFT_CTRL_PRESSED;
2795 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2796 // Remove Left-Alt.
2797 control_key_state &= ~LEFT_ALT_PRESSED;
2798 // Whichever Ctrl key is down, remove it from the state. We only
2799 // remove one key, to improve our chances of detecting the
2800 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2801 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2802 // Remove Left-Ctrl.
2803 control_key_state &= ~LEFT_CTRL_PRESSED;
2804 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2805 // Remove Right-Ctrl.
2806 control_key_state &= ~RIGHT_CTRL_PRESSED;
2807 }
2808 }
2809
2810 // Note that this logic isn't 100% perfect because Windows doesn't
2811 // allow us to detect all combinations because a physical AltGr key
2812 // press shows up as two bits, plus some combinations are ambiguous
2813 // about what is actually physically pressed.
2814 }
2815
2816 return control_key_state;
2817}
2818
2819// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2820// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2821// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2822// appropriately.
2823static DWORD _normalize_keypad_control_key_state(const WORD vk,
2824 const DWORD control_key_state) {
2825 if (!_is_numlock_on(control_key_state)) {
2826 return control_key_state;
2827 }
2828 if (!_is_enhanced_key(control_key_state)) {
2829 switch (vk) {
2830 case VK_INSERT: // 0
2831 case VK_DELETE: // .
2832 case VK_END: // 1
2833 case VK_DOWN: // 2
2834 case VK_NEXT: // 3
2835 case VK_LEFT: // 4
2836 case VK_CLEAR: // 5
2837 case VK_RIGHT: // 6
2838 case VK_HOME: // 7
2839 case VK_UP: // 8
2840 case VK_PRIOR: // 9
2841 return control_key_state | SHIFT_PRESSED;
2842 }
2843 }
2844
2845 return control_key_state;
2846}
2847
2848static const char* _get_keypad_sequence(const DWORD control_key_state,
2849 const char* const normal, const char* const shifted) {
2850 if (_is_shift_pressed(control_key_state)) {
2851 // Shift is pressed and NumLock is off
2852 return shifted;
2853 } else {
2854 // Shift is not pressed and NumLock is off, or,
2855 // Shift is pressed and NumLock is on, in which case we want the
2856 // NumLock and Shift to neutralize each other, thus, we want the normal
2857 // sequence.
2858 return normal;
2859 }
2860 // If Shift is not pressed and NumLock is on, a different virtual key code
2861 // is returned by Windows, which can be taken care of by a different case
2862 // statement in _console_read().
2863}
2864
2865// Write sequence to buf and return the number of bytes written.
2866static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2867 DWORD control_key_state, const char* const normal) {
2868 // Copy the base sequence into buf.
2869 const size_t len = strlen(normal);
2870 memcpy(buf, normal, len);
2871
2872 int code = 0;
2873
2874 control_key_state = _normalize_keypad_control_key_state(vk,
2875 control_key_state);
2876
2877 if (_is_shift_pressed(control_key_state)) {
2878 code |= 0x1;
2879 }
2880 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2881 code |= 0x2;
2882 }
2883 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2884 code |= 0x4;
2885 }
2886 // If some modifier was held down, then we need to insert the modifier code
2887 if (code != 0) {
2888 if (len == 0) {
2889 // Should be impossible because caller should pass a string of
2890 // non-zero length.
2891 return 0;
2892 }
2893 size_t index = len - 1;
2894 const char lastChar = buf[index];
2895 if (lastChar != '~') {
2896 buf[index++] = '1';
2897 }
2898 buf[index++] = ';'; // modifier separator
2899 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2900 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2901 buf[index++] = '1' + code;
2902 buf[index++] = lastChar; // move ~ (or other last char) to the end
2903 return index;
2904 }
2905 return len;
2906}
2907
2908// Write sequence to buf and return the number of bytes written.
2909static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2910 const DWORD control_key_state, const char* const normal,
2911 const char shifted) {
2912 if (_is_shift_pressed(control_key_state)) {
2913 // Shift is pressed and NumLock is off
2914 if (shifted != '\0') {
2915 buf[0] = shifted;
2916 return sizeof(buf[0]);
2917 } else {
2918 return 0;
2919 }
2920 } else {
2921 // Shift is not pressed and NumLock is off, or,
2922 // Shift is pressed and NumLock is on, in which case we want the
2923 // NumLock and Shift to neutralize each other, thus, we want the normal
2924 // sequence.
2925 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2926 }
2927 // If Shift is not pressed and NumLock is on, a different virtual key code
2928 // is returned by Windows, which can be taken care of by a different case
2929 // statement in _console_read().
2930}
2931
2932// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2933// Standard German. Figure this out at runtime so we know what to output for
2934// Shift-VK_DELETE.
2935static char _get_decimal_char() {
2936 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2937}
2938
2939// Prefix the len bytes in buf with the escape character, and then return the
2940// new buffer length.
2941size_t _escape_prefix(char* const buf, const size_t len) {
2942 // If nothing to prefix, don't do anything. We might be called with
2943 // len == 0, if alt was held down with a dead key which produced nothing.
2944 if (len == 0) {
2945 return 0;
2946 }
2947
2948 memmove(&buf[1], buf, len);
2949 buf[0] = '\x1b';
2950 return len + 1;
2951}
2952
Spencer Low9c8f7462015-11-10 19:17:16 -08002953// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002954static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08002955
2956// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
2957// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08002958static int _console_read(const HANDLE console, void* buf, size_t len) {
2959 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08002960 // Read of zero bytes should not block waiting for something from the console.
2961 if (len == 0) {
2962 return 0;
2963 }
2964
2965 // Flush as much as possible from input buffer.
2966 if (!g_console_input_buffer.empty()) {
2967 const int bytes_read = std::min(len, g_console_input_buffer.size());
2968 memcpy(buf, g_console_input_buffer.data(), bytes_read);
2969 const auto begin = g_console_input_buffer.begin();
2970 g_console_input_buffer.erase(begin, begin + bytes_read);
2971 return bytes_read;
2972 }
2973
2974 // Read from the actual console. This may block until input.
2975 INPUT_RECORD input_record;
2976 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002977 return -1;
2978 }
2979
Spencer Low9c8f7462015-11-10 19:17:16 -08002980 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08002981 const WORD vk = key_event->wVirtualKeyCode;
2982 const CHAR ch = key_event->uChar.AsciiChar;
2983 const DWORD control_key_state = _normalize_altgr_control_key_state(
2984 key_event);
2985
2986 // The following emulation code should write the output sequence to
2987 // either seqstr or to seqbuf and seqbuflen.
2988 const char* seqstr = NULL; // NULL terminated C-string
2989 // Enough space for max sequence string below, plus modifiers and/or
2990 // escape prefix.
2991 char seqbuf[16];
2992 size_t seqbuflen = 0; // Space used in seqbuf.
2993
2994#define MATCH(vk, normal) \
2995 case (vk): \
2996 { \
2997 seqstr = (normal); \
2998 } \
2999 break;
3000
3001 // Modifier keys should affect the output sequence.
3002#define MATCH_MODIFIER(vk, normal) \
3003 case (vk): \
3004 { \
3005 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
3006 control_key_state, (normal)); \
3007 } \
3008 break;
3009
3010 // The shift key should affect the output sequence.
3011#define MATCH_KEYPAD(vk, normal, shifted) \
3012 case (vk): \
3013 { \
3014 seqstr = _get_keypad_sequence(control_key_state, (normal), \
3015 (shifted)); \
3016 } \
3017 break;
3018
3019 // The shift key and other modifier keys should affect the output
3020 // sequence.
3021#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
3022 case (vk): \
3023 { \
3024 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
3025 control_key_state, (normal), (shifted)); \
3026 } \
3027 break;
3028
3029#define ESC "\x1b"
3030#define CSI ESC "["
3031#define SS3 ESC "O"
3032
3033 // Only support normal mode, not application mode.
3034
3035 // Enhanced keys:
3036 // * 6-pack: insert, delete, home, end, page up, page down
3037 // * cursor keys: up, down, right, left
3038 // * keypad: divide, enter
3039 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
3040 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
3041 if (_is_enhanced_key(control_key_state)) {
3042 switch (vk) {
3043 case VK_RETURN: // Enter key on keypad
3044 if (_is_ctrl_pressed(control_key_state)) {
3045 seqstr = "\n";
3046 } else {
3047 seqstr = "\r";
3048 }
3049 break;
3050
3051 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
3052 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
3053
3054 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
3055 // will be fixed soon to match xterm which sends CSI "F" and
3056 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
3057 MATCH(VK_END, CSI "F");
3058 MATCH(VK_HOME, CSI "H");
3059
3060 MATCH_MODIFIER(VK_LEFT, CSI "D");
3061 MATCH_MODIFIER(VK_UP, CSI "A");
3062 MATCH_MODIFIER(VK_RIGHT, CSI "C");
3063 MATCH_MODIFIER(VK_DOWN, CSI "B");
3064
3065 MATCH_MODIFIER(VK_INSERT, CSI "2~");
3066 MATCH_MODIFIER(VK_DELETE, CSI "3~");
3067
3068 MATCH(VK_DIVIDE, "/");
3069 }
3070 } else { // Non-enhanced keys:
3071 switch (vk) {
3072 case VK_BACK: // backspace
3073 if (_is_alt_pressed(control_key_state)) {
3074 seqstr = ESC "\x7f";
3075 } else {
3076 seqstr = "\x7f";
3077 }
3078 break;
3079
3080 case VK_TAB:
3081 if (_is_shift_pressed(control_key_state)) {
3082 seqstr = CSI "Z";
3083 } else {
3084 seqstr = "\t";
3085 }
3086 break;
3087
3088 // Number 5 key in keypad when NumLock is off, or if NumLock is
3089 // on and Shift is down.
3090 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
3091
3092 case VK_RETURN: // Enter key on main keyboard
3093 if (_is_alt_pressed(control_key_state)) {
3094 seqstr = ESC "\n";
3095 } else if (_is_ctrl_pressed(control_key_state)) {
3096 seqstr = "\n";
3097 } else {
3098 seqstr = "\r";
3099 }
3100 break;
3101
3102 // VK_ESCAPE: Don't do any special handling. The OS uses many
3103 // of the sequences with Escape and many of the remaining
3104 // sequences don't produce bKeyDown messages, only !bKeyDown
3105 // for whatever reason.
3106
3107 case VK_SPACE:
3108 if (_is_alt_pressed(control_key_state)) {
3109 seqstr = ESC " ";
3110 } else if (_is_ctrl_pressed(control_key_state)) {
3111 seqbuf[0] = '\0'; // NULL char
3112 seqbuflen = 1;
3113 } else {
3114 seqstr = " ";
3115 }
3116 break;
3117
3118 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
3119 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
3120
3121 MATCH_KEYPAD(VK_END, CSI "4~", "1");
3122 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
3123
3124 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
3125 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
3126 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
3127 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
3128
3129 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
3130 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
3131 _get_decimal_char());
3132
3133 case 0x30: // 0
3134 case 0x31: // 1
3135 case 0x39: // 9
3136 case VK_OEM_1: // ;:
3137 case VK_OEM_PLUS: // =+
3138 case VK_OEM_COMMA: // ,<
3139 case VK_OEM_PERIOD: // .>
3140 case VK_OEM_7: // '"
3141 case VK_OEM_102: // depends on keyboard, could be <> or \|
3142 case VK_OEM_2: // /?
3143 case VK_OEM_3: // `~
3144 case VK_OEM_4: // [{
3145 case VK_OEM_5: // \|
3146 case VK_OEM_6: // ]}
3147 {
3148 seqbuflen = _get_control_character(seqbuf, key_event,
3149 control_key_state);
3150
3151 if (_is_alt_pressed(control_key_state)) {
3152 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3153 }
3154 }
3155 break;
3156
3157 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08003158 case 0x33: // 3
3159 case 0x34: // 4
3160 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08003161 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08003162 case 0x37: // 7
3163 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08003164 case VK_OEM_MINUS: // -_
3165 {
3166 seqbuflen = _get_control_character(seqbuf, key_event,
3167 control_key_state);
3168
3169 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3170 // prefix with escape.
3171 if (_is_alt_pressed(control_key_state) &&
3172 !(_is_ctrl_pressed(control_key_state) &&
3173 !_is_shift_pressed(control_key_state))) {
3174 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3175 }
3176 }
3177 break;
3178
Spencer Lowbeb61982015-03-01 15:06:21 -08003179 case 0x41: // a
3180 case 0x42: // b
3181 case 0x43: // c
3182 case 0x44: // d
3183 case 0x45: // e
3184 case 0x46: // f
3185 case 0x47: // g
3186 case 0x48: // h
3187 case 0x49: // i
3188 case 0x4a: // j
3189 case 0x4b: // k
3190 case 0x4c: // l
3191 case 0x4d: // m
3192 case 0x4e: // n
3193 case 0x4f: // o
3194 case 0x50: // p
3195 case 0x51: // q
3196 case 0x52: // r
3197 case 0x53: // s
3198 case 0x54: // t
3199 case 0x55: // u
3200 case 0x56: // v
3201 case 0x57: // w
3202 case 0x58: // x
3203 case 0x59: // y
3204 case 0x5a: // z
3205 {
3206 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3207 control_key_state);
3208
3209 // If Alt is pressed, then prefix with escape.
3210 if (_is_alt_pressed(control_key_state)) {
3211 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3212 }
3213 }
3214 break;
3215
3216 // These virtual key codes are generated by the keys on the
3217 // keypad *when NumLock is on* and *Shift is up*.
3218 MATCH(VK_NUMPAD0, "0");
3219 MATCH(VK_NUMPAD1, "1");
3220 MATCH(VK_NUMPAD2, "2");
3221 MATCH(VK_NUMPAD3, "3");
3222 MATCH(VK_NUMPAD4, "4");
3223 MATCH(VK_NUMPAD5, "5");
3224 MATCH(VK_NUMPAD6, "6");
3225 MATCH(VK_NUMPAD7, "7");
3226 MATCH(VK_NUMPAD8, "8");
3227 MATCH(VK_NUMPAD9, "9");
3228
3229 MATCH(VK_MULTIPLY, "*");
3230 MATCH(VK_ADD, "+");
3231 MATCH(VK_SUBTRACT, "-");
3232 // VK_DECIMAL is generated by the . key on the keypad *when
3233 // NumLock is on* and *Shift is up* and the sequence is not
3234 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3235 // Windows Security screen to come up).
3236 case VK_DECIMAL:
3237 // U.S. English uses '.', Germany German uses ','.
3238 seqbuflen = _get_non_control_char(seqbuf, key_event,
3239 control_key_state);
3240 break;
3241
3242 MATCH_MODIFIER(VK_F1, SS3 "P");
3243 MATCH_MODIFIER(VK_F2, SS3 "Q");
3244 MATCH_MODIFIER(VK_F3, SS3 "R");
3245 MATCH_MODIFIER(VK_F4, SS3 "S");
3246 MATCH_MODIFIER(VK_F5, CSI "15~");
3247 MATCH_MODIFIER(VK_F6, CSI "17~");
3248 MATCH_MODIFIER(VK_F7, CSI "18~");
3249 MATCH_MODIFIER(VK_F8, CSI "19~");
3250 MATCH_MODIFIER(VK_F9, CSI "20~");
3251 MATCH_MODIFIER(VK_F10, CSI "21~");
3252 MATCH_MODIFIER(VK_F11, CSI "23~");
3253 MATCH_MODIFIER(VK_F12, CSI "24~");
3254
3255 MATCH_MODIFIER(VK_F13, CSI "25~");
3256 MATCH_MODIFIER(VK_F14, CSI "26~");
3257 MATCH_MODIFIER(VK_F15, CSI "28~");
3258 MATCH_MODIFIER(VK_F16, CSI "29~");
3259 MATCH_MODIFIER(VK_F17, CSI "31~");
3260 MATCH_MODIFIER(VK_F18, CSI "32~");
3261 MATCH_MODIFIER(VK_F19, CSI "33~");
3262 MATCH_MODIFIER(VK_F20, CSI "34~");
3263
3264 // MATCH_MODIFIER(VK_F21, ???);
3265 // MATCH_MODIFIER(VK_F22, ???);
3266 // MATCH_MODIFIER(VK_F23, ???);
3267 // MATCH_MODIFIER(VK_F24, ???);
3268 }
3269 }
3270
3271#undef MATCH
3272#undef MATCH_MODIFIER
3273#undef MATCH_KEYPAD
3274#undef MATCH_MODIFIER_KEYPAD
3275#undef ESC
3276#undef CSI
3277#undef SS3
3278
3279 const char* out;
3280 size_t outlen;
3281
3282 // Check for output in any of:
3283 // * seqstr is set (and strlen can be used to determine the length).
3284 // * seqbuf and seqbuflen are set
3285 // Fallback to ch from Windows.
3286 if (seqstr != NULL) {
3287 out = seqstr;
3288 outlen = strlen(seqstr);
3289 } else if (seqbuflen > 0) {
3290 out = seqbuf;
3291 outlen = seqbuflen;
3292 } else if (ch != '\0') {
3293 // Use whatever Windows told us it is.
3294 seqbuf[0] = ch;
3295 seqbuflen = 1;
3296 out = seqbuf;
3297 outlen = seqbuflen;
3298 } else {
3299 // No special handling for the virtual key code and Windows isn't
3300 // telling us a character code, then we don't know how to translate
3301 // the key press.
3302 //
3303 // Consume the input and 'continue' to cause us to get a new key
3304 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07003305 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08003306 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08003307 continue;
3308 }
3309
Spencer Low9c8f7462015-11-10 19:17:16 -08003310 // put output wRepeatCount times into g_console_input_buffer
3311 while (key_event->wRepeatCount-- > 0) {
3312 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08003313 }
3314
Spencer Low9c8f7462015-11-10 19:17:16 -08003315 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08003316 }
3317}
3318
3319static DWORD _old_console_mode; // previous GetConsoleMode() result
3320static HANDLE _console_handle; // when set, console mode should be restored
3321
Elliott Hughesa8265792015-11-03 11:18:40 -08003322void stdin_raw_init() {
3323 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08003324 if (in == nullptr) {
3325 return;
3326 }
Spencer Lowbeb61982015-03-01 15:06:21 -08003327
Elliott Hughesa8265792015-11-03 11:18:40 -08003328 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3329 // calling the process Ctrl-C routine (configured by
3330 // SetConsoleCtrlHandler()).
3331 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3332 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3333 // flag also seems necessary to have proper line-ending processing.
3334 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3335 ENABLE_LINE_INPUT |
3336 ENABLE_ECHO_INPUT))) {
3337 // This really should not fail.
3338 D("stdin_raw_init: SetConsoleMode() failed: %s",
3339 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003340 }
Elliott Hughesa8265792015-11-03 11:18:40 -08003341
3342 // Once this is set, it means that stdin has been configured for
3343 // reading from and that the old console mode should be restored later.
3344 _console_handle = in;
3345
3346 // Note that we don't need to configure C Runtime line-ending
3347 // translation because _console_read() does not call the C Runtime to
3348 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08003349}
3350
Elliott Hughesa8265792015-11-03 11:18:40 -08003351void stdin_raw_restore() {
3352 if (_console_handle != NULL) {
3353 const HANDLE in = _console_handle;
3354 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08003355
Elliott Hughesa8265792015-11-03 11:18:40 -08003356 if (!SetConsoleMode(in, _old_console_mode)) {
3357 // This really should not fail.
3358 D("stdin_raw_restore: SetConsoleMode() failed: %s",
3359 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003360 }
3361 }
3362}
3363
Spencer Low3a2421b2015-05-22 20:09:06 -07003364// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003365int unix_read(int fd, void* buf, size_t len) {
3366 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3367 // If it is a request to read from stdin, and stdin_raw_init() has been
3368 // called, and it successfully configured the console, then read from
3369 // the console using Win32 console APIs and partially emulate a unix
3370 // terminal.
3371 return _console_read(_console_handle, buf, len);
3372 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07003373 // On older versions of Windows (definitely 7, definitely not 10),
3374 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07003375 // we need to limit the read size.
3376 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07003377 len = 4096;
3378 }
Spencer Lowbeb61982015-03-01 15:06:21 -08003379 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003380 // can do LF/CR translation (which is overridable with _setmode()).
3381 // Undefine the macro that is set in sysdeps.h which bans calls to
3382 // plain read() in favor of unix_read() or adb_read().
3383#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003384#undef read
3385 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003386#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003387 }
3388}
Spencer Low6815c072015-05-11 01:08:48 -07003389
3390/**************************************************************************/
3391/**************************************************************************/
3392/***** *****/
3393/***** Unicode support *****/
3394/***** *****/
3395/**************************************************************************/
3396/**************************************************************************/
3397
3398// This implements support for using files with Unicode filenames and for
3399// outputting Unicode text to a Win32 console window. This is inspired from
3400// http://utf8everywhere.org/.
3401//
3402// Background
3403// ----------
3404//
3405// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3406// filenames to APIs such as open(). This works because filenames are largely
3407// opaque 'cookies' (perhaps excluding path separators).
3408//
3409// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3410// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3411// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3412// CreateFile() API is really just a macro that adds the W/A based on whether
3413// the UNICODE preprocessor symbol is defined).
3414//
3415// Options
3416// -------
3417//
3418// Thus, to write a portable program, there are a few options:
3419//
3420// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3421// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3422// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3423// open() API.
3424//
3425// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3426// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3427// potentially touching a lot of code.
3428//
3429// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3430// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3431// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3432// or C Runtime API.
3433//
3434// The Choice
3435// ----------
3436//
Spencer Low50f5bf12015-11-12 15:20:15 -08003437// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
3438// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07003439// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08003440// args that are passed to main() at the beginning of program startup. We also use
3441// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07003442// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3443//
3444// Unicode console output
3445// ----------------------
3446//
3447// The way to output Unicode to a Win32 console window is to call
3448// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003449// such as Lucida Console or Consolas, and in the case of East Asian languages
3450// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3451// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3452// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003453//
3454// The problem is getting the C Runtime to make fprintf and related APIs call
3455// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3456// promising, but the various modes have issues:
3457//
3458// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3459// UTF-16 do not display properly.
3460// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3461// totally wrong.
3462// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3463// handler to be called (upon a later I/O call), aborting the process.
3464// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3465// to output nothing.
3466//
3467// So the only solution is to write our own adb_fprintf() that converts UTF-8
3468// to UTF-16 and then calls WriteConsoleW().
3469
3470
Spencer Low6815c072015-05-11 01:08:48 -07003471// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3472// be passed to main().
3473NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3474 narrow_args = new char*[argc + 1];
3475
3476 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003477 std::string arg_narrow;
3478 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
3479 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
3480 }
3481 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003482 }
3483 narrow_args[argc] = nullptr; // terminate
3484}
3485
3486NarrowArgs::~NarrowArgs() {
3487 if (narrow_args != nullptr) {
3488 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3489 free(*argp);
3490 }
3491 delete[] narrow_args;
3492 narrow_args = nullptr;
3493 }
3494}
3495
3496int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003497 std::wstring path_wide;
3498 if (!android::base::UTF8ToWide(path, &path_wide)) {
3499 return -1;
3500 }
Spencer Low6815c072015-05-11 01:08:48 -07003501 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003502 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07003503 } else {
3504 int mode;
3505 va_list args;
3506 va_start(args, options);
3507 mode = va_arg(args, int);
3508 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08003509 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07003510 }
3511}
3512
3513// Version of stat() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08003514int adb_stat(const char* path, struct adb_stat* s) {
Spencer Low6815c072015-05-11 01:08:48 -07003515#pragma push_macro("wstat")
3516// This definition of wstat seems to be missing from <sys/stat.h>.
3517#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3518#ifdef _USE_32BIT_TIME_T
3519#define wstat _wstat32i64
3520#else
3521#define wstat _wstat64
3522#endif
3523#else
3524// <sys/stat.h> has a function prototype for wstat() that should be available.
3525#endif
3526
Spencer Low50f5bf12015-11-12 15:20:15 -08003527 std::wstring path_wide;
3528 if (!android::base::UTF8ToWide(path, &path_wide)) {
3529 return -1;
3530 }
3531
3532 return wstat(path_wide.c_str(), s);
Spencer Low6815c072015-05-11 01:08:48 -07003533
3534#pragma pop_macro("wstat")
3535}
3536
3537// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08003538DIR* adb_opendir(const char* path) {
3539 std::wstring path_wide;
3540 if (!android::base::UTF8ToWide(path, &path_wide)) {
3541 return nullptr;
3542 }
3543
Spencer Low6815c072015-05-11 01:08:48 -07003544 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3545 // the fields, but right now all the callers treat the structure as
3546 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08003547 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07003548}
3549
3550// Version of readdir() that returns UTF-8 paths.
3551struct dirent* adb_readdir(DIR* dir) {
3552 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3553 struct _wdirent* const went = _wreaddir(wdir);
3554 if (went == nullptr) {
3555 return nullptr;
3556 }
Spencer Low50f5bf12015-11-12 15:20:15 -08003557
Spencer Low6815c072015-05-11 01:08:48 -07003558 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08003559 std::string name_utf8;
3560 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
3561 return nullptr;
3562 }
Spencer Low6815c072015-05-11 01:08:48 -07003563
3564 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3565 // space for UTF-16 wchar_t's) with UTF-8 char's.
3566 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3567
3568 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3569 // Name too big to fit in existing buffer.
3570 errno = ENOMEM;
3571 return nullptr;
3572 }
3573
3574 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3575 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3576 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3577 // bigger than the caller expects because they expect a dirent structure
3578 // which has a smaller d_name field. Ignore this since the caller should be
3579 // resilient.
3580
3581 // Rewrite the UTF-16 d_name field to UTF-8.
3582 strcpy(ent->d_name, name_utf8.c_str());
3583
3584 return ent;
3585}
3586
3587// Version of closedir() to go with our version of adb_opendir().
3588int adb_closedir(DIR* dir) {
3589 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3590}
3591
3592// Version of unlink() that takes a UTF-8 path.
3593int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003594 std::wstring wpath;
3595 if (!android::base::UTF8ToWide(path, &wpath)) {
3596 return -1;
3597 }
Spencer Low6815c072015-05-11 01:08:48 -07003598
3599 int rc = _wunlink(wpath.c_str());
3600
3601 if (rc == -1 && errno == EACCES) {
3602 /* unlink returns EACCES when the file is read-only, so we first */
3603 /* try to make it writable, then unlink again... */
3604 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3605 if (rc == 0)
3606 rc = _wunlink(wpath.c_str());
3607 }
3608 return rc;
3609}
3610
3611// Version of mkdir() that takes a UTF-8 path.
3612int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003613 std::wstring path_wide;
3614 if (!android::base::UTF8ToWide(path, &path_wide)) {
3615 return -1;
3616 }
3617
3618 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003619}
3620
3621// Version of utime() that takes a UTF-8 path.
3622int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003623 std::wstring path_wide;
3624 if (!android::base::UTF8ToWide(path, &path_wide)) {
3625 return -1;
3626 }
3627
Spencer Low6815c072015-05-11 01:08:48 -07003628 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3629 "utimbuf and _utimbuf should be the same size because they both "
3630 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08003631 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07003632}
3633
3634// Version of chmod() that takes a UTF-8 path.
3635int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003636 std::wstring path_wide;
3637 if (!android::base::UTF8ToWide(path, &path_wide)) {
3638 return -1;
3639 }
3640
3641 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07003642}
3643
Spencer Lowf373c352015-11-15 16:29:36 -08003644// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
3645static inline size_t utf8_codepoint_len(uint8_t ch) {
3646 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
3647}
Elliott Hughes37be38a2015-11-11 18:02:29 +00003648
Spencer Lowf373c352015-11-15 16:29:36 -08003649namespace internal {
3650
3651// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
3652// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
3653// remaining_bytes.
3654size_t ParseCompleteUTF8(const char* const first, const char* const last,
3655 std::vector<char>* const remaining_bytes) {
3656 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
3657 // Current_after points one byte past the current byte to be examined.
3658 for (const char* current_after = last; current_after != first; --current_after) {
3659 const char* const current = current_after - 1;
3660 const char ch = *current;
3661 const char kHighBit = 0x80u;
3662 const char kTwoHighestBits = 0xC0u;
3663 if ((ch & kHighBit) == 0) { // high bit not set
3664 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
3665 // bytes with no leading byte, so return the entire buffer.
3666 break;
3667 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
3668 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
3669 const size_t bytes_available = last - current;
3670 if (bytes_available < utf8_codepoint_len(ch)) {
3671 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
3672 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
3673 // to remaining_bytes.
3674 remaining_bytes->insert(remaining_bytes->end(), current, last);
3675 return current - first;
3676 } else {
3677 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
3678 // trailing bytes with no lead byte, so return the entire buffer.
3679 break;
3680 }
3681 } else {
3682 // Trailing byte, so keep going backwards looking for the lead byte.
3683 }
3684 }
3685
3686 // Return the size of the entire buffer. It is possible that we walked backward past invalid
3687 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
3688 // so that they can be processed.
3689 return last - first;
3690}
3691
3692}
3693
3694// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
3695// Note that we use only one buffer even though stderr and stdout are logically separate streams.
3696// This matches the behavior of Linux.
3697// Protected by g_console_output_buffer_lock.
3698static auto& g_console_output_buffer = *new std::vector<char>();
3699
3700// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
3701static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
3702 HANDLE console) {
3703 const int saved_errno = errno;
3704 std::vector<char> combined_buffer;
3705
3706 // Complete UTF-8 sequences that should be immediately written to the console.
3707 const char* utf8;
3708 size_t utf8_size;
3709
3710 adb_mutex_lock(&g_console_output_buffer_lock);
3711 if (g_console_output_buffer.empty()) {
3712 // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
3713 // common case with plain ASCII), parse buf directly.
3714 utf8 = buf;
3715 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer);
3716 } else {
3717 // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
3718 // combined_buffer (and effectively clear g_console_output_buffer) and append buf to
3719 // combined_buffer, then parse it all together.
3720 combined_buffer.swap(g_console_output_buffer);
3721 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
3722
3723 utf8 = combined_buffer.data();
3724 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
3725 &g_console_output_buffer);
3726 }
3727 adb_mutex_unlock(&g_console_output_buffer_lock);
3728
3729 std::wstring utf16;
3730
3731 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
3732 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
3733 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07003734 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08003735 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07003736
3737 // Note that this does not do \n => \r\n translation because that
3738 // doesn't seem necessary for the Windows console. For the Windows
3739 // console \r moves to the beginning of the line and \n moves to a new
3740 // line.
3741
3742 // Flush any stream buffering so that our output is afterwards which
3743 // makes sense because our call is afterwards.
3744 (void)fflush(stream);
3745
3746 // Write UTF-16 to the console.
3747 DWORD written = 0;
Spencer Lowf373c352015-11-15 16:29:36 -08003748 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Low6815c072015-05-11 01:08:48 -07003749 errno = EIO;
3750 return -1;
3751 }
3752
Spencer Lowf373c352015-11-15 16:29:36 -08003753 // Return the size of the original buffer passed in, signifying that we consumed it all, even
3754 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
3755 // matches the Linux behavior.
3756 errno = saved_errno;
3757 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07003758}
3759
3760// Function prototype because attributes cannot be placed on func definitions.
3761static int _console_vfprintf(const HANDLE console, FILE* stream,
3762 const char *format, va_list ap)
3763 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3764
3765// Internal function to format a UTF-8 string and write it to a Win32 console.
3766// Returns -1 on error.
3767static int _console_vfprintf(const HANDLE console, FILE* stream,
3768 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08003769 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07003770 std::string output_utf8;
3771
3772 // Format the string.
3773 // This could throw std::bad_alloc.
3774 android::base::StringAppendV(&output_utf8, format, ap);
3775
Spencer Lowf373c352015-11-15 16:29:36 -08003776 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
3777 console);
3778 if (result != -1) {
3779 errno = saved_errno;
3780 } else {
3781 // If -1 was returned, errno has been set.
3782 }
3783 return result;
Spencer Low6815c072015-05-11 01:08:48 -07003784}
3785
3786// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3787// Windows console.
3788int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3789 const HANDLE console = _get_console_handle(stream);
3790
3791 // If there is an associated Win32 console, write to it specially,
3792 // otherwise defer to the regular C Runtime, passing it UTF-8.
3793 if (console != NULL) {
3794 return _console_vfprintf(console, stream, format, ap);
3795 } else {
3796 // If vfprintf is a macro, undefine it, so we can call the real
3797 // C Runtime API.
3798#pragma push_macro("vfprintf")
3799#undef vfprintf
3800 return vfprintf(stream, format, ap);
3801#pragma pop_macro("vfprintf")
3802 }
3803}
3804
Spencer Lowf373c352015-11-15 16:29:36 -08003805// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
3806int adb_vprintf(const char *format, va_list ap) {
3807 return adb_vfprintf(stdout, format, ap);
3808}
3809
Spencer Low6815c072015-05-11 01:08:48 -07003810// Version of fprintf() that takes UTF-8 and can write Unicode to a
3811// Windows console.
3812int adb_fprintf(FILE *stream, const char *format, ...) {
3813 va_list ap;
3814 va_start(ap, format);
3815 const int result = adb_vfprintf(stream, format, ap);
3816 va_end(ap);
3817
3818 return result;
3819}
3820
3821// Version of printf() that takes UTF-8 and can write Unicode to a
3822// Windows console.
3823int adb_printf(const char *format, ...) {
3824 va_list ap;
3825 va_start(ap, format);
3826 const int result = adb_vfprintf(stdout, format, ap);
3827 va_end(ap);
3828
3829 return result;
3830}
3831
3832// Version of fputs() that takes UTF-8 and can write Unicode to a
3833// Windows console.
3834int adb_fputs(const char* buf, FILE* stream) {
3835 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3836 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08003837 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07003838 return adb_fprintf(stream, "%s", buf);
3839}
3840
3841// Version of fputc() that takes UTF-8 and can write Unicode to a
3842// Windows console.
3843int adb_fputc(int ch, FILE* stream) {
3844 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08003845 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07003846 return EOF;
3847 }
3848 // For success, fputc returns the char, cast to unsigned char, then to int.
3849 return static_cast<unsigned char>(ch);
3850}
3851
Spencer Lowf373c352015-11-15 16:29:36 -08003852// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
3853int adb_putchar(int ch) {
3854 return adb_fputc(ch, stdout);
3855}
3856
3857// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
3858int adb_puts(const char* buf) {
3859 // adb_printf returns -1 on error, which is conveniently the same as EOF
3860 // which puts (and hence adb_puts) should return on error.
3861 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
3862 return adb_printf("%s\n", buf);
3863}
3864
Spencer Low6815c072015-05-11 01:08:48 -07003865// Internal function to write UTF-8 to a Win32 console. Returns the number of
3866// items (of length size) written. On error, returns a short item count or 0.
3867static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3868 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08003869 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
3870 console);
Spencer Low6815c072015-05-11 01:08:48 -07003871 if (result == -1) {
3872 return 0;
3873 }
3874 return result / size;
3875}
3876
3877// Version of fwrite() that takes UTF-8 and can write Unicode to a
3878// Windows console.
3879size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3880 const HANDLE console = _get_console_handle(stream);
3881
3882 // If there is an associated Win32 console, write to it specially,
3883 // otherwise defer to the regular C Runtime, passing it UTF-8.
3884 if (console != NULL) {
3885 return _console_fwrite(ptr, size, nmemb, stream, console);
3886 } else {
3887 // If fwrite is a macro, undefine it, so we can call the real
3888 // C Runtime API.
3889#pragma push_macro("fwrite")
3890#undef fwrite
3891 return fwrite(ptr, size, nmemb, stream);
3892#pragma pop_macro("fwrite")
3893 }
3894}
3895
3896// Version of fopen() that takes a UTF-8 filename and can access a file with
3897// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08003898FILE* adb_fopen(const char* path, const char* mode) {
3899 std::wstring path_wide;
3900 if (!android::base::UTF8ToWide(path, &path_wide)) {
3901 return nullptr;
3902 }
3903
3904 std::wstring mode_wide;
3905 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
3906 return nullptr;
3907 }
3908
3909 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003910}
3911
Spencer Low50740f52015-09-08 17:13:04 -07003912// Return a lowercase version of the argument. Uses C Runtime tolower() on
3913// each byte which is not UTF-8 aware, and theoretically uses the current C
3914// Runtime locale (which in practice is not changed, so this becomes a ASCII
3915// conversion).
3916static std::string ToLower(const std::string& anycase) {
3917 // copy string
3918 std::string str(anycase);
3919 // transform the copy
3920 std::transform(str.begin(), str.end(), str.begin(), tolower);
3921 return str;
3922}
3923
3924extern "C" int main(int argc, char** argv);
3925
3926// Link with -municode to cause this wmain() to be used as the program
3927// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3928// regular main() with UTF-8 args.
3929extern "C" int wmain(int argc, wchar_t **argv) {
3930 // Convert args from UTF-16 to UTF-8 and pass that to main().
3931 NarrowArgs narrow_args(argc, argv);
3932 return main(argc, narrow_args.data());
3933}
3934
Spencer Low6815c072015-05-11 01:08:48 -07003935// Shadow UTF-8 environment variable name/value pairs that are created from
3936// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003937// currently updated if putenv, setenv, unsetenv are called. Note that no
3938// thread synchronization is done, but we're called early enough in
3939// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08003940static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07003941
3942// Make sure that shadow UTF-8 environment variables are setup.
3943static void _ensure_env_setup() {
3944 // If some name/value pairs exist, then we've already done the setup below.
3945 if (g_environ_utf8.size() != 0) {
3946 return;
3947 }
3948
Spencer Low50740f52015-09-08 17:13:04 -07003949 if (_wenviron == nullptr) {
3950 // If _wenviron is null, then -municode probably wasn't used. That
3951 // linker flag will cause the entry point to setup _wenviron. It will
3952 // also require an implementation of wmain() (which we provide above).
3953 fatal("_wenviron is not set, did you link with -municode?");
3954 }
3955
Spencer Low6815c072015-05-11 01:08:48 -07003956 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3957 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3958 // to use the D() macro here because that tracing only works if the
3959 // ADB_TRACE environment variable is setup, but that env var can't be read
3960 // until this code completes.
3961 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3962 wchar_t* const equal = wcschr(*env, L'=');
3963 if (equal == nullptr) {
3964 // Malformed environment variable with no equal sign. Shouldn't
3965 // really happen, but we should be resilient to this.
3966 continue;
3967 }
3968
Spencer Low50f5bf12015-11-12 15:20:15 -08003969 // If we encounter an error converting UTF-16, don't error-out on account of a single env
3970 // var because the program might never even read this particular variable.
3971 std::string name_utf8;
3972 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
3973 continue;
3974 }
3975
Spencer Low50740f52015-09-08 17:13:04 -07003976 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08003977 name_utf8 = ToLower(name_utf8);
3978
3979 std::string value_utf8;
3980 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
3981 continue;
3982 }
3983
3984 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003985
Spencer Low50740f52015-09-08 17:13:04 -07003986 // Don't overwrite a previus env var with the same name. In reality,
3987 // the system probably won't let two env vars with the same name exist
3988 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08003989 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07003990 }
3991}
3992
3993// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07003994// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07003995char* adb_getenv(const char* name) {
3996 _ensure_env_setup();
3997
Spencer Low50740f52015-09-08 17:13:04 -07003998 // Case-insensitive search by searching for lowercase name in a map of
3999 // lowercase names.
4000 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07004001 if (it == g_environ_utf8.end()) {
4002 return nullptr;
4003 }
4004
4005 return it->second;
4006}
4007
4008// Version of getcwd() that returns the current working directory in UTF-8.
4009char* adb_getcwd(char* buf, int size) {
4010 wchar_t* wbuf = _wgetcwd(nullptr, 0);
4011 if (wbuf == nullptr) {
4012 return nullptr;
4013 }
4014
Spencer Low50f5bf12015-11-12 15:20:15 -08004015 std::string buf_utf8;
4016 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07004017 free(wbuf);
4018 wbuf = nullptr;
4019
Spencer Low50f5bf12015-11-12 15:20:15 -08004020 if (!narrow_result) {
4021 return nullptr;
4022 }
4023
Spencer Low6815c072015-05-11 01:08:48 -07004024 // If size was specified, make sure all the chars will fit.
4025 if (size != 0) {
4026 if (size < static_cast<int>(buf_utf8.length() + 1)) {
4027 errno = ERANGE;
4028 return nullptr;
4029 }
4030 }
4031
4032 // If buf was not specified, allocate storage.
4033 if (buf == nullptr) {
4034 if (size == 0) {
4035 size = buf_utf8.length() + 1;
4036 }
4037 buf = reinterpret_cast<char*>(malloc(size));
4038 if (buf == nullptr) {
4039 return nullptr;
4040 }
4041 }
4042
4043 // Destination buffer was allocated with enough space, or we've already
4044 // checked an existing buffer size for enough space.
4045 strcpy(buf, buf_utf8.c_str());
4046
4047 return buf;
4048}