blob: 0a2a8f6902d20531aa58d33178bc84ff969b9ed6 [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
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080091#define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
92
Spencer Low753d4852015-07-30 23:07:55 -070093std::string SystemErrorCodeToString(const DWORD error_code) {
94 const int kErrorMessageBufferSize = 256;
Spencer Lowcc467f12015-08-02 18:13:54 -070095 WCHAR msgbuf[kErrorMessageBufferSize];
Spencer Low753d4852015-07-30 23:07:55 -070096 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
Spencer Lowcc467f12015-08-02 18:13:54 -070097 DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf,
Spencer Low753d4852015-07-30 23:07:55 -070098 arraysize(msgbuf), nullptr);
99 if (len == 0) {
100 return android::base::StringPrintf(
101 "Error (%lu) while retrieving error. (%lu)", GetLastError(),
102 error_code);
103 }
104
Spencer Lowcc467f12015-08-02 18:13:54 -0700105 // Convert UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -0800106 std::string msg;
107 if (!android::base::WideToUTF8(msgbuf, &msg)) {
108 return android::base::StringPrintf(
109 "Error (%d) converting from UTF-16 to UTF-8 while retrieving error. (%lu)", errno,
110 error_code);
111 }
112
Spencer Low753d4852015-07-30 23:07:55 -0700113 // Messages returned by the system end with line breaks.
114 msg = android::base::Trim(msg);
115 // There are many Windows error messages compared to POSIX, so include the
116 // numeric error code for easier, quicker, accurate identification. Use
117 // decimal instead of hex because there are decimal ranges like 10000-11999
118 // for Winsock.
119 android::base::StringAppendF(&msg, " (%lu)", error_code);
120 return msg;
121}
122
Spencer Low2bbb3a92015-08-26 18:46:09 -0700123void handle_deleter::operator()(HANDLE h) {
124 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
125 // implying that NULL is a valid handle, but this is probably impossible.
126 // Other APIs like CreateEvent() are documented to return NULL on error,
127 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
128 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
129 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
130 // only need to check for INVALID_HANDLE_VALUE.
131 if (h != INVALID_HANDLE_VALUE) {
132 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700133 D("CloseHandle(%p) failed: %s", h,
Spencer Low2bbb3a92015-08-26 18:46:09 -0700134 SystemErrorCodeToString(GetLastError()).c_str());
135 }
136 }
137}
138
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800139/**************************************************************************/
140/**************************************************************************/
141/***** *****/
142/***** replaces libs/cutils/load_file.c *****/
143/***** *****/
144/**************************************************************************/
145/**************************************************************************/
146
147void *load_file(const char *fn, unsigned *_sz)
148{
149 HANDLE file;
150 char *data;
151 DWORD file_size;
152
Spencer Low50f5bf12015-11-12 15:20:15 -0800153 std::wstring fn_wide;
154 if (!android::base::UTF8ToWide(fn, &fn_wide))
155 return NULL;
156
157 file = CreateFileW( fn_wide.c_str(),
Spencer Low6815c072015-05-11 01:08:48 -0700158 GENERIC_READ,
159 FILE_SHARE_READ,
160 NULL,
161 OPEN_EXISTING,
162 0,
163 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800164
165 if (file == INVALID_HANDLE_VALUE)
166 return NULL;
167
168 file_size = GetFileSize( file, NULL );
169 data = NULL;
170
171 if (file_size > 0) {
172 data = (char*) malloc( file_size + 1 );
173 if (data == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -0700174 D("load_file: could not allocate %ld bytes", file_size );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800175 file_size = 0;
176 } else {
177 DWORD out_bytes;
178
179 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
180 out_bytes != file_size )
181 {
Yabin Cui815ad882015-09-02 17:44:28 -0700182 D("load_file: could not read %ld bytes from '%s'", file_size, fn);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800183 free(data);
184 data = NULL;
185 file_size = 0;
186 }
187 }
188 }
189 CloseHandle( file );
190
191 *_sz = (unsigned) file_size;
192 return data;
193}
194
195/**************************************************************************/
196/**************************************************************************/
197/***** *****/
198/***** common file descriptor handling *****/
199/***** *****/
200/**************************************************************************/
201/**************************************************************************/
202
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800203/* used to emulate unix-domain socket pairs */
204typedef struct SocketPairRec_* SocketPair;
205
206typedef struct FHRec_
207{
208 FHClass clazz;
209 int used;
210 int eof;
211 union {
212 HANDLE handle;
213 SOCKET socket;
214 SocketPair pair;
215 } u;
216
217 HANDLE event;
218 int mask;
219
220 char name[32];
221
222} FHRec;
223
224#define fh_handle u.handle
225#define fh_socket u.socket
226#define fh_pair u.pair
227
228#define WIN32_FH_BASE 100
229
230#define WIN32_MAX_FHS 128
231
232static adb_mutex_t _win32_lock;
233static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700234static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800235
236static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700237_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800238{
239 FH f;
240
241 fd -= WIN32_FH_BASE;
242
Spencer Lowb732a372015-07-24 15:38:19 -0700243 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui815ad882015-09-02 17:44:28 -0700244 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700245 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800246 errno = EBADF;
247 return NULL;
248 }
249
250 f = &_win32_fhs[fd];
251
252 if (f->used == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700253 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700254 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800255 errno = EBADF;
256 return NULL;
257 }
258
259 return f;
260}
261
262
263static int
264_fh_to_int( FH f )
265{
266 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
267 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
268
269 return -1;
270}
271
272static FH
273_fh_alloc( FHClass clazz )
274{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800275 FH f = NULL;
276
277 adb_mutex_lock( &_win32_lock );
278
Spencer Lowb732a372015-07-24 15:38:19 -0700279 // Search entire array, starting from _win32_fh_next.
280 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
281 // Keep incrementing _win32_fh_next to avoid giving out an index that
282 // was recently closed, to try to avoid use-after-free.
283 const int index = _win32_fh_next++;
284 // Handle wrap-around of _win32_fh_next.
285 if (_win32_fh_next == WIN32_MAX_FHS) {
286 _win32_fh_next = 0;
287 }
288 if (_win32_fhs[index].clazz == NULL) {
289 f = &_win32_fhs[index];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800290 goto Exit;
291 }
292 }
Yabin Cui815ad882015-09-02 17:44:28 -0700293 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowb732a372015-07-24 15:38:19 -0700294 errno = EMFILE; // Too many open files
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800295Exit:
296 if (f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700297 f->clazz = clazz;
298 f->used = 1;
299 f->eof = 0;
300 f->name[0] = '\0';
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800301 clazz->_fh_init(f);
302 }
303 adb_mutex_unlock( &_win32_lock );
304 return f;
305}
306
307
308static int
309_fh_close( FH f )
310{
Spencer Lowb732a372015-07-24 15:38:19 -0700311 // Use lock so that closing only happens once and so that _fh_alloc can't
312 // allocate a FH that we're in the middle of closing.
313 adb_mutex_lock(&_win32_lock);
314 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800315 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700316 f->name[0] = '\0';
317 f->eof = 0;
318 f->used = 0;
319 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800320 }
Spencer Lowb732a372015-07-24 15:38:19 -0700321 adb_mutex_unlock(&_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800322 return 0;
323}
324
Spencer Low753d4852015-07-30 23:07:55 -0700325// Deleter for unique_fh.
326class fh_deleter {
327 public:
328 void operator()(struct FHRec_* fh) {
329 // We're called from a destructor and destructors should not overwrite
330 // errno because callers may do:
331 // errno = EBLAH;
332 // return -1; // calls destructor, which should not overwrite errno
333 const int saved_errno = errno;
334 _fh_close(fh);
335 errno = saved_errno;
336 }
337};
338
339// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
340typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
341
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800342/**************************************************************************/
343/**************************************************************************/
344/***** *****/
345/***** file-based descriptor handling *****/
346/***** *****/
347/**************************************************************************/
348/**************************************************************************/
349
Elliott Hughes6a096932015-04-16 16:47:02 -0700350static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800351 f->fh_handle = INVALID_HANDLE_VALUE;
352}
353
Elliott Hughes6a096932015-04-16 16:47:02 -0700354static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800355 CloseHandle( f->fh_handle );
356 f->fh_handle = INVALID_HANDLE_VALUE;
357 return 0;
358}
359
Elliott Hughes6a096932015-04-16 16:47:02 -0700360static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800361 DWORD read_bytes;
362
363 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700364 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800365 errno = EIO;
366 return -1;
367 } else if (read_bytes < (DWORD)len) {
368 f->eof = 1;
369 }
370 return (int)read_bytes;
371}
372
Elliott Hughes6a096932015-04-16 16:47:02 -0700373static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800374 DWORD wrote_bytes;
375
376 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700377 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800378 errno = EIO;
379 return -1;
380 } else if (wrote_bytes < (DWORD)len) {
381 f->eof = 1;
382 }
383 return (int)wrote_bytes;
384}
385
Elliott Hughes6a096932015-04-16 16:47:02 -0700386static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800387 DWORD method;
388 DWORD result;
389
390 switch (origin)
391 {
392 case SEEK_SET: method = FILE_BEGIN; break;
393 case SEEK_CUR: method = FILE_CURRENT; break;
394 case SEEK_END: method = FILE_END; break;
395 default:
396 errno = EINVAL;
397 return -1;
398 }
399
400 result = SetFilePointer( f->fh_handle, pos, NULL, method );
401 if (result == INVALID_SET_FILE_POINTER) {
402 errno = EIO;
403 return -1;
404 } else {
405 f->eof = 0;
406 }
407 return (int)result;
408}
409
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800410
411/**************************************************************************/
412/**************************************************************************/
413/***** *****/
414/***** file-based descriptor handling *****/
415/***** *****/
416/**************************************************************************/
417/**************************************************************************/
418
419int adb_open(const char* path, int options)
420{
421 FH f;
422
423 DWORD desiredAccess = 0;
424 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
425
426 switch (options) {
427 case O_RDONLY:
428 desiredAccess = GENERIC_READ;
429 break;
430 case O_WRONLY:
431 desiredAccess = GENERIC_WRITE;
432 break;
433 case O_RDWR:
434 desiredAccess = GENERIC_READ | GENERIC_WRITE;
435 break;
436 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700437 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800438 errno = EINVAL;
439 return -1;
440 }
441
442 f = _fh_alloc( &_fh_file_class );
443 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800444 return -1;
445 }
446
Spencer Low50f5bf12015-11-12 15:20:15 -0800447 std::wstring path_wide;
448 if (!android::base::UTF8ToWide(path, &path_wide)) {
449 return -1;
450 }
451 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Low6815c072015-05-11 01:08:48 -0700452 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800453
454 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700455 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800456 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700457 D( "adb_open: could not open '%s': ", path );
458 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800459 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700460 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800461 errno = ENOENT;
462 return -1;
463
464 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700465 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800466 errno = ENOTDIR;
467 return -1;
468
469 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700470 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700471 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800472 errno = ENOENT;
473 return -1;
474 }
475 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800476
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800477 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700478 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800479 return _fh_to_int(f);
480}
481
482/* ignore mode on Win32 */
483int adb_creat(const char* path, int mode)
484{
485 FH f;
486
487 f = _fh_alloc( &_fh_file_class );
488 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800489 return -1;
490 }
491
Spencer Low50f5bf12015-11-12 15:20:15 -0800492 std::wstring path_wide;
493 if (!android::base::UTF8ToWide(path, &path_wide)) {
494 return -1;
495 }
496 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Low6815c072015-05-11 01:08:48 -0700497 FILE_SHARE_READ | FILE_SHARE_WRITE,
498 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
499 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800500
501 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700502 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800503 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700504 D( "adb_creat: could not open '%s': ", path );
505 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800506 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700507 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800508 errno = ENOENT;
509 return -1;
510
511 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700512 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800513 errno = ENOTDIR;
514 return -1;
515
516 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700517 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700518 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800519 errno = ENOENT;
520 return -1;
521 }
522 }
523 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700524 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800525 return _fh_to_int(f);
526}
527
528
529int adb_read(int fd, void* buf, int len)
530{
Spencer Low3a2421b2015-05-22 20:09:06 -0700531 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800532
533 if (f == NULL) {
534 return -1;
535 }
536
537 return f->clazz->_fh_read( f, buf, len );
538}
539
540
541int adb_write(int fd, const void* buf, int len)
542{
Spencer Low3a2421b2015-05-22 20:09:06 -0700543 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800544
545 if (f == NULL) {
546 return -1;
547 }
548
549 return f->clazz->_fh_write(f, buf, len);
550}
551
552
553int adb_lseek(int fd, int pos, int where)
554{
Spencer Low3a2421b2015-05-22 20:09:06 -0700555 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800556
557 if (!f) {
558 return -1;
559 }
560
561 return f->clazz->_fh_lseek(f, pos, where);
562}
563
564
565int adb_close(int fd)
566{
Spencer Low3a2421b2015-05-22 20:09:06 -0700567 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800568
569 if (!f) {
570 return -1;
571 }
572
Yabin Cui815ad882015-09-02 17:44:28 -0700573 D( "adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800574 _fh_close(f);
575 return 0;
576}
577
Spencer Low028e1592015-10-18 16:45:09 -0700578// Overrides strerror() to handle error codes not supported by the Windows C
579// Runtime (MSVCRT.DLL).
580char* adb_strerror(int err) {
581 // sysdeps.h defines strerror to adb_strerror, but in this function, we
582 // want to call the real C Runtime strerror().
583#pragma push_macro("strerror")
584#undef strerror
585 const int saved_err = errno; // Save because we overwrite it later.
586
587 // Lookup the string for an unknown error.
588 char* errmsg = strerror(-1);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700589 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low028e1592015-10-18 16:45:09 -0700590
591 // Lookup the string for this error to see if the C Runtime has it.
592 errmsg = strerror(err);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700593 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low028e1592015-10-18 16:45:09 -0700594 // The CRT returned an error message and it is different than the error
595 // message for an unknown error, so it is probably valid, so use it.
596 } else {
597 // Check if we have a string for this error code.
598 const char* custom_msg = nullptr;
599 switch (err) {
600#pragma push_macro("ERR")
601#undef ERR
602#define ERR(errnum, desc) case errnum: custom_msg = desc; break
603 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
604 // Note that these cannot be longer than 94 characters because we
605 // pass this to _strerror() which has that requirement.
606 ERR(ECONNRESET, "Connection reset by peer");
607 ERR(EHOSTUNREACH, "No route to host");
608 ERR(ENETDOWN, "Network is down");
609 ERR(ENETRESET, "Network dropped connection because of reset");
610 ERR(ENOBUFS, "No buffer space available");
611 ERR(ENOPROTOOPT, "Protocol not available");
612 ERR(ENOTCONN, "Transport endpoint is not connected");
613 ERR(ENOTSOCK, "Socket operation on non-socket");
614 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
615#pragma pop_macro("ERR")
616 }
617
618 if (custom_msg != nullptr) {
619 // Use _strerror() to write our string into the writable per-thread
620 // buffer used by strerror()/_strerror(). _strerror() appends the
621 // msg for the current value of errno, so set errno to a consistent
622 // value for every call so that our code-path is always the same.
623 errno = 0;
624 errmsg = _strerror(custom_msg);
625 const size_t custom_msg_len = strlen(custom_msg);
626 // Just in case _strerror() returned a read-only string, check if
627 // the returned string starts with our custom message because that
628 // implies that the string is not read-only.
629 if ((errmsg != nullptr) &&
630 !strncmp(custom_msg, errmsg, custom_msg_len)) {
631 // _strerror() puts other text after our custom message, so
632 // remove that by terminating after our message.
633 errmsg[custom_msg_len] = '\0';
634 } else {
635 // For some reason nullptr was returned or a pointer to a
636 // read-only string was returned, so fallback to whatever
637 // strerror() can muster (probably "Unknown error" or some
638 // generic CRT error string).
639 errmsg = strerror(err);
640 }
641 } else {
642 // We don't have a custom message, so use whatever strerror(err)
643 // returned earlier.
644 }
645 }
646
647 errno = saved_err; // restore
648
649 return errmsg;
650#pragma pop_macro("strerror")
651}
652
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800653/**************************************************************************/
654/**************************************************************************/
655/***** *****/
656/***** socket-based file descriptors *****/
657/***** *****/
658/**************************************************************************/
659/**************************************************************************/
660
Spencer Low31aafa62015-01-25 14:40:16 -0800661#undef setsockopt
662
Spencer Low753d4852015-07-30 23:07:55 -0700663static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700664 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
665 // lot of POSIX and socket error codes, some of the resulting error codes
666 // are mapped to strings by adb_strerror() above.
Spencer Low753d4852015-07-30 23:07:55 -0700667 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800668 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700669 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
670 // case WSAEINTR: errno = EINTR; break;
671 case WSAEFAULT: errno = EFAULT; break;
672 case WSAEINVAL: errno = EINVAL; break;
673 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700674 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
675 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
676 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800677 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700678 case WSAENOTSOCK: errno = ENOTSOCK; break;
679 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
680 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
681 case WSAENETDOWN: errno = ENETDOWN; break;
682 case WSAENETRESET: errno = ENETRESET; break;
683 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
684 // to use EPIPE for these situations and there are some callers that look
685 // for EPIPE.
686 case WSAECONNABORTED: errno = EPIPE; break;
687 case WSAECONNRESET: errno = ECONNRESET; break;
688 case WSAENOBUFS: errno = ENOBUFS; break;
689 case WSAENOTCONN: errno = ENOTCONN; break;
690 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
691 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
692 // considerations: Reportedly send() can return zero on timeout, and POSIX
693 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
694 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
695 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800696 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800697 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700698 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700699 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800700 }
701}
702
Elliott Hughes6a096932015-04-16 16:47:02 -0700703static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800704 f->fh_socket = INVALID_SOCKET;
705 f->event = WSACreateEvent();
Spencer Low753d4852015-07-30 23:07:55 -0700706 if (f->event == WSA_INVALID_EVENT) {
Yabin Cui815ad882015-09-02 17:44:28 -0700707 D("WSACreateEvent failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700708 SystemErrorCodeToString(WSAGetLastError()).c_str());
709
710 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
711 // on failure, instead of NULL which is what Windows really returns on
712 // error. It might be better to change all the other code to look for
713 // NULL, but that is a much riskier change.
714 f->event = INVALID_HANDLE_VALUE;
715 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800716 f->mask = 0;
717}
718
Elliott Hughes6a096932015-04-16 16:47:02 -0700719static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700720 if (f->fh_socket != INVALID_SOCKET) {
721 /* gently tell any peer that we're closing the socket */
722 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
723 // If the socket is not connected, this returns an error. We want to
724 // minimize logging spam, so don't log these errors for now.
725#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700726 D("socket shutdown failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700727 SystemErrorCodeToString(WSAGetLastError()).c_str());
728#endif
729 }
730 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Yabin Cui815ad882015-09-02 17:44:28 -0700731 D("closesocket failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700732 SystemErrorCodeToString(WSAGetLastError()).c_str());
733 }
734 f->fh_socket = INVALID_SOCKET;
735 }
736 if (f->event != NULL) {
737 if (!CloseHandle(f->event)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700738 D("CloseHandle failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700739 SystemErrorCodeToString(GetLastError()).c_str());
740 }
741 f->event = NULL;
742 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800743 f->mask = 0;
744 return 0;
745}
746
Elliott Hughes6a096932015-04-16 16:47:02 -0700747static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800748 errno = EPIPE;
749 return -1;
750}
751
Elliott Hughes6a096932015-04-16 16:47:02 -0700752static int _fh_socket_read(FH f, void* buf, int len) {
753 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800754 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700755 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700756 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
757 // that to reduce spam and confusion.
758 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700759 D("recv fd %d failed: %s", _fh_to_int(f),
Spencer Low32625852015-08-11 16:45:32 -0700760 SystemErrorCodeToString(err).c_str());
761 }
Spencer Low753d4852015-07-30 23:07:55 -0700762 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800763 result = -1;
764 }
765 return result;
766}
767
Elliott Hughes6a096932015-04-16 16:47:02 -0700768static int _fh_socket_write(FH f, const void* buf, int len) {
769 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800770 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700771 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700772 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
773 // that to reduce spam and confusion.
774 if (err != WSAEWOULDBLOCK) {
775 D("send fd %d failed: %s", _fh_to_int(f),
776 SystemErrorCodeToString(err).c_str());
777 }
Spencer Low753d4852015-07-30 23:07:55 -0700778 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800779 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700780 } else {
781 // According to https://code.google.com/p/chromium/issues/detail?id=27870
782 // Winsock Layered Service Providers may cause this.
783 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
784 << f->name << ", but " << result
785 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800786 }
787 return result;
788}
789
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800790/**************************************************************************/
791/**************************************************************************/
792/***** *****/
793/***** replacement for libs/cutils/socket_xxxx.c *****/
794/***** *****/
795/**************************************************************************/
796/**************************************************************************/
797
798#include <winsock2.h>
799
800static int _winsock_init;
801
802static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800803_init_winsock( void )
804{
Spencer Low753d4852015-07-30 23:07:55 -0700805 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700806 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800807 if (!_winsock_init) {
808 WSADATA wsaData;
809 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
810 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700811 fatal( "adb: could not initialize Winsock: %s",
812 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800813 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800814 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700815
816 // Note that we do not call atexit() to register WSACleanup to be called
817 // at normal process termination because:
818 // 1) When exit() is called, there are still threads actively using
819 // Winsock because we don't cleanly shutdown all threads, so it
820 // doesn't make sense to call WSACleanup() and may cause problems
821 // with those threads.
822 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
823 // calls WSACleanup() which tries to unload a DLL, which tries to
824 // grab the LoaderLock. This conflicts with the device_poll_thread
825 // which holds the LoaderLock because AdbWinApi.dll calls
826 // setupapi.dll which tries to load wintrust.dll which tries to load
827 // crypt32.dll which calls atexit() which tries to acquire the C
828 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800829 }
830}
831
Spencer Lowc7c45612015-09-29 15:05:29 -0700832// Map a socket type to an explicit socket protocol instead of using the socket
833// protocol of 0. Explicit socket protocols are used by most apps and we should
834// do the same to reduce the chance of exercising uncommon code-paths that might
835// have problems or that might load different Winsock service providers that
836// have problems.
837static int GetSocketProtocolFromSocketType(int type) {
838 switch (type) {
839 case SOCK_STREAM:
840 return IPPROTO_TCP;
841 case SOCK_DGRAM:
842 return IPPROTO_UDP;
843 default:
844 LOG(FATAL) << "Unknown socket type: " << type;
845 return 0;
846 }
847}
848
Spencer Low753d4852015-07-30 23:07:55 -0700849int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800850 struct sockaddr_in addr;
851 SOCKET s;
852
Spencer Low753d4852015-07-30 23:07:55 -0700853 unique_fh f(_fh_alloc(&_fh_socket_class));
854 if (!f) {
855 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800856 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700857 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800858
859 if (!_winsock_init)
860 _init_winsock();
861
862 memset(&addr, 0, sizeof(addr));
863 addr.sin_family = AF_INET;
864 addr.sin_port = htons(port);
865 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
866
Spencer Lowc7c45612015-09-29 15:05:29 -0700867 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800868 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700869 *error = android::base::StringPrintf("cannot create socket: %s",
870 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700871 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700872 return -1;
873 }
874 f->fh_socket = s;
875
876 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700877 // Save err just in case inet_ntoa() or ntohs() changes the last error.
878 const DWORD err = WSAGetLastError();
879 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
880 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
881 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700882 D("could not connect to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700883 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800884 return -1;
885 }
886
Spencer Low753d4852015-07-30 23:07:55 -0700887 const int fd = _fh_to_int(f.get());
888 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
889 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700890 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700891 fd );
892 f.release();
893 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800894}
895
896#define LISTEN_BACKLOG 4
897
Spencer Low753d4852015-07-30 23:07:55 -0700898// interface_address is INADDR_LOOPBACK or INADDR_ANY.
899static int _network_server(int port, int type, u_long interface_address,
900 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800901 struct sockaddr_in addr;
902 SOCKET s;
903 int n;
904
Spencer Low753d4852015-07-30 23:07:55 -0700905 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800906 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700907 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800908 return -1;
909 }
910
911 if (!_winsock_init)
912 _init_winsock();
913
914 memset(&addr, 0, sizeof(addr));
915 addr.sin_family = AF_INET;
916 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700917 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800918
Spencer Low753d4852015-07-30 23:07:55 -0700919 // TODO: Consider using dual-stack socket that can simultaneously listen on
920 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700921 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700922 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700923 *error = android::base::StringPrintf("cannot create socket: %s",
924 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700925 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700926 return -1;
927 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800928
929 f->fh_socket = s;
930
Spencer Low32625852015-08-11 16:45:32 -0700931 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
932 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800933 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700934 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
935 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700936 *error = android::base::StringPrintf(
937 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
938 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700939 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700940 return -1;
941 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800942
Spencer Low32625852015-08-11 16:45:32 -0700943 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
944 // Save err just in case inet_ntoa() or ntohs() changes the last error.
945 const DWORD err = WSAGetLastError();
946 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
947 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
948 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700949 D("could not bind to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700950 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800951 return -1;
952 }
953 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700954 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700955 *error = android::base::StringPrintf("cannot listen on socket: %s",
956 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700957 D("could not listen on %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700958 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800959 return -1;
960 }
961 }
Spencer Low753d4852015-07-30 23:07:55 -0700962 const int fd = _fh_to_int(f.get());
963 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
964 interface_address == INADDR_LOOPBACK ? "lo" : "any",
965 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700966 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700967 fd );
968 f.release();
969 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800970}
971
Spencer Low753d4852015-07-30 23:07:55 -0700972int network_loopback_server(int port, int type, std::string* error) {
973 return _network_server(port, type, INADDR_LOOPBACK, error);
974}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800975
Spencer Low753d4852015-07-30 23:07:55 -0700976int network_inaddr_any_server(int port, int type, std::string* error) {
977 return _network_server(port, type, INADDR_ANY, error);
978}
979
980int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
981 unique_fh f(_fh_alloc(&_fh_socket_class));
982 if (!f) {
983 *error = strerror(errno);
984 return -1;
985 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800986
Elliott Hughes43df1092015-07-23 17:12:58 -0700987 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800988
Spencer Low753d4852015-07-30 23:07:55 -0700989 struct addrinfo hints;
990 memset(&hints, 0, sizeof(hints));
991 hints.ai_family = AF_UNSPEC;
992 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700993 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700994
995 char port_str[16];
996 snprintf(port_str, sizeof(port_str), "%d", port);
997
998 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700999
1000#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
1001 // TODO: When the Android SDK tools increases the Windows system
Spencer Low50f5bf12015-11-12 15:20:15 -08001002 // requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -07001003#else
1004 // Otherwise, keep using getaddrinfo(), or do runtime API detection
1005 // with GetProcAddress("GetAddrInfoW").
1006#endif
Spencer Low753d4852015-07-30 23:07:55 -07001007 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -07001008 *error = android::base::StringPrintf(
1009 "cannot resolve host '%s' and port %s: %s", host.c_str(),
1010 port_str, SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001011 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001012 return -1;
1013 }
Spencer Low753d4852015-07-30 23:07:55 -07001014 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
1015 addrinfo(addrinfo_ptr, freeaddrinfo);
1016 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001017
Spencer Low753d4852015-07-30 23:07:55 -07001018 // TODO: Try all the addresses if there's more than one? This just uses
1019 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
1020 // which tries all addresses, takes a timeout and more.
1021 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
1022 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001023 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -07001024 *error = android::base::StringPrintf("cannot create socket: %s",
1025 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001026 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001027 return -1;
1028 }
1029 f->fh_socket = s;
1030
Spencer Low753d4852015-07-30 23:07:55 -07001031 // TODO: Implement timeouts for Windows. Seems like the default in theory
1032 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
1033 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -07001034 // TODO: Use WSAAddressToString or inet_ntop on address.
1035 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
1036 host.c_str(), port_str,
1037 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001038 D("could not connect to %s:%s:%s: %s",
Spencer Low753d4852015-07-30 23:07:55 -07001039 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
1040 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001041 return -1;
1042 }
1043
Spencer Low753d4852015-07-30 23:07:55 -07001044 const int fd = _fh_to_int(f.get());
1045 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
1046 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -07001047 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low753d4852015-07-30 23:07:55 -07001048 type != SOCK_STREAM ? "udp" : "tcp", fd );
1049 f.release();
1050 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001051}
1052
1053#undef accept
1054int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
1055{
Spencer Low3a2421b2015-05-22 20:09:06 -07001056 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001057
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001058 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001059 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -07001060 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001061 return -1;
1062 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001063
Spencer Low753d4852015-07-30 23:07:55 -07001064 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001065 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -07001066 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1067 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001068 return -1;
1069 }
1070
1071 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1072 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001073 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -07001074 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
1075 " failed: " + SystemErrorCodeToString(err);
1076 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001077 return -1;
1078 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001079
Spencer Low753d4852015-07-30 23:07:55 -07001080 const int fd = _fh_to_int(fh.get());
1081 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -07001082 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -07001083 fh.release();
1084 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001085}
1086
1087
Spencer Low31aafa62015-01-25 14:40:16 -08001088int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001089{
Spencer Low3a2421b2015-05-22 20:09:06 -07001090 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001091
Spencer Low31aafa62015-01-25 14:40:16 -08001092 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001093 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001094 errno = EBADF;
1095 return -1;
1096 }
Spencer Lowc7c45612015-09-29 15:05:29 -07001097
1098 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1099 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1100 // auto-tuning.
1101
Spencer Low753d4852015-07-30 23:07:55 -07001102 int result = setsockopt( fh->fh_socket, level, optname,
1103 reinterpret_cast<const char*>(optval), optlen );
1104 if ( result == SOCKET_ERROR ) {
1105 const DWORD err = WSAGetLastError();
1106 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
1107 "failed: %s\n", fd, level, optname,
1108 SystemErrorCodeToString(err).c_str() );
1109 _socket_set_errno( err );
1110 result = -1;
1111 }
1112 return result;
1113}
1114
1115
1116int adb_shutdown(int fd)
1117{
1118 FH f = _fh_from_int(fd, __func__);
1119
1120 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001121 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001122 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001123 return -1;
1124 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001125
Yabin Cui815ad882015-09-02 17:44:28 -07001126 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001127 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1128 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001129 D("socket shutdown fd %d failed: %s", fd,
Spencer Low753d4852015-07-30 23:07:55 -07001130 SystemErrorCodeToString(err).c_str());
1131 _socket_set_errno(err);
1132 return -1;
1133 }
1134 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001135}
1136
1137/**************************************************************************/
1138/**************************************************************************/
1139/***** *****/
1140/***** emulated socketpairs *****/
1141/***** *****/
1142/**************************************************************************/
1143/**************************************************************************/
1144
1145/* we implement socketpairs directly in use space for the following reasons:
1146 * - it avoids copying data from/to the Nt kernel
1147 * - it allows us to implement fdevent hooks easily and cheaply, something
1148 * that is not possible with standard Win32 pipes !!
1149 *
1150 * basically, we use two circular buffers, each one corresponding to a given
1151 * direction.
1152 *
1153 * each buffer is implemented as two regions:
1154 *
1155 * region A which is (a_start,a_end)
1156 * region B which is (0, b_end) with b_end <= a_start
1157 *
1158 * an empty buffer has: a_start = a_end = b_end = 0
1159 *
1160 * a_start is the pointer where we start reading data
1161 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
1162 * then you start writing at b_end
1163 *
1164 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
1165 *
1166 * there is room when b_end < a_start || a_end < BUFER_SIZE
1167 *
1168 * when reading, a_start is incremented, it a_start meets a_end, then
1169 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1170 */
1171
1172#define BIP_BUFFER_SIZE 4096
1173
1174#if 0
1175#include <stdio.h>
1176# define BIPD(x) D x
1177# define BIPDUMP bip_dump_hex
1178
1179static void bip_dump_hex( const unsigned char* ptr, size_t len )
1180{
1181 int nn, len2 = len;
1182
1183 if (len2 > 8) len2 = 8;
1184
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001185 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001186 printf("%02x", ptr[nn]);
1187 printf(" ");
1188
1189 for (nn = 0; nn < len2; nn++) {
1190 int c = ptr[nn];
1191 if (c < 32 || c > 127)
1192 c = '.';
1193 printf("%c", c);
1194 }
1195 printf("\n");
1196 fflush(stdout);
1197}
1198
1199#else
1200# define BIPD(x) do {} while (0)
1201# define BIPDUMP(p,l) BIPD(p)
1202#endif
1203
1204typedef struct BipBufferRec_
1205{
1206 int a_start;
1207 int a_end;
1208 int b_end;
1209 int fdin;
1210 int fdout;
1211 int closed;
1212 int can_write; /* boolean */
1213 HANDLE evt_write; /* event signaled when one can write to a buffer */
1214 int can_read; /* boolean */
1215 HANDLE evt_read; /* event signaled when one can read from a buffer */
1216 CRITICAL_SECTION lock;
1217 unsigned char buff[ BIP_BUFFER_SIZE ];
1218
1219} BipBufferRec, *BipBuffer;
1220
1221static void
1222bip_buffer_init( BipBuffer buffer )
1223{
Yabin Cui815ad882015-09-02 17:44:28 -07001224 D( "bit_buffer_init %p", buffer );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001225 buffer->a_start = 0;
1226 buffer->a_end = 0;
1227 buffer->b_end = 0;
1228 buffer->can_write = 1;
1229 buffer->can_read = 0;
1230 buffer->fdin = 0;
1231 buffer->fdout = 0;
1232 buffer->closed = 0;
1233 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1234 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1235 InitializeCriticalSection( &buffer->lock );
1236}
1237
1238static void
1239bip_buffer_close( BipBuffer bip )
1240{
1241 bip->closed = 1;
1242
1243 if (!bip->can_read) {
1244 SetEvent( bip->evt_read );
1245 }
1246 if (!bip->can_write) {
1247 SetEvent( bip->evt_write );
1248 }
1249}
1250
1251static void
1252bip_buffer_done( BipBuffer bip )
1253{
Yabin Cui815ad882015-09-02 17:44:28 -07001254 BIPD(( "bip_buffer_done: %d->%d", bip->fdin, bip->fdout ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001255 CloseHandle( bip->evt_read );
1256 CloseHandle( bip->evt_write );
1257 DeleteCriticalSection( &bip->lock );
1258}
1259
1260static int
1261bip_buffer_write( BipBuffer bip, const void* src, int len )
1262{
1263 int avail, count = 0;
1264
1265 if (len <= 0)
1266 return 0;
1267
Yabin Cui815ad882015-09-02 17:44:28 -07001268 BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001269 BIPDUMP( src, len );
1270
David Pursell7616ae12015-09-11 16:06:59 -07001271 if (bip->closed) {
1272 errno = EPIPE;
1273 return -1;
1274 }
1275
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001276 EnterCriticalSection( &bip->lock );
1277
1278 while (!bip->can_write) {
1279 int ret;
1280 LeaveCriticalSection( &bip->lock );
1281
1282 if (bip->closed) {
1283 errno = EPIPE;
1284 return -1;
1285 }
1286 /* spinlocking here is probably unfair, but let's live with it */
1287 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1288 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
Yabin Cui815ad882015-09-02 17:44:28 -07001289 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 -08001290 return 0;
1291 }
1292 if (bip->closed) {
1293 errno = EPIPE;
1294 return -1;
1295 }
1296 EnterCriticalSection( &bip->lock );
1297 }
1298
Yabin Cui815ad882015-09-02 17:44:28 -07001299 BIPD(( "bip_buffer_write: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001300
1301 avail = BIP_BUFFER_SIZE - bip->a_end;
1302 if (avail > 0)
1303 {
1304 /* we can append to region A */
1305 if (avail > len)
1306 avail = len;
1307
1308 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001309 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001310 count += avail;
1311 len -= avail;
1312
1313 bip->a_end += avail;
1314 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1315 bip->can_write = 0;
1316 ResetEvent( bip->evt_write );
1317 goto Exit;
1318 }
1319 }
1320
1321 if (len == 0)
1322 goto Exit;
1323
1324 avail = bip->a_start - bip->b_end;
1325 assert( avail > 0 ); /* since can_write is TRUE */
1326
1327 if (avail > len)
1328 avail = len;
1329
1330 memcpy( bip->buff + bip->b_end, src, avail );
1331 count += avail;
1332 bip->b_end += avail;
1333
1334 if (bip->b_end == bip->a_start) {
1335 bip->can_write = 0;
1336 ResetEvent( bip->evt_write );
1337 }
1338
1339Exit:
1340 assert( count > 0 );
1341
1342 if ( !bip->can_read ) {
1343 bip->can_read = 1;
1344 SetEvent( bip->evt_read );
1345 }
1346
Yabin Cui815ad882015-09-02 17:44:28 -07001347 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 -08001348 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1349 LeaveCriticalSection( &bip->lock );
1350
1351 return count;
1352 }
1353
1354static int
1355bip_buffer_read( BipBuffer bip, void* dst, int len )
1356{
1357 int avail, count = 0;
1358
1359 if (len <= 0)
1360 return 0;
1361
Yabin Cui815ad882015-09-02 17:44:28 -07001362 BIPD(( "bip_buffer_read: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001363
1364 EnterCriticalSection( &bip->lock );
1365 while ( !bip->can_read )
1366 {
1367#if 0
1368 LeaveCriticalSection( &bip->lock );
1369 errno = EAGAIN;
1370 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001371#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001372 int ret;
1373 LeaveCriticalSection( &bip->lock );
1374
1375 if (bip->closed) {
1376 errno = EPIPE;
1377 return -1;
1378 }
1379
1380 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1381 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
Yabin Cui815ad882015-09-02 17:44:28 -07001382 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 -08001383 return 0;
1384 }
1385 if (bip->closed) {
1386 errno = EPIPE;
1387 return -1;
1388 }
1389 EnterCriticalSection( &bip->lock );
1390#endif
1391 }
1392
Yabin Cui815ad882015-09-02 17:44:28 -07001393 BIPD(( "bip_buffer_read: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001394
1395 avail = bip->a_end - bip->a_start;
1396 assert( avail > 0 ); /* since can_read is TRUE */
1397
1398 if (avail > len)
1399 avail = len;
1400
1401 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001402 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001403 count += avail;
1404 len -= avail;
1405
1406 bip->a_start += avail;
1407 if (bip->a_start < bip->a_end)
1408 goto Exit;
1409
1410 bip->a_start = 0;
1411 bip->a_end = bip->b_end;
1412 bip->b_end = 0;
1413
1414 avail = bip->a_end;
1415 if (avail > 0) {
1416 if (avail > len)
1417 avail = len;
1418 memcpy( dst, bip->buff, avail );
1419 count += avail;
1420 bip->a_start += avail;
1421
1422 if ( bip->a_start < bip->a_end )
1423 goto Exit;
1424
1425 bip->a_start = bip->a_end = 0;
1426 }
1427
1428 bip->can_read = 0;
1429 ResetEvent( bip->evt_read );
1430
1431Exit:
1432 assert( count > 0 );
1433
1434 if (!bip->can_write ) {
1435 bip->can_write = 1;
1436 SetEvent( bip->evt_write );
1437 }
1438
1439 BIPDUMP( (const unsigned char*)dst - count, count );
Yabin Cui815ad882015-09-02 17:44:28 -07001440 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 -08001441 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1442 LeaveCriticalSection( &bip->lock );
1443
1444 return count;
1445}
1446
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001447typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001448{
1449 BipBufferRec a2b_bip;
1450 BipBufferRec b2a_bip;
1451 FH a_fd;
1452 int used;
1453
1454} SocketPairRec;
1455
1456void _fh_socketpair_init( FH f )
1457{
1458 f->fh_pair = NULL;
1459}
1460
1461static int
1462_fh_socketpair_close( FH f )
1463{
1464 if ( f->fh_pair ) {
1465 SocketPair pair = f->fh_pair;
1466
1467 if ( f == pair->a_fd ) {
1468 pair->a_fd = NULL;
1469 }
1470
1471 bip_buffer_close( &pair->b2a_bip );
1472 bip_buffer_close( &pair->a2b_bip );
1473
1474 if ( --pair->used == 0 ) {
1475 bip_buffer_done( &pair->b2a_bip );
1476 bip_buffer_done( &pair->a2b_bip );
1477 free( pair );
1478 }
1479 f->fh_pair = NULL;
1480 }
1481 return 0;
1482}
1483
1484static int
1485_fh_socketpair_lseek( FH f, int pos, int origin )
1486{
1487 errno = ESPIPE;
1488 return -1;
1489}
1490
1491static int
1492_fh_socketpair_read( FH f, void* buf, int len )
1493{
1494 SocketPair pair = f->fh_pair;
1495 BipBuffer bip;
1496
1497 if (!pair)
1498 return -1;
1499
1500 if ( f == pair->a_fd )
1501 bip = &pair->b2a_bip;
1502 else
1503 bip = &pair->a2b_bip;
1504
1505 return bip_buffer_read( bip, buf, len );
1506}
1507
1508static int
1509_fh_socketpair_write( FH f, const void* buf, int len )
1510{
1511 SocketPair pair = f->fh_pair;
1512 BipBuffer bip;
1513
1514 if (!pair)
1515 return -1;
1516
1517 if ( f == pair->a_fd )
1518 bip = &pair->a2b_bip;
1519 else
1520 bip = &pair->b2a_bip;
1521
1522 return bip_buffer_write( bip, buf, len );
1523}
1524
1525
1526static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1527
1528static const FHClassRec _fh_socketpair_class =
1529{
1530 _fh_socketpair_init,
1531 _fh_socketpair_close,
1532 _fh_socketpair_lseek,
1533 _fh_socketpair_read,
1534 _fh_socketpair_write,
1535 _fh_socketpair_hook
1536};
1537
1538
Elliott Hughes6a096932015-04-16 16:47:02 -07001539int adb_socketpair(int sv[2]) {
1540 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001541
Spencer Low753d4852015-07-30 23:07:55 -07001542 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1543 if (!fa) {
1544 return -1;
1545 }
1546 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1547 if (!fb) {
1548 return -1;
1549 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001550
Elliott Hughes6a096932015-04-16 16:47:02 -07001551 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001552 if (pair == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001553 D("adb_socketpair: not enough memory to allocate pipes" );
Spencer Low753d4852015-07-30 23:07:55 -07001554 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001555 }
1556
1557 bip_buffer_init( &pair->a2b_bip );
1558 bip_buffer_init( &pair->b2a_bip );
1559
1560 fa->fh_pair = pair;
1561 fb->fh_pair = pair;
1562 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001563 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001564
Spencer Low753d4852015-07-30 23:07:55 -07001565 sv[0] = _fh_to_int(fa.get());
1566 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001567
1568 pair->a2b_bip.fdin = sv[0];
1569 pair->a2b_bip.fdout = sv[1];
1570 pair->b2a_bip.fdin = sv[1];
1571 pair->b2a_bip.fdout = sv[0];
1572
1573 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1574 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
Yabin Cui815ad882015-09-02 17:44:28 -07001575 D( "adb_socketpair: returns (%d, %d)", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001576 fa.release();
1577 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001578 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001579}
1580
1581/**************************************************************************/
1582/**************************************************************************/
1583/***** *****/
1584/***** fdevents emulation *****/
1585/***** *****/
1586/***** this is a very simple implementation, we rely on the fact *****/
1587/***** that ADB doesn't use FDE_ERROR. *****/
1588/***** *****/
1589/**************************************************************************/
1590/**************************************************************************/
1591
1592#define FATAL(x...) fatal(__FUNCTION__, x)
1593
1594#if DEBUG
1595static void dump_fde(fdevent *fde, const char *info)
1596{
1597 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1598 fde->state & FDE_READ ? 'R' : ' ',
1599 fde->state & FDE_WRITE ? 'W' : ' ',
1600 fde->state & FDE_ERROR ? 'E' : ' ',
1601 info);
1602}
1603#else
1604#define dump_fde(fde, info) do { } while(0)
1605#endif
1606
1607#define FDE_EVENTMASK 0x00ff
1608#define FDE_STATEMASK 0xff00
1609
1610#define FDE_ACTIVE 0x0100
1611#define FDE_PENDING 0x0200
1612#define FDE_CREATED 0x0400
1613
1614static void fdevent_plist_enqueue(fdevent *node);
1615static void fdevent_plist_remove(fdevent *node);
1616static fdevent *fdevent_plist_dequeue(void);
1617
1618static fdevent list_pending = {
1619 .next = &list_pending,
1620 .prev = &list_pending,
1621};
1622
1623static fdevent **fd_table = 0;
1624static int fd_table_max = 0;
1625
1626typedef struct EventLooperRec_* EventLooper;
1627
1628typedef struct EventHookRec_
1629{
1630 EventHook next;
1631 FH fh;
1632 HANDLE h;
1633 int wanted; /* wanted event flags */
1634 int ready; /* ready event flags */
1635 void* aux;
1636 void (*prepare)( EventHook hook );
1637 int (*start) ( EventHook hook );
1638 void (*stop) ( EventHook hook );
1639 int (*check) ( EventHook hook );
1640 int (*peek) ( EventHook hook );
1641} EventHookRec;
1642
1643static EventHook _free_hooks;
1644
1645static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001646event_hook_alloc(FH fh) {
1647 EventHook hook = _free_hooks;
1648 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001649 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001650 } else {
1651 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001652 if (hook == NULL)
1653 fatal( "could not allocate event hook\n" );
1654 }
1655 hook->next = NULL;
1656 hook->fh = fh;
1657 hook->wanted = 0;
1658 hook->ready = 0;
1659 hook->h = INVALID_HANDLE_VALUE;
1660 hook->aux = NULL;
1661
1662 hook->prepare = NULL;
1663 hook->start = NULL;
1664 hook->stop = NULL;
1665 hook->check = NULL;
1666 hook->peek = NULL;
1667
1668 return hook;
1669}
1670
1671static void
1672event_hook_free( EventHook hook )
1673{
1674 hook->fh = NULL;
1675 hook->wanted = 0;
1676 hook->ready = 0;
1677 hook->next = _free_hooks;
1678 _free_hooks = hook;
1679}
1680
1681
1682static void
1683event_hook_signal( EventHook hook )
1684{
1685 FH f = hook->fh;
1686 int fd = _fh_to_int(f);
1687 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1688
1689 if (fde != NULL && fde->fd == fd) {
1690 if ((fde->state & FDE_PENDING) == 0) {
1691 fde->state |= FDE_PENDING;
1692 fdevent_plist_enqueue( fde );
1693 }
1694 fde->events |= hook->wanted;
1695 }
1696}
1697
1698
1699#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1700
1701typedef struct EventLooperRec_
1702{
1703 EventHook hooks;
1704 HANDLE htab[ MAX_LOOPER_HANDLES ];
1705 int htab_count;
1706
1707} EventLooperRec;
1708
1709static EventHook*
1710event_looper_find_p( EventLooper looper, FH fh )
1711{
1712 EventHook *pnode = &looper->hooks;
1713 EventHook node = *pnode;
1714 for (;;) {
1715 if ( node == NULL || node->fh == fh )
1716 break;
1717 pnode = &node->next;
1718 node = *pnode;
1719 }
1720 return pnode;
1721}
1722
1723static void
1724event_looper_hook( EventLooper looper, int fd, int events )
1725{
Spencer Low3a2421b2015-05-22 20:09:06 -07001726 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001727 EventHook *pnode;
1728 EventHook node;
1729
1730 if (f == NULL) /* invalid arg */ {
Yabin Cui815ad882015-09-02 17:44:28 -07001731 D("event_looper_hook: invalid fd=%d", fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001732 return;
1733 }
1734
1735 pnode = event_looper_find_p( looper, f );
1736 node = *pnode;
1737 if ( node == NULL ) {
1738 node = event_hook_alloc( f );
1739 node->next = *pnode;
1740 *pnode = node;
1741 }
1742
1743 if ( (node->wanted & events) != events ) {
1744 /* this should update start/stop/check/peek */
Yabin Cui815ad882015-09-02 17:44:28 -07001745 D("event_looper_hook: call hook for %d (new=%x, old=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001746 fd, node->wanted, events);
1747 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1748 node->wanted |= events;
1749 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07001750 D("event_looper_hook: ignoring events %x for %d wanted=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001751 events, fd, node->wanted);
1752 }
1753}
1754
1755static void
1756event_looper_unhook( EventLooper looper, int fd, int events )
1757{
Spencer Low3a2421b2015-05-22 20:09:06 -07001758 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001759 EventHook *pnode = event_looper_find_p( looper, fh );
1760 EventHook node = *pnode;
1761
1762 if (node != NULL) {
1763 int events2 = events & node->wanted;
1764 if ( events2 == 0 ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001765 D( "event_looper_unhook: events %x not registered for fd %d", events, fd );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001766 return;
1767 }
1768 node->wanted &= ~events2;
1769 if (!node->wanted) {
1770 *pnode = node->next;
1771 event_hook_free( node );
1772 }
1773 }
1774}
1775
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001776/*
1777 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1778 * handles to wait on.
1779 *
1780 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1781 * instance, this may happen if there are more than 64 processes running on a
1782 * device, or there are multiple devices connected (including the emulator) with
1783 * the combined number of running processes greater than 64. In this case using
1784 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1785 * because of the API limitations (64 handles max). So, we need to provide a way
1786 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1787 * easiest (and "Microsoft recommended") way to do that would be dividing the
1788 * handle array into chunks with the chunk size less than 64, and fire up as many
1789 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1790 * handles, and will report back to the caller which handle has been set.
1791 * Here is the implementation of that algorithm.
1792 */
1793
1794/* Number of handles to wait on in each wating thread. */
1795#define WAIT_ALL_CHUNK_SIZE 63
1796
1797/* Descriptor for a wating thread */
1798typedef struct WaitForAllParam {
1799 /* A handle to an event to signal when waiting is over. This handle is shared
1800 * accross all the waiting threads, so each waiting thread knows when any
1801 * other thread has exited, so it can exit too. */
1802 HANDLE main_event;
1803 /* Upon exit from a waiting thread contains the index of the handle that has
1804 * been signaled. The index is an absolute index of the signaled handle in
1805 * the original array. This pointer is shared accross all the waiting threads
1806 * and it's not guaranteed (due to a race condition) that when all the
1807 * waiting threads exit, the value contained here would indicate the first
1808 * handle that was signaled. This is fine, because the caller cares only
1809 * about any handle being signaled. It doesn't care about the order, nor
1810 * about the whole list of handles that were signaled. */
1811 LONG volatile *signaled_index;
1812 /* Array of handles to wait on in a waiting thread. */
1813 HANDLE* handles;
1814 /* Number of handles in 'handles' array to wait on. */
1815 int handles_count;
1816 /* Index inside the main array of the first handle in the 'handles' array. */
1817 int first_handle_index;
1818 /* Waiting thread handle. */
1819 HANDLE thread;
1820} WaitForAllParam;
1821
1822/* Waiting thread routine. */
1823static unsigned __stdcall
1824_in_waiter_thread(void* arg)
1825{
1826 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1827 int res;
1828 WaitForAllParam* const param = (WaitForAllParam*)arg;
1829
1830 /* We have to wait on the main_event in order to be notified when any of the
1831 * sibling threads is exiting. */
1832 wait_on[0] = param->main_event;
1833 /* The rest of the handles go behind the main event handle. */
1834 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1835
1836 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1837 if (res > 0 && res < (param->handles_count + 1)) {
1838 /* One of the original handles got signaled. Save its absolute index into
1839 * the output variable. */
1840 InterlockedCompareExchange(param->signaled_index,
1841 res - 1L + param->first_handle_index, -1L);
1842 }
1843
1844 /* Notify the caller (and the siblings) that the wait is over. */
1845 SetEvent(param->main_event);
1846
1847 _endthreadex(0);
1848 return 0;
1849}
1850
1851/* WaitForMultipeObjects fixer routine.
1852 * Param:
1853 * handles Array of handles to wait on.
1854 * handles_count Number of handles in the array.
1855 * Return:
1856 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1857 * WAIT_FAILED on an error.
1858 */
1859static int
1860_wait_for_all(HANDLE* handles, int handles_count)
1861{
1862 WaitForAllParam* threads;
1863 HANDLE main_event;
1864 int chunks, chunk, remains;
1865
1866 /* This variable is going to be accessed by several threads at the same time,
1867 * this is bound to fail randomly when the core is run on multi-core machines.
1868 * To solve this, we need to do the following (1 _and_ 2):
1869 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1870 * out the reads/writes in this function unexpectedly.
1871 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1872 * all accesses inside a critical section. But we can also use
1873 * InterlockedCompareExchange() which always provide a full memory barrier
1874 * on Win32.
1875 */
1876 volatile LONG sig_index = -1;
1877
1878 /* Calculate number of chunks, and allocate thread param array. */
1879 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1880 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1881 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1882 sizeof(WaitForAllParam));
1883 if (threads == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001884 D("Unable to allocate thread array for %d handles.", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001885 return (int)WAIT_FAILED;
1886 }
1887
1888 /* Create main event to wait on for all waiting threads. This is a "manualy
1889 * reset" event that will remain set once it was set. */
1890 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1891 if (main_event == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001892 D("Unable to create main event. Error: %ld", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001893 free(threads);
1894 return (int)WAIT_FAILED;
1895 }
1896
1897 /*
1898 * Initialize waiting thread parameters.
1899 */
1900
1901 for (chunk = 0; chunk < chunks; chunk++) {
1902 threads[chunk].main_event = main_event;
1903 threads[chunk].signaled_index = &sig_index;
1904 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1905 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1906 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1907 }
1908 if (remains) {
1909 threads[chunk].main_event = main_event;
1910 threads[chunk].signaled_index = &sig_index;
1911 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1912 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1913 threads[chunk].handles_count = remains;
1914 chunks++;
1915 }
1916
1917 /* Start the waiting threads. */
1918 for (chunk = 0; chunk < chunks; chunk++) {
1919 /* Note that using adb_thread_create is not appropriate here, since we
1920 * need a handle to wait on for thread termination. */
1921 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1922 &threads[chunk], 0, NULL);
1923 if (threads[chunk].thread == NULL) {
1924 /* Unable to create a waiter thread. Collapse. */
Yabin Cui815ad882015-09-02 17:44:28 -07001925 D("Unable to create a waiting thread %d of %d. errno=%d",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001926 chunk, chunks, errno);
1927 chunks = chunk;
1928 SetEvent(main_event);
1929 break;
1930 }
1931 }
1932
1933 /* Wait on any of the threads to get signaled. */
1934 WaitForSingleObject(main_event, INFINITE);
1935
1936 /* Wait on all the waiting threads to exit. */
1937 for (chunk = 0; chunk < chunks; chunk++) {
1938 WaitForSingleObject(threads[chunk].thread, INFINITE);
1939 CloseHandle(threads[chunk].thread);
1940 }
1941
1942 CloseHandle(main_event);
1943 free(threads);
1944
1945
1946 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1947 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1948}
1949
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001950static EventLooperRec win32_looper;
1951
1952static void fdevent_init(void)
1953{
1954 win32_looper.htab_count = 0;
1955 win32_looper.hooks = NULL;
1956}
1957
1958static void fdevent_connect(fdevent *fde)
1959{
1960 EventLooper looper = &win32_looper;
1961 int events = fde->state & FDE_EVENTMASK;
1962
1963 if (events != 0)
1964 event_looper_hook( looper, fde->fd, events );
1965}
1966
1967static void fdevent_disconnect(fdevent *fde)
1968{
1969 EventLooper looper = &win32_looper;
1970 int events = fde->state & FDE_EVENTMASK;
1971
1972 if (events != 0)
1973 event_looper_unhook( looper, fde->fd, events );
1974}
1975
1976static void fdevent_update(fdevent *fde, unsigned events)
1977{
1978 EventLooper looper = &win32_looper;
1979 unsigned events0 = fde->state & FDE_EVENTMASK;
1980
1981 if (events != events0) {
1982 int removes = events0 & ~events;
1983 int adds = events & ~events0;
1984 if (removes) {
Yabin Cui815ad882015-09-02 17:44:28 -07001985 D("fdevent_update: remove %x from %d", removes, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001986 event_looper_unhook( looper, fde->fd, removes );
1987 }
1988 if (adds) {
Yabin Cui815ad882015-09-02 17:44:28 -07001989 D("fdevent_update: add %x to %d", adds, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001990 event_looper_hook ( looper, fde->fd, adds );
1991 }
1992 }
1993}
1994
1995static void fdevent_process()
1996{
1997 EventLooper looper = &win32_looper;
1998 EventHook hook;
1999 int gotone = 0;
2000
2001 /* if we have at least one ready hook, execute it/them */
2002 for (hook = looper->hooks; hook; hook = hook->next) {
2003 hook->ready = 0;
2004 if (hook->prepare) {
2005 hook->prepare(hook);
2006 if (hook->ready != 0) {
2007 event_hook_signal( hook );
2008 gotone = 1;
2009 }
2010 }
2011 }
2012
2013 /* nothing's ready yet, so wait for something to happen */
2014 if (!gotone)
2015 {
2016 looper->htab_count = 0;
2017
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002018 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002019 {
2020 if (hook->start && !hook->start(hook)) {
Yabin Cui815ad882015-09-02 17:44:28 -07002021 D( "fdevent_process: error when starting a hook" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002022 return;
2023 }
2024 if (hook->h != INVALID_HANDLE_VALUE) {
2025 int nn;
2026
2027 for (nn = 0; nn < looper->htab_count; nn++)
2028 {
2029 if ( looper->htab[nn] == hook->h )
2030 goto DontAdd;
2031 }
2032 looper->htab[ looper->htab_count++ ] = hook->h;
2033 DontAdd:
2034 ;
2035 }
2036 }
2037
2038 if (looper->htab_count == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -07002039 D( "fdevent_process: nothing to wait for !!" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002040 return;
2041 }
2042
2043 do
2044 {
2045 int wait_ret;
2046
Yabin Cui815ad882015-09-02 17:44:28 -07002047 D( "adb_win32: waiting for %d events", looper->htab_count );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002048 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Yabin Cui815ad882015-09-02 17:44:28 -07002049 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.", looper->htab_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002050 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
2051 } else {
2052 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002053 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002054 if (wait_ret == (int)WAIT_FAILED) {
Yabin Cui815ad882015-09-02 17:44:28 -07002055 D( "adb_win32: wait failed, error %ld", GetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002056 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07002057 D( "adb_win32: got one (index %d)", wait_ret );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002058
2059 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
2060 * like mouse movements. we need to filter these with the "check" function
2061 */
2062 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
2063 {
2064 for (hook = looper->hooks; hook; hook = hook->next)
2065 {
2066 if ( looper->htab[wait_ret] == hook->h &&
2067 (!hook->check || hook->check(hook)) )
2068 {
Yabin Cui815ad882015-09-02 17:44:28 -07002069 D( "adb_win32: signaling %s for %x", hook->fh->name, hook->ready );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002070 event_hook_signal( hook );
2071 gotone = 1;
2072 break;
2073 }
2074 }
2075 }
2076 }
2077 }
2078 while (!gotone);
2079
2080 for (hook = looper->hooks; hook; hook = hook->next) {
2081 if (hook->stop)
2082 hook->stop( hook );
2083 }
2084 }
2085
2086 for (hook = looper->hooks; hook; hook = hook->next) {
2087 if (hook->peek && hook->peek(hook))
2088 event_hook_signal( hook );
2089 }
2090}
2091
2092
2093static void fdevent_register(fdevent *fde)
2094{
2095 int fd = fde->fd - WIN32_FH_BASE;
2096
2097 if(fd < 0) {
2098 FATAL("bogus negative fd (%d)\n", fde->fd);
2099 }
2100
2101 if(fd >= fd_table_max) {
2102 int oldmax = fd_table_max;
2103 if(fde->fd > 32000) {
2104 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
2105 }
2106 if(fd_table_max == 0) {
2107 fdevent_init();
2108 fd_table_max = 256;
2109 }
2110 while(fd_table_max <= fd) {
2111 fd_table_max *= 2;
2112 }
Elliott Hughes6a096932015-04-16 16:47:02 -07002113 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002114 if(fd_table == 0) {
2115 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
2116 }
2117 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
2118 }
2119
2120 fd_table[fd] = fde;
2121}
2122
2123static void fdevent_unregister(fdevent *fde)
2124{
2125 int fd = fde->fd - WIN32_FH_BASE;
2126
2127 if((fd < 0) || (fd >= fd_table_max)) {
2128 FATAL("fd out of range (%d)\n", fde->fd);
2129 }
2130
2131 if(fd_table[fd] != fde) {
2132 FATAL("fd_table out of sync");
2133 }
2134
2135 fd_table[fd] = 0;
2136
2137 if(!(fde->state & FDE_DONT_CLOSE)) {
2138 dump_fde(fde, "close");
2139 adb_close(fde->fd);
2140 }
2141}
2142
2143static void fdevent_plist_enqueue(fdevent *node)
2144{
2145 fdevent *list = &list_pending;
2146
2147 node->next = list;
2148 node->prev = list->prev;
2149 node->prev->next = node;
2150 list->prev = node;
2151}
2152
2153static void fdevent_plist_remove(fdevent *node)
2154{
2155 node->prev->next = node->next;
2156 node->next->prev = node->prev;
2157 node->next = 0;
2158 node->prev = 0;
2159}
2160
2161static fdevent *fdevent_plist_dequeue(void)
2162{
2163 fdevent *list = &list_pending;
2164 fdevent *node = list->next;
2165
2166 if(node == list) return 0;
2167
2168 list->next = node->next;
2169 list->next->prev = list;
2170 node->next = 0;
2171 node->prev = 0;
2172
2173 return node;
2174}
2175
2176fdevent *fdevent_create(int fd, fd_func func, void *arg)
2177{
2178 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2179 if(fde == 0) return 0;
2180 fdevent_install(fde, fd, func, arg);
2181 fde->state |= FDE_CREATED;
2182 return fde;
2183}
2184
2185void fdevent_destroy(fdevent *fde)
2186{
2187 if(fde == 0) return;
2188 if(!(fde->state & FDE_CREATED)) {
2189 FATAL("fde %p not created by fdevent_create()\n", fde);
2190 }
2191 fdevent_remove(fde);
2192}
2193
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002194void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002195{
2196 memset(fde, 0, sizeof(fdevent));
2197 fde->state = FDE_ACTIVE;
2198 fde->fd = fd;
2199 fde->func = func;
2200 fde->arg = arg;
2201
2202 fdevent_register(fde);
2203 dump_fde(fde, "connect");
2204 fdevent_connect(fde);
2205 fde->state |= FDE_ACTIVE;
2206}
2207
2208void fdevent_remove(fdevent *fde)
2209{
2210 if(fde->state & FDE_PENDING) {
2211 fdevent_plist_remove(fde);
2212 }
2213
2214 if(fde->state & FDE_ACTIVE) {
2215 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002216 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002217 fdevent_unregister(fde);
2218 }
2219
2220 fde->state = 0;
2221 fde->events = 0;
2222}
2223
2224
2225void fdevent_set(fdevent *fde, unsigned events)
2226{
2227 events &= FDE_EVENTMASK;
2228
2229 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2230
2231 if(fde->state & FDE_ACTIVE) {
2232 fdevent_update(fde, events);
2233 dump_fde(fde, "update");
2234 }
2235
2236 fde->state = (fde->state & FDE_STATEMASK) | events;
2237
2238 if(fde->state & FDE_PENDING) {
2239 /* if we're pending, make sure
2240 ** we don't signal an event that
2241 ** is no longer wanted.
2242 */
2243 fde->events &= (~events);
2244 if(fde->events == 0) {
2245 fdevent_plist_remove(fde);
2246 fde->state &= (~FDE_PENDING);
2247 }
2248 }
2249}
2250
2251void fdevent_add(fdevent *fde, unsigned events)
2252{
2253 fdevent_set(
2254 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2255}
2256
2257void fdevent_del(fdevent *fde, unsigned events)
2258{
2259 fdevent_set(
2260 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2261}
2262
2263void fdevent_loop()
2264{
2265 fdevent *fde;
2266
2267 for(;;) {
2268#if DEBUG
2269 fprintf(stderr,"--- ---- waiting for events\n");
2270#endif
2271 fdevent_process();
2272
2273 while((fde = fdevent_plist_dequeue())) {
2274 unsigned events = fde->events;
2275 fde->events = 0;
2276 fde->state &= (~FDE_PENDING);
2277 dump_fde(fde, "callback");
2278 fde->func(fde->fd, events, fde->arg);
2279 }
2280 }
2281}
2282
2283/** FILE EVENT HOOKS
2284 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002285
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002286static void _event_file_prepare( EventHook hook )
2287{
2288 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2289 /* we can always read/write */
2290 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2291 }
2292}
2293
2294static int _event_file_peek( EventHook hook )
2295{
2296 return (hook->wanted & (FDE_READ|FDE_WRITE));
2297}
2298
2299static void _fh_file_hook( FH f, int events, EventHook hook )
2300{
2301 hook->h = f->fh_handle;
2302 hook->prepare = _event_file_prepare;
2303 hook->peek = _event_file_peek;
2304}
2305
2306/** SOCKET EVENT HOOKS
2307 **/
2308
2309static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2310{
2311 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2312 if (hook->wanted & FDE_READ)
2313 hook->ready |= FDE_READ;
2314 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2315 hook->ready |= FDE_ERROR;
2316 }
2317 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2318 if (hook->wanted & FDE_WRITE)
2319 hook->ready |= FDE_WRITE;
2320 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2321 hook->ready |= FDE_ERROR;
2322 }
2323 if ( evts->lNetworkEvents & FD_OOB ) {
2324 if (hook->wanted & FDE_ERROR)
2325 hook->ready |= FDE_ERROR;
2326 }
2327}
2328
2329static void _event_socket_prepare( EventHook hook )
2330{
2331 WSANETWORKEVENTS evts;
2332
2333 /* look if some of the events we want already happened ? */
2334 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2335 _event_socket_verify( hook, &evts );
2336}
2337
2338static int _socket_wanted_to_flags( int wanted )
2339{
2340 int flags = 0;
2341 if (wanted & FDE_READ)
2342 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2343
2344 if (wanted & FDE_WRITE)
2345 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2346
2347 if (wanted & FDE_ERROR)
2348 flags |= FD_OOB;
2349
2350 return flags;
2351}
2352
2353static int _event_socket_start( EventHook hook )
2354{
2355 /* create an event which we're going to wait for */
2356 FH fh = hook->fh;
2357 long flags = _socket_wanted_to_flags( hook->wanted );
2358
2359 hook->h = fh->event;
2360 if (hook->h == INVALID_HANDLE_VALUE) {
Yabin Cui815ad882015-09-02 17:44:28 -07002361 D( "_event_socket_start: no event for %s", fh->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002362 return 0;
2363 }
2364
2365 if ( flags != fh->mask ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002366 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 -08002367 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002368 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d", hook->fh->name, WSAGetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002369 CloseHandle( hook->h );
2370 hook->h = INVALID_HANDLE_VALUE;
2371 exit(1);
2372 return 0;
2373 }
2374 fh->mask = flags;
2375 }
2376 return 1;
2377}
2378
2379static void _event_socket_stop( EventHook hook )
2380{
2381 hook->h = INVALID_HANDLE_VALUE;
2382}
2383
2384static int _event_socket_check( EventHook hook )
2385{
2386 int result = 0;
2387 FH fh = hook->fh;
2388 WSANETWORKEVENTS evts;
2389
2390 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2391 _event_socket_verify( hook, &evts );
2392 result = (hook->ready != 0);
2393 if (result) {
2394 ResetEvent( hook->h );
2395 }
2396 }
Yabin Cui815ad882015-09-02 17:44:28 -07002397 D( "_event_socket_check %s returns %d", fh->name, result );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002398 return result;
2399}
2400
2401static int _event_socket_peek( EventHook hook )
2402{
2403 WSANETWORKEVENTS evts;
2404 FH fh = hook->fh;
2405
2406 /* look if some of the events we want already happened ? */
2407 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2408 _event_socket_verify( hook, &evts );
2409 if (hook->ready)
2410 ResetEvent( hook->h );
2411 }
2412
2413 return hook->ready != 0;
2414}
2415
2416
2417
2418static void _fh_socket_hook( FH f, int events, EventHook hook )
2419{
2420 hook->prepare = _event_socket_prepare;
2421 hook->start = _event_socket_start;
2422 hook->stop = _event_socket_stop;
2423 hook->check = _event_socket_check;
2424 hook->peek = _event_socket_peek;
2425
Spencer Low753d4852015-07-30 23:07:55 -07002426 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002427 _event_socket_start( hook );
2428}
2429
2430/** SOCKETPAIR EVENT HOOKS
2431 **/
2432
2433static void _event_socketpair_prepare( EventHook hook )
2434{
2435 FH fh = hook->fh;
2436 SocketPair pair = fh->fh_pair;
2437 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2438 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2439
2440 if (hook->wanted & FDE_READ && rbip->can_read)
2441 hook->ready |= FDE_READ;
2442
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002443 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002444 hook->ready |= FDE_WRITE;
2445 }
2446
2447 static int _event_socketpair_start( EventHook hook )
2448 {
2449 FH fh = hook->fh;
2450 SocketPair pair = fh->fh_pair;
2451 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2452 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2453
2454 if (hook->wanted == FDE_READ)
2455 hook->h = rbip->evt_read;
2456
2457 else if (hook->wanted == FDE_WRITE)
2458 hook->h = wbip->evt_write;
2459
2460 else {
Yabin Cui815ad882015-09-02 17:44:28 -07002461 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002462 return 0;
2463 }
Yabin Cui815ad882015-09-02 17:44:28 -07002464 D( "_event_socketpair_start: hook %s for %x wanted=%x",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002465 hook->fh->name, _fh_to_int(fh), hook->wanted);
2466 return 1;
2467}
2468
2469static int _event_socketpair_peek( EventHook hook )
2470{
2471 _event_socketpair_prepare( hook );
2472 return hook->ready != 0;
2473}
2474
2475static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2476{
2477 hook->prepare = _event_socketpair_prepare;
2478 hook->start = _event_socketpair_start;
2479 hook->peek = _event_socketpair_peek;
2480}
2481
2482
2483void
2484adb_sysdeps_init( void )
2485{
2486#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2487#include "mutex_list.h"
2488 InitializeCriticalSection( &_win32_lock );
2489}
2490
Spencer Lowbeb61982015-03-01 15:06:21 -08002491/**************************************************************************/
2492/**************************************************************************/
2493/***** *****/
2494/***** Console Window Terminal Emulation *****/
2495/***** *****/
2496/**************************************************************************/
2497/**************************************************************************/
2498
2499// This reads input from a Win32 console window and translates it into Unix
2500// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2501// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2502// is emulated instead of xterm because it is probably more popular than xterm:
2503// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2504// supports modern fonts, etc. It seems best to emulate the terminal that most
2505// Android developers use because they'll fix apps (the shell, etc.) to keep
2506// working with that terminal's emulation.
2507//
2508// The point of this emulation is not to be perfect or to solve all issues with
2509// console windows on Windows, but to be better than the original code which
2510// just called read() (which called ReadFile(), which called ReadConsoleA())
2511// which did not support Ctrl-C, tab completion, shell input line editing
2512// keys, server echo, and more.
2513//
2514// This implementation reconfigures the console with SetConsoleMode(), then
2515// calls ReadConsoleInput() to get raw input which it remaps to Unix
2516// terminal-style sequences which is returned via unix_read() which is used
2517// by the 'adb shell' command.
2518//
2519// Code organization:
2520//
David Pursell58805362015-10-28 14:29:51 -07002521// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08002522// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2523// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2524// * _console_read() is the main code of the emulation.
2525
David Pursell58805362015-10-28 14:29:51 -07002526// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
2527// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
2528// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
2529static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
2530 // First check isatty(); this is very fast and eliminates most non-console
2531 // FDs, but returns 1 for both consoles and character devices like NUL.
2532#pragma push_macro("isatty")
2533#undef isatty
2534 if (!isatty(fd)) {
2535 return nullptr;
2536 }
2537#pragma pop_macro("isatty")
2538
2539 // To differentiate between character devices and consoles we need to get
2540 // the underlying HANDLE and use GetConsoleMode(), which is what requires
2541 // GENERIC_READ permissions.
2542 const intptr_t intptr_handle = _get_osfhandle(fd);
2543 if (intptr_handle == -1) {
2544 return nullptr;
2545 }
2546 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
2547 DWORD temp_mode = 0;
2548 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
2549 return nullptr;
2550 }
2551
2552 return handle;
2553}
2554
2555// Returns a console handle if |stream| is a console, otherwise returns nullptr.
2556static HANDLE _get_console_handle(FILE* const stream) {
2557 const int fd = fileno(stream);
2558 if (fd < 0) {
2559 return nullptr;
2560 }
2561 return _get_console_handle(fd);
2562}
2563
2564int unix_isatty(int fd) {
2565 return _get_console_handle(fd) ? 1 : 0;
2566}
Spencer Lowbeb61982015-03-01 15:06:21 -08002567
Spencer Low9c8f7462015-11-10 19:17:16 -08002568// Get the next KEY_EVENT_RECORD that should be processed.
2569static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002570 for (;;) {
2571 DWORD read_count = 0;
2572 memset(input_record, 0, sizeof(*input_record));
2573 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08002574 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
2575 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002576 errno = EIO;
2577 return false;
2578 }
2579
2580 if (read_count == 0) { // should be impossible
2581 fatal("ReadConsoleInputA returned 0");
2582 }
2583
2584 if (read_count != 1) { // should be impossible
2585 fatal("ReadConsoleInputA did not return one input record");
2586 }
2587
2588 if ((input_record->EventType == KEY_EVENT) &&
2589 (input_record->Event.KeyEvent.bKeyDown)) {
2590 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2591 fatal("ReadConsoleInputA returned a key event with zero repeat"
2592 " count");
2593 }
2594
2595 // Got an interesting INPUT_RECORD, so return
2596 return true;
2597 }
2598 }
2599}
2600
Spencer Lowbeb61982015-03-01 15:06:21 -08002601static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2602 return (control_key_state & SHIFT_PRESSED) != 0;
2603}
2604
2605static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2606 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2607}
2608
2609static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2610 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2611}
2612
2613static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2614 return (control_key_state & NUMLOCK_ON) != 0;
2615}
2616
2617static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2618 return (control_key_state & CAPSLOCK_ON) != 0;
2619}
2620
2621static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2622 return (control_key_state & ENHANCED_KEY) != 0;
2623}
2624
2625// Constants from MSDN for ToAscii().
2626static const BYTE TOASCII_KEY_OFF = 0x00;
2627static const BYTE TOASCII_KEY_DOWN = 0x80;
2628static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2629
2630// Given a key event, ignore a modifier key and return the character that was
2631// entered without the modifier. Writes to *ch and returns the number of bytes
2632// written.
2633static size_t _get_char_ignoring_modifier(char* const ch,
2634 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2635 const WORD modifier) {
2636 // If there is no character from Windows, try ignoring the specified
2637 // modifier and look for a character. Note that if AltGr is being used,
2638 // there will be a character from Windows.
2639 if (key_event->uChar.AsciiChar == '\0') {
2640 // Note that we read the control key state from the passed in argument
2641 // instead of from key_event since the argument has been normalized.
2642 if (((modifier == VK_SHIFT) &&
2643 _is_shift_pressed(control_key_state)) ||
2644 ((modifier == VK_CONTROL) &&
2645 _is_ctrl_pressed(control_key_state)) ||
2646 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2647
2648 BYTE key_state[256] = {0};
2649 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2650 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2651 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2652 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2653 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2654 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2655 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2656 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2657
2658 // cause this modifier to be ignored
2659 key_state[modifier] = TOASCII_KEY_OFF;
2660
2661 WORD translated = 0;
2662 if (ToAscii(key_event->wVirtualKeyCode,
2663 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2664 // Ignoring the modifier, we found a character.
2665 *ch = (CHAR)translated;
2666 return 1;
2667 }
2668 }
2669 }
2670
2671 // Just use whatever Windows told us originally.
2672 *ch = key_event->uChar.AsciiChar;
2673
2674 // If the character from Windows is NULL, return a size of zero.
2675 return (*ch == '\0') ? 0 : 1;
2676}
2677
2678// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2679// but taking into account the shift key. This is because for a sequence like
2680// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2681// we want to find the character ')'.
2682//
2683// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2684// because it is the default key-sequence to switch the input language.
2685// This is configurable in the Region and Language control panel.
2686static __inline__ size_t _get_non_control_char(char* const ch,
2687 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2688 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2689 VK_CONTROL);
2690}
2691
2692// Get without Alt.
2693static __inline__ size_t _get_non_alt_char(char* const ch,
2694 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2695 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2696 VK_MENU);
2697}
2698
2699// Ignore the control key, find the character from Windows, and apply any
2700// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2701// *pch and returns number of bytes written.
2702static size_t _get_control_character(char* const pch,
2703 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2704 const size_t len = _get_non_control_char(pch, key_event,
2705 control_key_state);
2706
2707 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2708 char ch = *pch;
2709 switch (ch) {
2710 case '2':
2711 case '@':
2712 case '`':
2713 ch = '\0';
2714 break;
2715 case '3':
2716 case '[':
2717 case '{':
2718 ch = '\x1b';
2719 break;
2720 case '4':
2721 case '\\':
2722 case '|':
2723 ch = '\x1c';
2724 break;
2725 case '5':
2726 case ']':
2727 case '}':
2728 ch = '\x1d';
2729 break;
2730 case '6':
2731 case '^':
2732 case '~':
2733 ch = '\x1e';
2734 break;
2735 case '7':
2736 case '-':
2737 case '_':
2738 ch = '\x1f';
2739 break;
2740 case '8':
2741 ch = '\x7f';
2742 break;
2743 case '/':
2744 if (!_is_alt_pressed(control_key_state)) {
2745 ch = '\x1f';
2746 }
2747 break;
2748 case '?':
2749 if (!_is_alt_pressed(control_key_state)) {
2750 ch = '\x7f';
2751 }
2752 break;
2753 }
2754 *pch = ch;
2755 }
2756
2757 return len;
2758}
2759
2760static DWORD _normalize_altgr_control_key_state(
2761 const KEY_EVENT_RECORD* const key_event) {
2762 DWORD control_key_state = key_event->dwControlKeyState;
2763
2764 // If we're in an AltGr situation where the AltGr key is down (depending on
2765 // the keyboard layout, that might be the physical right alt key which
2766 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2767 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2768 // a character (which indicates that there was an AltGr mapping), then act
2769 // as if alt and control are not really down for the purposes of modifiers.
2770 // This makes it so that if the user with, say, a German keyboard layout
2771 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2772 // output the key and we don't see the Alt and Ctrl keys.
2773 if (_is_ctrl_pressed(control_key_state) &&
2774 _is_alt_pressed(control_key_state)
2775 && (key_event->uChar.AsciiChar != '\0')) {
2776 // Try to remove as few bits as possible to improve our chances of
2777 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2778 // Left-Alt + Right-Ctrl + AltGr.
2779 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2780 // Remove Right-Alt.
2781 control_key_state &= ~RIGHT_ALT_PRESSED;
2782 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2783 // pressed, Left-Ctrl is almost always set, except if the user
2784 // presses Right-Ctrl, then AltGr (in that specific order) for
2785 // whatever reason. At any rate, make sure the bit is not set.
2786 control_key_state &= ~LEFT_CTRL_PRESSED;
2787 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2788 // Remove Left-Alt.
2789 control_key_state &= ~LEFT_ALT_PRESSED;
2790 // Whichever Ctrl key is down, remove it from the state. We only
2791 // remove one key, to improve our chances of detecting the
2792 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2793 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2794 // Remove Left-Ctrl.
2795 control_key_state &= ~LEFT_CTRL_PRESSED;
2796 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2797 // Remove Right-Ctrl.
2798 control_key_state &= ~RIGHT_CTRL_PRESSED;
2799 }
2800 }
2801
2802 // Note that this logic isn't 100% perfect because Windows doesn't
2803 // allow us to detect all combinations because a physical AltGr key
2804 // press shows up as two bits, plus some combinations are ambiguous
2805 // about what is actually physically pressed.
2806 }
2807
2808 return control_key_state;
2809}
2810
2811// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2812// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2813// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2814// appropriately.
2815static DWORD _normalize_keypad_control_key_state(const WORD vk,
2816 const DWORD control_key_state) {
2817 if (!_is_numlock_on(control_key_state)) {
2818 return control_key_state;
2819 }
2820 if (!_is_enhanced_key(control_key_state)) {
2821 switch (vk) {
2822 case VK_INSERT: // 0
2823 case VK_DELETE: // .
2824 case VK_END: // 1
2825 case VK_DOWN: // 2
2826 case VK_NEXT: // 3
2827 case VK_LEFT: // 4
2828 case VK_CLEAR: // 5
2829 case VK_RIGHT: // 6
2830 case VK_HOME: // 7
2831 case VK_UP: // 8
2832 case VK_PRIOR: // 9
2833 return control_key_state | SHIFT_PRESSED;
2834 }
2835 }
2836
2837 return control_key_state;
2838}
2839
2840static const char* _get_keypad_sequence(const DWORD control_key_state,
2841 const char* const normal, const char* const shifted) {
2842 if (_is_shift_pressed(control_key_state)) {
2843 // Shift is pressed and NumLock is off
2844 return shifted;
2845 } else {
2846 // Shift is not pressed and NumLock is off, or,
2847 // Shift is pressed and NumLock is on, in which case we want the
2848 // NumLock and Shift to neutralize each other, thus, we want the normal
2849 // sequence.
2850 return normal;
2851 }
2852 // If Shift is not pressed and NumLock is on, a different virtual key code
2853 // is returned by Windows, which can be taken care of by a different case
2854 // statement in _console_read().
2855}
2856
2857// Write sequence to buf and return the number of bytes written.
2858static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2859 DWORD control_key_state, const char* const normal) {
2860 // Copy the base sequence into buf.
2861 const size_t len = strlen(normal);
2862 memcpy(buf, normal, len);
2863
2864 int code = 0;
2865
2866 control_key_state = _normalize_keypad_control_key_state(vk,
2867 control_key_state);
2868
2869 if (_is_shift_pressed(control_key_state)) {
2870 code |= 0x1;
2871 }
2872 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2873 code |= 0x2;
2874 }
2875 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2876 code |= 0x4;
2877 }
2878 // If some modifier was held down, then we need to insert the modifier code
2879 if (code != 0) {
2880 if (len == 0) {
2881 // Should be impossible because caller should pass a string of
2882 // non-zero length.
2883 return 0;
2884 }
2885 size_t index = len - 1;
2886 const char lastChar = buf[index];
2887 if (lastChar != '~') {
2888 buf[index++] = '1';
2889 }
2890 buf[index++] = ';'; // modifier separator
2891 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2892 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2893 buf[index++] = '1' + code;
2894 buf[index++] = lastChar; // move ~ (or other last char) to the end
2895 return index;
2896 }
2897 return len;
2898}
2899
2900// Write sequence to buf and return the number of bytes written.
2901static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2902 const DWORD control_key_state, const char* const normal,
2903 const char shifted) {
2904 if (_is_shift_pressed(control_key_state)) {
2905 // Shift is pressed and NumLock is off
2906 if (shifted != '\0') {
2907 buf[0] = shifted;
2908 return sizeof(buf[0]);
2909 } else {
2910 return 0;
2911 }
2912 } else {
2913 // Shift is not pressed and NumLock is off, or,
2914 // Shift is pressed and NumLock is on, in which case we want the
2915 // NumLock and Shift to neutralize each other, thus, we want the normal
2916 // sequence.
2917 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2918 }
2919 // If Shift is not pressed and NumLock is on, a different virtual key code
2920 // is returned by Windows, which can be taken care of by a different case
2921 // statement in _console_read().
2922}
2923
2924// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2925// Standard German. Figure this out at runtime so we know what to output for
2926// Shift-VK_DELETE.
2927static char _get_decimal_char() {
2928 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2929}
2930
2931// Prefix the len bytes in buf with the escape character, and then return the
2932// new buffer length.
2933size_t _escape_prefix(char* const buf, const size_t len) {
2934 // If nothing to prefix, don't do anything. We might be called with
2935 // len == 0, if alt was held down with a dead key which produced nothing.
2936 if (len == 0) {
2937 return 0;
2938 }
2939
2940 memmove(&buf[1], buf, len);
2941 buf[0] = '\x1b';
2942 return len + 1;
2943}
2944
Spencer Low9c8f7462015-11-10 19:17:16 -08002945// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002946static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08002947
2948// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
2949// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08002950static int _console_read(const HANDLE console, void* buf, size_t len) {
2951 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08002952 // Read of zero bytes should not block waiting for something from the console.
2953 if (len == 0) {
2954 return 0;
2955 }
2956
2957 // Flush as much as possible from input buffer.
2958 if (!g_console_input_buffer.empty()) {
2959 const int bytes_read = std::min(len, g_console_input_buffer.size());
2960 memcpy(buf, g_console_input_buffer.data(), bytes_read);
2961 const auto begin = g_console_input_buffer.begin();
2962 g_console_input_buffer.erase(begin, begin + bytes_read);
2963 return bytes_read;
2964 }
2965
2966 // Read from the actual console. This may block until input.
2967 INPUT_RECORD input_record;
2968 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002969 return -1;
2970 }
2971
Spencer Low9c8f7462015-11-10 19:17:16 -08002972 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08002973 const WORD vk = key_event->wVirtualKeyCode;
2974 const CHAR ch = key_event->uChar.AsciiChar;
2975 const DWORD control_key_state = _normalize_altgr_control_key_state(
2976 key_event);
2977
2978 // The following emulation code should write the output sequence to
2979 // either seqstr or to seqbuf and seqbuflen.
2980 const char* seqstr = NULL; // NULL terminated C-string
2981 // Enough space for max sequence string below, plus modifiers and/or
2982 // escape prefix.
2983 char seqbuf[16];
2984 size_t seqbuflen = 0; // Space used in seqbuf.
2985
2986#define MATCH(vk, normal) \
2987 case (vk): \
2988 { \
2989 seqstr = (normal); \
2990 } \
2991 break;
2992
2993 // Modifier keys should affect the output sequence.
2994#define MATCH_MODIFIER(vk, normal) \
2995 case (vk): \
2996 { \
2997 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2998 control_key_state, (normal)); \
2999 } \
3000 break;
3001
3002 // The shift key should affect the output sequence.
3003#define MATCH_KEYPAD(vk, normal, shifted) \
3004 case (vk): \
3005 { \
3006 seqstr = _get_keypad_sequence(control_key_state, (normal), \
3007 (shifted)); \
3008 } \
3009 break;
3010
3011 // The shift key and other modifier keys should affect the output
3012 // sequence.
3013#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
3014 case (vk): \
3015 { \
3016 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
3017 control_key_state, (normal), (shifted)); \
3018 } \
3019 break;
3020
3021#define ESC "\x1b"
3022#define CSI ESC "["
3023#define SS3 ESC "O"
3024
3025 // Only support normal mode, not application mode.
3026
3027 // Enhanced keys:
3028 // * 6-pack: insert, delete, home, end, page up, page down
3029 // * cursor keys: up, down, right, left
3030 // * keypad: divide, enter
3031 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
3032 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
3033 if (_is_enhanced_key(control_key_state)) {
3034 switch (vk) {
3035 case VK_RETURN: // Enter key on keypad
3036 if (_is_ctrl_pressed(control_key_state)) {
3037 seqstr = "\n";
3038 } else {
3039 seqstr = "\r";
3040 }
3041 break;
3042
3043 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
3044 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
3045
3046 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
3047 // will be fixed soon to match xterm which sends CSI "F" and
3048 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
3049 MATCH(VK_END, CSI "F");
3050 MATCH(VK_HOME, CSI "H");
3051
3052 MATCH_MODIFIER(VK_LEFT, CSI "D");
3053 MATCH_MODIFIER(VK_UP, CSI "A");
3054 MATCH_MODIFIER(VK_RIGHT, CSI "C");
3055 MATCH_MODIFIER(VK_DOWN, CSI "B");
3056
3057 MATCH_MODIFIER(VK_INSERT, CSI "2~");
3058 MATCH_MODIFIER(VK_DELETE, CSI "3~");
3059
3060 MATCH(VK_DIVIDE, "/");
3061 }
3062 } else { // Non-enhanced keys:
3063 switch (vk) {
3064 case VK_BACK: // backspace
3065 if (_is_alt_pressed(control_key_state)) {
3066 seqstr = ESC "\x7f";
3067 } else {
3068 seqstr = "\x7f";
3069 }
3070 break;
3071
3072 case VK_TAB:
3073 if (_is_shift_pressed(control_key_state)) {
3074 seqstr = CSI "Z";
3075 } else {
3076 seqstr = "\t";
3077 }
3078 break;
3079
3080 // Number 5 key in keypad when NumLock is off, or if NumLock is
3081 // on and Shift is down.
3082 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
3083
3084 case VK_RETURN: // Enter key on main keyboard
3085 if (_is_alt_pressed(control_key_state)) {
3086 seqstr = ESC "\n";
3087 } else if (_is_ctrl_pressed(control_key_state)) {
3088 seqstr = "\n";
3089 } else {
3090 seqstr = "\r";
3091 }
3092 break;
3093
3094 // VK_ESCAPE: Don't do any special handling. The OS uses many
3095 // of the sequences with Escape and many of the remaining
3096 // sequences don't produce bKeyDown messages, only !bKeyDown
3097 // for whatever reason.
3098
3099 case VK_SPACE:
3100 if (_is_alt_pressed(control_key_state)) {
3101 seqstr = ESC " ";
3102 } else if (_is_ctrl_pressed(control_key_state)) {
3103 seqbuf[0] = '\0'; // NULL char
3104 seqbuflen = 1;
3105 } else {
3106 seqstr = " ";
3107 }
3108 break;
3109
3110 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
3111 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
3112
3113 MATCH_KEYPAD(VK_END, CSI "4~", "1");
3114 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
3115
3116 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
3117 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
3118 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
3119 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
3120
3121 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
3122 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
3123 _get_decimal_char());
3124
3125 case 0x30: // 0
3126 case 0x31: // 1
3127 case 0x39: // 9
3128 case VK_OEM_1: // ;:
3129 case VK_OEM_PLUS: // =+
3130 case VK_OEM_COMMA: // ,<
3131 case VK_OEM_PERIOD: // .>
3132 case VK_OEM_7: // '"
3133 case VK_OEM_102: // depends on keyboard, could be <> or \|
3134 case VK_OEM_2: // /?
3135 case VK_OEM_3: // `~
3136 case VK_OEM_4: // [{
3137 case VK_OEM_5: // \|
3138 case VK_OEM_6: // ]}
3139 {
3140 seqbuflen = _get_control_character(seqbuf, key_event,
3141 control_key_state);
3142
3143 if (_is_alt_pressed(control_key_state)) {
3144 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3145 }
3146 }
3147 break;
3148
3149 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08003150 case 0x33: // 3
3151 case 0x34: // 4
3152 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08003153 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08003154 case 0x37: // 7
3155 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08003156 case VK_OEM_MINUS: // -_
3157 {
3158 seqbuflen = _get_control_character(seqbuf, key_event,
3159 control_key_state);
3160
3161 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3162 // prefix with escape.
3163 if (_is_alt_pressed(control_key_state) &&
3164 !(_is_ctrl_pressed(control_key_state) &&
3165 !_is_shift_pressed(control_key_state))) {
3166 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3167 }
3168 }
3169 break;
3170
Spencer Lowbeb61982015-03-01 15:06:21 -08003171 case 0x41: // a
3172 case 0x42: // b
3173 case 0x43: // c
3174 case 0x44: // d
3175 case 0x45: // e
3176 case 0x46: // f
3177 case 0x47: // g
3178 case 0x48: // h
3179 case 0x49: // i
3180 case 0x4a: // j
3181 case 0x4b: // k
3182 case 0x4c: // l
3183 case 0x4d: // m
3184 case 0x4e: // n
3185 case 0x4f: // o
3186 case 0x50: // p
3187 case 0x51: // q
3188 case 0x52: // r
3189 case 0x53: // s
3190 case 0x54: // t
3191 case 0x55: // u
3192 case 0x56: // v
3193 case 0x57: // w
3194 case 0x58: // x
3195 case 0x59: // y
3196 case 0x5a: // z
3197 {
3198 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3199 control_key_state);
3200
3201 // If Alt is pressed, then prefix with escape.
3202 if (_is_alt_pressed(control_key_state)) {
3203 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3204 }
3205 }
3206 break;
3207
3208 // These virtual key codes are generated by the keys on the
3209 // keypad *when NumLock is on* and *Shift is up*.
3210 MATCH(VK_NUMPAD0, "0");
3211 MATCH(VK_NUMPAD1, "1");
3212 MATCH(VK_NUMPAD2, "2");
3213 MATCH(VK_NUMPAD3, "3");
3214 MATCH(VK_NUMPAD4, "4");
3215 MATCH(VK_NUMPAD5, "5");
3216 MATCH(VK_NUMPAD6, "6");
3217 MATCH(VK_NUMPAD7, "7");
3218 MATCH(VK_NUMPAD8, "8");
3219 MATCH(VK_NUMPAD9, "9");
3220
3221 MATCH(VK_MULTIPLY, "*");
3222 MATCH(VK_ADD, "+");
3223 MATCH(VK_SUBTRACT, "-");
3224 // VK_DECIMAL is generated by the . key on the keypad *when
3225 // NumLock is on* and *Shift is up* and the sequence is not
3226 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3227 // Windows Security screen to come up).
3228 case VK_DECIMAL:
3229 // U.S. English uses '.', Germany German uses ','.
3230 seqbuflen = _get_non_control_char(seqbuf, key_event,
3231 control_key_state);
3232 break;
3233
3234 MATCH_MODIFIER(VK_F1, SS3 "P");
3235 MATCH_MODIFIER(VK_F2, SS3 "Q");
3236 MATCH_MODIFIER(VK_F3, SS3 "R");
3237 MATCH_MODIFIER(VK_F4, SS3 "S");
3238 MATCH_MODIFIER(VK_F5, CSI "15~");
3239 MATCH_MODIFIER(VK_F6, CSI "17~");
3240 MATCH_MODIFIER(VK_F7, CSI "18~");
3241 MATCH_MODIFIER(VK_F8, CSI "19~");
3242 MATCH_MODIFIER(VK_F9, CSI "20~");
3243 MATCH_MODIFIER(VK_F10, CSI "21~");
3244 MATCH_MODIFIER(VK_F11, CSI "23~");
3245 MATCH_MODIFIER(VK_F12, CSI "24~");
3246
3247 MATCH_MODIFIER(VK_F13, CSI "25~");
3248 MATCH_MODIFIER(VK_F14, CSI "26~");
3249 MATCH_MODIFIER(VK_F15, CSI "28~");
3250 MATCH_MODIFIER(VK_F16, CSI "29~");
3251 MATCH_MODIFIER(VK_F17, CSI "31~");
3252 MATCH_MODIFIER(VK_F18, CSI "32~");
3253 MATCH_MODIFIER(VK_F19, CSI "33~");
3254 MATCH_MODIFIER(VK_F20, CSI "34~");
3255
3256 // MATCH_MODIFIER(VK_F21, ???);
3257 // MATCH_MODIFIER(VK_F22, ???);
3258 // MATCH_MODIFIER(VK_F23, ???);
3259 // MATCH_MODIFIER(VK_F24, ???);
3260 }
3261 }
3262
3263#undef MATCH
3264#undef MATCH_MODIFIER
3265#undef MATCH_KEYPAD
3266#undef MATCH_MODIFIER_KEYPAD
3267#undef ESC
3268#undef CSI
3269#undef SS3
3270
3271 const char* out;
3272 size_t outlen;
3273
3274 // Check for output in any of:
3275 // * seqstr is set (and strlen can be used to determine the length).
3276 // * seqbuf and seqbuflen are set
3277 // Fallback to ch from Windows.
3278 if (seqstr != NULL) {
3279 out = seqstr;
3280 outlen = strlen(seqstr);
3281 } else if (seqbuflen > 0) {
3282 out = seqbuf;
3283 outlen = seqbuflen;
3284 } else if (ch != '\0') {
3285 // Use whatever Windows told us it is.
3286 seqbuf[0] = ch;
3287 seqbuflen = 1;
3288 out = seqbuf;
3289 outlen = seqbuflen;
3290 } else {
3291 // No special handling for the virtual key code and Windows isn't
3292 // telling us a character code, then we don't know how to translate
3293 // the key press.
3294 //
3295 // Consume the input and 'continue' to cause us to get a new key
3296 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07003297 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08003298 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08003299 continue;
3300 }
3301
Spencer Low9c8f7462015-11-10 19:17:16 -08003302 // put output wRepeatCount times into g_console_input_buffer
3303 while (key_event->wRepeatCount-- > 0) {
3304 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08003305 }
3306
Spencer Low9c8f7462015-11-10 19:17:16 -08003307 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08003308 }
3309}
3310
3311static DWORD _old_console_mode; // previous GetConsoleMode() result
3312static HANDLE _console_handle; // when set, console mode should be restored
3313
Elliott Hughesa8265792015-11-03 11:18:40 -08003314void stdin_raw_init() {
3315 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowbeb61982015-03-01 15:06:21 -08003316
Elliott Hughesa8265792015-11-03 11:18:40 -08003317 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3318 // calling the process Ctrl-C routine (configured by
3319 // SetConsoleCtrlHandler()).
3320 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3321 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3322 // flag also seems necessary to have proper line-ending processing.
3323 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3324 ENABLE_LINE_INPUT |
3325 ENABLE_ECHO_INPUT))) {
3326 // This really should not fail.
3327 D("stdin_raw_init: SetConsoleMode() failed: %s",
3328 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003329 }
Elliott Hughesa8265792015-11-03 11:18:40 -08003330
3331 // Once this is set, it means that stdin has been configured for
3332 // reading from and that the old console mode should be restored later.
3333 _console_handle = in;
3334
3335 // Note that we don't need to configure C Runtime line-ending
3336 // translation because _console_read() does not call the C Runtime to
3337 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08003338}
3339
Elliott Hughesa8265792015-11-03 11:18:40 -08003340void stdin_raw_restore() {
3341 if (_console_handle != NULL) {
3342 const HANDLE in = _console_handle;
3343 _console_handle = NULL; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08003344
Elliott Hughesa8265792015-11-03 11:18:40 -08003345 if (!SetConsoleMode(in, _old_console_mode)) {
3346 // This really should not fail.
3347 D("stdin_raw_restore: SetConsoleMode() failed: %s",
3348 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003349 }
3350 }
3351}
3352
Spencer Low3a2421b2015-05-22 20:09:06 -07003353// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003354int unix_read(int fd, void* buf, size_t len) {
3355 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3356 // If it is a request to read from stdin, and stdin_raw_init() has been
3357 // called, and it successfully configured the console, then read from
3358 // the console using Win32 console APIs and partially emulate a unix
3359 // terminal.
3360 return _console_read(_console_handle, buf, len);
3361 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07003362 // On older versions of Windows (definitely 7, definitely not 10),
3363 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07003364 // we need to limit the read size.
3365 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07003366 len = 4096;
3367 }
Spencer Lowbeb61982015-03-01 15:06:21 -08003368 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003369 // can do LF/CR translation (which is overridable with _setmode()).
3370 // Undefine the macro that is set in sysdeps.h which bans calls to
3371 // plain read() in favor of unix_read() or adb_read().
3372#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003373#undef read
3374 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003375#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003376 }
3377}
Spencer Low6815c072015-05-11 01:08:48 -07003378
3379/**************************************************************************/
3380/**************************************************************************/
3381/***** *****/
3382/***** Unicode support *****/
3383/***** *****/
3384/**************************************************************************/
3385/**************************************************************************/
3386
3387// This implements support for using files with Unicode filenames and for
3388// outputting Unicode text to a Win32 console window. This is inspired from
3389// http://utf8everywhere.org/.
3390//
3391// Background
3392// ----------
3393//
3394// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3395// filenames to APIs such as open(). This works because filenames are largely
3396// opaque 'cookies' (perhaps excluding path separators).
3397//
3398// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3399// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3400// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3401// CreateFile() API is really just a macro that adds the W/A based on whether
3402// the UNICODE preprocessor symbol is defined).
3403//
3404// Options
3405// -------
3406//
3407// Thus, to write a portable program, there are a few options:
3408//
3409// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3410// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3411// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3412// open() API.
3413//
3414// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3415// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3416// potentially touching a lot of code.
3417//
3418// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3419// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3420// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3421// or C Runtime API.
3422//
3423// The Choice
3424// ----------
3425//
Spencer Low50f5bf12015-11-12 15:20:15 -08003426// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
3427// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07003428// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08003429// args that are passed to main() at the beginning of program startup. We also use
3430// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07003431// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3432//
3433// Unicode console output
3434// ----------------------
3435//
3436// The way to output Unicode to a Win32 console window is to call
3437// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003438// such as Lucida Console or Consolas, and in the case of East Asian languages
3439// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3440// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3441// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003442//
3443// The problem is getting the C Runtime to make fprintf and related APIs call
3444// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3445// promising, but the various modes have issues:
3446//
3447// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3448// UTF-16 do not display properly.
3449// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3450// totally wrong.
3451// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3452// handler to be called (upon a later I/O call), aborting the process.
3453// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3454// to output nothing.
3455//
3456// So the only solution is to write our own adb_fprintf() that converts UTF-8
3457// to UTF-16 and then calls WriteConsoleW().
3458
3459
Spencer Low6815c072015-05-11 01:08:48 -07003460// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3461// be passed to main().
3462NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3463 narrow_args = new char*[argc + 1];
3464
3465 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003466 std::string arg_narrow;
3467 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
3468 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
3469 }
3470 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003471 }
3472 narrow_args[argc] = nullptr; // terminate
3473}
3474
3475NarrowArgs::~NarrowArgs() {
3476 if (narrow_args != nullptr) {
3477 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3478 free(*argp);
3479 }
3480 delete[] narrow_args;
3481 narrow_args = nullptr;
3482 }
3483}
3484
3485int unix_open(const char* path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003486 std::wstring path_wide;
3487 if (!android::base::UTF8ToWide(path, &path_wide)) {
3488 return -1;
3489 }
Spencer Low6815c072015-05-11 01:08:48 -07003490 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003491 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07003492 } else {
3493 int mode;
3494 va_list args;
3495 va_start(args, options);
3496 mode = va_arg(args, int);
3497 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08003498 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07003499 }
3500}
3501
3502// Version of stat() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08003503int adb_stat(const char* path, struct adb_stat* s) {
Spencer Low6815c072015-05-11 01:08:48 -07003504#pragma push_macro("wstat")
3505// This definition of wstat seems to be missing from <sys/stat.h>.
3506#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3507#ifdef _USE_32BIT_TIME_T
3508#define wstat _wstat32i64
3509#else
3510#define wstat _wstat64
3511#endif
3512#else
3513// <sys/stat.h> has a function prototype for wstat() that should be available.
3514#endif
3515
Spencer Low50f5bf12015-11-12 15:20:15 -08003516 std::wstring path_wide;
3517 if (!android::base::UTF8ToWide(path, &path_wide)) {
3518 return -1;
3519 }
3520
3521 return wstat(path_wide.c_str(), s);
Spencer Low6815c072015-05-11 01:08:48 -07003522
3523#pragma pop_macro("wstat")
3524}
3525
3526// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08003527DIR* adb_opendir(const char* path) {
3528 std::wstring path_wide;
3529 if (!android::base::UTF8ToWide(path, &path_wide)) {
3530 return nullptr;
3531 }
3532
Spencer Low6815c072015-05-11 01:08:48 -07003533 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3534 // the fields, but right now all the callers treat the structure as
3535 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08003536 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07003537}
3538
3539// Version of readdir() that returns UTF-8 paths.
3540struct dirent* adb_readdir(DIR* dir) {
3541 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3542 struct _wdirent* const went = _wreaddir(wdir);
3543 if (went == nullptr) {
3544 return nullptr;
3545 }
Spencer Low50f5bf12015-11-12 15:20:15 -08003546
Spencer Low6815c072015-05-11 01:08:48 -07003547 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08003548 std::string name_utf8;
3549 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
3550 return nullptr;
3551 }
Spencer Low6815c072015-05-11 01:08:48 -07003552
3553 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3554 // space for UTF-16 wchar_t's) with UTF-8 char's.
3555 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3556
3557 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3558 // Name too big to fit in existing buffer.
3559 errno = ENOMEM;
3560 return nullptr;
3561 }
3562
3563 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3564 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3565 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3566 // bigger than the caller expects because they expect a dirent structure
3567 // which has a smaller d_name field. Ignore this since the caller should be
3568 // resilient.
3569
3570 // Rewrite the UTF-16 d_name field to UTF-8.
3571 strcpy(ent->d_name, name_utf8.c_str());
3572
3573 return ent;
3574}
3575
3576// Version of closedir() to go with our version of adb_opendir().
3577int adb_closedir(DIR* dir) {
3578 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3579}
3580
3581// Version of unlink() that takes a UTF-8 path.
3582int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003583 std::wstring wpath;
3584 if (!android::base::UTF8ToWide(path, &wpath)) {
3585 return -1;
3586 }
Spencer Low6815c072015-05-11 01:08:48 -07003587
3588 int rc = _wunlink(wpath.c_str());
3589
3590 if (rc == -1 && errno == EACCES) {
3591 /* unlink returns EACCES when the file is read-only, so we first */
3592 /* try to make it writable, then unlink again... */
3593 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3594 if (rc == 0)
3595 rc = _wunlink(wpath.c_str());
3596 }
3597 return rc;
3598}
3599
3600// Version of mkdir() that takes a UTF-8 path.
3601int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003602 std::wstring path_wide;
3603 if (!android::base::UTF8ToWide(path, &path_wide)) {
3604 return -1;
3605 }
3606
3607 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003608}
3609
3610// Version of utime() that takes a UTF-8 path.
3611int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003612 std::wstring path_wide;
3613 if (!android::base::UTF8ToWide(path, &path_wide)) {
3614 return -1;
3615 }
3616
Spencer Low6815c072015-05-11 01:08:48 -07003617 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3618 "utimbuf and _utimbuf should be the same size because they both "
3619 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08003620 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07003621}
3622
3623// Version of chmod() that takes a UTF-8 path.
3624int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08003625 std::wstring path_wide;
3626 if (!android::base::UTF8ToWide(path, &path_wide)) {
3627 return -1;
3628 }
3629
3630 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07003631}
3632
Spencer Low6815c072015-05-11 01:08:48 -07003633// Internal helper function to write UTF-8 bytes to a console. Returns -1
3634// on error.
3635static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3636 HANDLE console) {
Elliott Hughes37be38a2015-11-11 18:02:29 +00003637 std::wstring output;
3638
3639 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors.
3640 // Data might not be UTF-8 if the user cat's random data, runs dmesg, etc.
Spencer Low6815c072015-05-11 01:08:48 -07003641 // This could throw std::bad_alloc.
Elliott Hughes37be38a2015-11-11 18:02:29 +00003642 (void)android::base::UTF8ToWide(buf, size, &output);
Spencer Low6815c072015-05-11 01:08:48 -07003643
3644 // Note that this does not do \n => \r\n translation because that
3645 // doesn't seem necessary for the Windows console. For the Windows
3646 // console \r moves to the beginning of the line and \n moves to a new
3647 // line.
3648
3649 // Flush any stream buffering so that our output is afterwards which
3650 // makes sense because our call is afterwards.
3651 (void)fflush(stream);
3652
3653 // Write UTF-16 to the console.
3654 DWORD written = 0;
3655 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3656 NULL)) {
3657 errno = EIO;
3658 return -1;
3659 }
3660
3661 // This is the number of UTF-16 chars written, which might be different
3662 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3663 // get this count correct.
3664 return written;
3665}
3666
3667// Function prototype because attributes cannot be placed on func definitions.
3668static int _console_vfprintf(const HANDLE console, FILE* stream,
3669 const char *format, va_list ap)
3670 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3671
3672// Internal function to format a UTF-8 string and write it to a Win32 console.
3673// Returns -1 on error.
3674static int _console_vfprintf(const HANDLE console, FILE* stream,
3675 const char *format, va_list ap) {
3676 std::string output_utf8;
3677
3678 // Format the string.
3679 // This could throw std::bad_alloc.
3680 android::base::StringAppendV(&output_utf8, format, ap);
3681
3682 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3683 stream, console);
3684}
3685
3686// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3687// Windows console.
3688int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3689 const HANDLE console = _get_console_handle(stream);
3690
3691 // If there is an associated Win32 console, write to it specially,
3692 // otherwise defer to the regular C Runtime, passing it UTF-8.
3693 if (console != NULL) {
3694 return _console_vfprintf(console, stream, format, ap);
3695 } else {
3696 // If vfprintf is a macro, undefine it, so we can call the real
3697 // C Runtime API.
3698#pragma push_macro("vfprintf")
3699#undef vfprintf
3700 return vfprintf(stream, format, ap);
3701#pragma pop_macro("vfprintf")
3702 }
3703}
3704
3705// Version of fprintf() that takes UTF-8 and can write Unicode to a
3706// Windows console.
3707int adb_fprintf(FILE *stream, const char *format, ...) {
3708 va_list ap;
3709 va_start(ap, format);
3710 const int result = adb_vfprintf(stream, format, ap);
3711 va_end(ap);
3712
3713 return result;
3714}
3715
3716// Version of printf() that takes UTF-8 and can write Unicode to a
3717// Windows console.
3718int adb_printf(const char *format, ...) {
3719 va_list ap;
3720 va_start(ap, format);
3721 const int result = adb_vfprintf(stdout, format, ap);
3722 va_end(ap);
3723
3724 return result;
3725}
3726
3727// Version of fputs() that takes UTF-8 and can write Unicode to a
3728// Windows console.
3729int adb_fputs(const char* buf, FILE* stream) {
3730 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3731 // which fputs (and hence adb_fputs) should return on error.
3732 return adb_fprintf(stream, "%s", buf);
3733}
3734
3735// Version of fputc() that takes UTF-8 and can write Unicode to a
3736// Windows console.
3737int adb_fputc(int ch, FILE* stream) {
3738 const int result = adb_fprintf(stream, "%c", ch);
3739 if (result <= 0) {
3740 // If there was an error, or if nothing was printed (which should be an
3741 // error), return an error, which fprintf signifies with EOF.
3742 return EOF;
3743 }
3744 // For success, fputc returns the char, cast to unsigned char, then to int.
3745 return static_cast<unsigned char>(ch);
3746}
3747
3748// Internal function to write UTF-8 to a Win32 console. Returns the number of
3749// items (of length size) written. On error, returns a short item count or 0.
3750static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3751 FILE* stream, HANDLE console) {
3752 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3753 // if we're passed only some of the bytes of a character (for example, from
3754 // the network socket for adb shell), we won't be able to convert the char
3755 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3756 // right.
3757 //
3758 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3759 //
3760 // For now we ignore this problem because the alternative is that we'd have
3761 // to parse UTF-8 and buffer things up (doable). At least this is better
3762 // than what we had before -- always incorrect multi-byte UTF-8 output.
3763 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3764 size * nmemb, stream, console);
3765 if (result == -1) {
3766 return 0;
3767 }
3768 return result / size;
3769}
3770
3771// Version of fwrite() that takes UTF-8 and can write Unicode to a
3772// Windows console.
3773size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3774 const HANDLE console = _get_console_handle(stream);
3775
3776 // If there is an associated Win32 console, write to it specially,
3777 // otherwise defer to the regular C Runtime, passing it UTF-8.
3778 if (console != NULL) {
3779 return _console_fwrite(ptr, size, nmemb, stream, console);
3780 } else {
3781 // If fwrite is a macro, undefine it, so we can call the real
3782 // C Runtime API.
3783#pragma push_macro("fwrite")
3784#undef fwrite
3785 return fwrite(ptr, size, nmemb, stream);
3786#pragma pop_macro("fwrite")
3787 }
3788}
3789
3790// Version of fopen() that takes a UTF-8 filename and can access a file with
3791// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08003792FILE* adb_fopen(const char* path, const char* mode) {
3793 std::wstring path_wide;
3794 if (!android::base::UTF8ToWide(path, &path_wide)) {
3795 return nullptr;
3796 }
3797
3798 std::wstring mode_wide;
3799 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
3800 return nullptr;
3801 }
3802
3803 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003804}
3805
Spencer Low50740f52015-09-08 17:13:04 -07003806// Return a lowercase version of the argument. Uses C Runtime tolower() on
3807// each byte which is not UTF-8 aware, and theoretically uses the current C
3808// Runtime locale (which in practice is not changed, so this becomes a ASCII
3809// conversion).
3810static std::string ToLower(const std::string& anycase) {
3811 // copy string
3812 std::string str(anycase);
3813 // transform the copy
3814 std::transform(str.begin(), str.end(), str.begin(), tolower);
3815 return str;
3816}
3817
3818extern "C" int main(int argc, char** argv);
3819
3820// Link with -municode to cause this wmain() to be used as the program
3821// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3822// regular main() with UTF-8 args.
3823extern "C" int wmain(int argc, wchar_t **argv) {
3824 // Convert args from UTF-16 to UTF-8 and pass that to main().
3825 NarrowArgs narrow_args(argc, argv);
3826 return main(argc, narrow_args.data());
3827}
3828
Spencer Low6815c072015-05-11 01:08:48 -07003829// Shadow UTF-8 environment variable name/value pairs that are created from
3830// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003831// currently updated if putenv, setenv, unsetenv are called. Note that no
3832// thread synchronization is done, but we're called early enough in
3833// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08003834static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07003835
3836// Make sure that shadow UTF-8 environment variables are setup.
3837static void _ensure_env_setup() {
3838 // If some name/value pairs exist, then we've already done the setup below.
3839 if (g_environ_utf8.size() != 0) {
3840 return;
3841 }
3842
Spencer Low50740f52015-09-08 17:13:04 -07003843 if (_wenviron == nullptr) {
3844 // If _wenviron is null, then -municode probably wasn't used. That
3845 // linker flag will cause the entry point to setup _wenviron. It will
3846 // also require an implementation of wmain() (which we provide above).
3847 fatal("_wenviron is not set, did you link with -municode?");
3848 }
3849
Spencer Low6815c072015-05-11 01:08:48 -07003850 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3851 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3852 // to use the D() macro here because that tracing only works if the
3853 // ADB_TRACE environment variable is setup, but that env var can't be read
3854 // until this code completes.
3855 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3856 wchar_t* const equal = wcschr(*env, L'=');
3857 if (equal == nullptr) {
3858 // Malformed environment variable with no equal sign. Shouldn't
3859 // really happen, but we should be resilient to this.
3860 continue;
3861 }
3862
Spencer Low50f5bf12015-11-12 15:20:15 -08003863 // If we encounter an error converting UTF-16, don't error-out on account of a single env
3864 // var because the program might never even read this particular variable.
3865 std::string name_utf8;
3866 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
3867 continue;
3868 }
3869
Spencer Low50740f52015-09-08 17:13:04 -07003870 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08003871 name_utf8 = ToLower(name_utf8);
3872
3873 std::string value_utf8;
3874 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
3875 continue;
3876 }
3877
3878 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07003879
Spencer Low50740f52015-09-08 17:13:04 -07003880 // Don't overwrite a previus env var with the same name. In reality,
3881 // the system probably won't let two env vars with the same name exist
3882 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08003883 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07003884 }
3885}
3886
3887// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07003888// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07003889char* adb_getenv(const char* name) {
3890 _ensure_env_setup();
3891
Spencer Low50740f52015-09-08 17:13:04 -07003892 // Case-insensitive search by searching for lowercase name in a map of
3893 // lowercase names.
3894 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07003895 if (it == g_environ_utf8.end()) {
3896 return nullptr;
3897 }
3898
3899 return it->second;
3900}
3901
3902// Version of getcwd() that returns the current working directory in UTF-8.
3903char* adb_getcwd(char* buf, int size) {
3904 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3905 if (wbuf == nullptr) {
3906 return nullptr;
3907 }
3908
Spencer Low50f5bf12015-11-12 15:20:15 -08003909 std::string buf_utf8;
3910 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07003911 free(wbuf);
3912 wbuf = nullptr;
3913
Spencer Low50f5bf12015-11-12 15:20:15 -08003914 if (!narrow_result) {
3915 return nullptr;
3916 }
3917
Spencer Low6815c072015-05-11 01:08:48 -07003918 // If size was specified, make sure all the chars will fit.
3919 if (size != 0) {
3920 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3921 errno = ERANGE;
3922 return nullptr;
3923 }
3924 }
3925
3926 // If buf was not specified, allocate storage.
3927 if (buf == nullptr) {
3928 if (size == 0) {
3929 size = buf_utf8.length() + 1;
3930 }
3931 buf = reinterpret_cast<char*>(malloc(size));
3932 if (buf == nullptr) {
3933 return nullptr;
3934 }
3935 }
3936
3937 // Destination buffer was allocated with enough space, or we've already
3938 // checked an existing buffer size for enough space.
3939 strcpy(buf, buf_utf8.c_str());
3940
3941 return buf;
3942}