blob: b53cd77229af9c9cd8f4265fa8f45d6a7f2631a3 [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
17#define TRACE_TAG TRACE_SYSDEPS
18
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 Low753d4852015-07-30 23:07:55 -070028#include <memory>
29#include <string>
Spencer Low6815c072015-05-11 01:08:48 -070030#include <unordered_map>
Spencer Low753d4852015-07-30 23:07:55 -070031
Elliott Hughesfe447512015-07-24 11:35:40 -070032#include <cutils/sockets.h>
33
Spencer Low753d4852015-07-30 23:07:55 -070034#include <base/logging.h>
35#include <base/stringprintf.h>
36#include <base/strings.h>
37
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080038#include "adb.h"
39
40extern void fatal(const char *fmt, ...);
41
Elliott Hughes6a096932015-04-16 16:47:02 -070042/* forward declarations */
43
44typedef const struct FHClassRec_* FHClass;
45typedef struct FHRec_* FH;
46typedef struct EventHookRec_* EventHook;
47
48typedef struct FHClassRec_ {
49 void (*_fh_init)(FH);
50 int (*_fh_close)(FH);
51 int (*_fh_lseek)(FH, int, int);
52 int (*_fh_read)(FH, void*, int);
53 int (*_fh_write)(FH, const void*, int);
54 void (*_fh_hook)(FH, int, EventHook);
55} FHClassRec;
56
57static void _fh_file_init(FH);
58static int _fh_file_close(FH);
59static int _fh_file_lseek(FH, int, int);
60static int _fh_file_read(FH, void*, int);
61static int _fh_file_write(FH, const void*, int);
62static void _fh_file_hook(FH, int, EventHook);
63
64static const FHClassRec _fh_file_class = {
65 _fh_file_init,
66 _fh_file_close,
67 _fh_file_lseek,
68 _fh_file_read,
69 _fh_file_write,
70 _fh_file_hook
71};
72
73static void _fh_socket_init(FH);
74static int _fh_socket_close(FH);
75static int _fh_socket_lseek(FH, int, int);
76static int _fh_socket_read(FH, void*, int);
77static int _fh_socket_write(FH, const void*, int);
78static void _fh_socket_hook(FH, int, EventHook);
79
80static const FHClassRec _fh_socket_class = {
81 _fh_socket_init,
82 _fh_socket_close,
83 _fh_socket_lseek,
84 _fh_socket_read,
85 _fh_socket_write,
86 _fh_socket_hook
87};
88
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080089#define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
90
Spencer Low753d4852015-07-30 23:07:55 -070091std::string SystemErrorCodeToString(const DWORD error_code) {
92 const int kErrorMessageBufferSize = 256;
Spencer Lowcc467f12015-08-02 18:13:54 -070093 WCHAR msgbuf[kErrorMessageBufferSize];
Spencer Low753d4852015-07-30 23:07:55 -070094 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
Spencer Lowcc467f12015-08-02 18:13:54 -070095 DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf,
Spencer Low753d4852015-07-30 23:07:55 -070096 arraysize(msgbuf), nullptr);
97 if (len == 0) {
98 return android::base::StringPrintf(
99 "Error (%lu) while retrieving error. (%lu)", GetLastError(),
100 error_code);
101 }
102
Spencer Lowcc467f12015-08-02 18:13:54 -0700103 // Convert UTF-16 to UTF-8.
104 std::string msg(narrow(msgbuf));
Spencer Low753d4852015-07-30 23:07:55 -0700105 // Messages returned by the system end with line breaks.
106 msg = android::base::Trim(msg);
107 // There are many Windows error messages compared to POSIX, so include the
108 // numeric error code for easier, quicker, accurate identification. Use
109 // decimal instead of hex because there are decimal ranges like 10000-11999
110 // for Winsock.
111 android::base::StringAppendF(&msg, " (%lu)", error_code);
112 return msg;
113}
114
Spencer Low2bbb3a92015-08-26 18:46:09 -0700115void handle_deleter::operator()(HANDLE h) {
116 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
117 // implying that NULL is a valid handle, but this is probably impossible.
118 // Other APIs like CreateEvent() are documented to return NULL on error,
119 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
120 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
121 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
122 // only need to check for INVALID_HANDLE_VALUE.
123 if (h != INVALID_HANDLE_VALUE) {
124 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700125 D("CloseHandle(%p) failed: %s", h,
Spencer Low2bbb3a92015-08-26 18:46:09 -0700126 SystemErrorCodeToString(GetLastError()).c_str());
127 }
128 }
129}
130
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800131/**************************************************************************/
132/**************************************************************************/
133/***** *****/
134/***** replaces libs/cutils/load_file.c *****/
135/***** *****/
136/**************************************************************************/
137/**************************************************************************/
138
139void *load_file(const char *fn, unsigned *_sz)
140{
141 HANDLE file;
142 char *data;
143 DWORD file_size;
144
Spencer Low6815c072015-05-11 01:08:48 -0700145 file = CreateFileW( widen(fn).c_str(),
146 GENERIC_READ,
147 FILE_SHARE_READ,
148 NULL,
149 OPEN_EXISTING,
150 0,
151 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800152
153 if (file == INVALID_HANDLE_VALUE)
154 return NULL;
155
156 file_size = GetFileSize( file, NULL );
157 data = NULL;
158
159 if (file_size > 0) {
160 data = (char*) malloc( file_size + 1 );
161 if (data == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -0700162 D("load_file: could not allocate %ld bytes", file_size );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800163 file_size = 0;
164 } else {
165 DWORD out_bytes;
166
167 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
168 out_bytes != file_size )
169 {
Yabin Cui815ad882015-09-02 17:44:28 -0700170 D("load_file: could not read %ld bytes from '%s'", file_size, fn);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800171 free(data);
172 data = NULL;
173 file_size = 0;
174 }
175 }
176 }
177 CloseHandle( file );
178
179 *_sz = (unsigned) file_size;
180 return data;
181}
182
183/**************************************************************************/
184/**************************************************************************/
185/***** *****/
186/***** common file descriptor handling *****/
187/***** *****/
188/**************************************************************************/
189/**************************************************************************/
190
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800191/* used to emulate unix-domain socket pairs */
192typedef struct SocketPairRec_* SocketPair;
193
194typedef struct FHRec_
195{
196 FHClass clazz;
197 int used;
198 int eof;
199 union {
200 HANDLE handle;
201 SOCKET socket;
202 SocketPair pair;
203 } u;
204
205 HANDLE event;
206 int mask;
207
208 char name[32];
209
210} FHRec;
211
212#define fh_handle u.handle
213#define fh_socket u.socket
214#define fh_pair u.pair
215
216#define WIN32_FH_BASE 100
217
218#define WIN32_MAX_FHS 128
219
220static adb_mutex_t _win32_lock;
221static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700222static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800223
224static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700225_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800226{
227 FH f;
228
229 fd -= WIN32_FH_BASE;
230
Spencer Lowb732a372015-07-24 15:38:19 -0700231 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui815ad882015-09-02 17:44:28 -0700232 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700233 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800234 errno = EBADF;
235 return NULL;
236 }
237
238 f = &_win32_fhs[fd];
239
240 if (f->used == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700241 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700242 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800243 errno = EBADF;
244 return NULL;
245 }
246
247 return f;
248}
249
250
251static int
252_fh_to_int( FH f )
253{
254 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
255 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
256
257 return -1;
258}
259
260static FH
261_fh_alloc( FHClass clazz )
262{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800263 FH f = NULL;
264
265 adb_mutex_lock( &_win32_lock );
266
Spencer Lowb732a372015-07-24 15:38:19 -0700267 // Search entire array, starting from _win32_fh_next.
268 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
269 // Keep incrementing _win32_fh_next to avoid giving out an index that
270 // was recently closed, to try to avoid use-after-free.
271 const int index = _win32_fh_next++;
272 // Handle wrap-around of _win32_fh_next.
273 if (_win32_fh_next == WIN32_MAX_FHS) {
274 _win32_fh_next = 0;
275 }
276 if (_win32_fhs[index].clazz == NULL) {
277 f = &_win32_fhs[index];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800278 goto Exit;
279 }
280 }
Yabin Cui815ad882015-09-02 17:44:28 -0700281 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowb732a372015-07-24 15:38:19 -0700282 errno = EMFILE; // Too many open files
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800283Exit:
284 if (f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700285 f->clazz = clazz;
286 f->used = 1;
287 f->eof = 0;
288 f->name[0] = '\0';
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800289 clazz->_fh_init(f);
290 }
291 adb_mutex_unlock( &_win32_lock );
292 return f;
293}
294
295
296static int
297_fh_close( FH f )
298{
Spencer Lowb732a372015-07-24 15:38:19 -0700299 // Use lock so that closing only happens once and so that _fh_alloc can't
300 // allocate a FH that we're in the middle of closing.
301 adb_mutex_lock(&_win32_lock);
302 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800303 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700304 f->name[0] = '\0';
305 f->eof = 0;
306 f->used = 0;
307 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800308 }
Spencer Lowb732a372015-07-24 15:38:19 -0700309 adb_mutex_unlock(&_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800310 return 0;
311}
312
Spencer Low753d4852015-07-30 23:07:55 -0700313// Deleter for unique_fh.
314class fh_deleter {
315 public:
316 void operator()(struct FHRec_* fh) {
317 // We're called from a destructor and destructors should not overwrite
318 // errno because callers may do:
319 // errno = EBLAH;
320 // return -1; // calls destructor, which should not overwrite errno
321 const int saved_errno = errno;
322 _fh_close(fh);
323 errno = saved_errno;
324 }
325};
326
327// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
328typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
329
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800330/**************************************************************************/
331/**************************************************************************/
332/***** *****/
333/***** file-based descriptor handling *****/
334/***** *****/
335/**************************************************************************/
336/**************************************************************************/
337
Elliott Hughes6a096932015-04-16 16:47:02 -0700338static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800339 f->fh_handle = INVALID_HANDLE_VALUE;
340}
341
Elliott Hughes6a096932015-04-16 16:47:02 -0700342static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800343 CloseHandle( f->fh_handle );
344 f->fh_handle = INVALID_HANDLE_VALUE;
345 return 0;
346}
347
Elliott Hughes6a096932015-04-16 16:47:02 -0700348static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800349 DWORD read_bytes;
350
351 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700352 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800353 errno = EIO;
354 return -1;
355 } else if (read_bytes < (DWORD)len) {
356 f->eof = 1;
357 }
358 return (int)read_bytes;
359}
360
Elliott Hughes6a096932015-04-16 16:47:02 -0700361static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800362 DWORD wrote_bytes;
363
364 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700365 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800366 errno = EIO;
367 return -1;
368 } else if (wrote_bytes < (DWORD)len) {
369 f->eof = 1;
370 }
371 return (int)wrote_bytes;
372}
373
Elliott Hughes6a096932015-04-16 16:47:02 -0700374static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800375 DWORD method;
376 DWORD result;
377
378 switch (origin)
379 {
380 case SEEK_SET: method = FILE_BEGIN; break;
381 case SEEK_CUR: method = FILE_CURRENT; break;
382 case SEEK_END: method = FILE_END; break;
383 default:
384 errno = EINVAL;
385 return -1;
386 }
387
388 result = SetFilePointer( f->fh_handle, pos, NULL, method );
389 if (result == INVALID_SET_FILE_POINTER) {
390 errno = EIO;
391 return -1;
392 } else {
393 f->eof = 0;
394 }
395 return (int)result;
396}
397
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800398
399/**************************************************************************/
400/**************************************************************************/
401/***** *****/
402/***** file-based descriptor handling *****/
403/***** *****/
404/**************************************************************************/
405/**************************************************************************/
406
407int adb_open(const char* path, int options)
408{
409 FH f;
410
411 DWORD desiredAccess = 0;
412 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
413
414 switch (options) {
415 case O_RDONLY:
416 desiredAccess = GENERIC_READ;
417 break;
418 case O_WRONLY:
419 desiredAccess = GENERIC_WRITE;
420 break;
421 case O_RDWR:
422 desiredAccess = GENERIC_READ | GENERIC_WRITE;
423 break;
424 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700425 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800426 errno = EINVAL;
427 return -1;
428 }
429
430 f = _fh_alloc( &_fh_file_class );
431 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800432 return -1;
433 }
434
Spencer Low6815c072015-05-11 01:08:48 -0700435 f->fh_handle = CreateFileW( widen(path).c_str(), desiredAccess, shareMode,
436 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800437
438 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700439 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800440 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700441 D( "adb_open: could not open '%s': ", path );
442 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800443 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700444 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800445 errno = ENOENT;
446 return -1;
447
448 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700449 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800450 errno = ENOTDIR;
451 return -1;
452
453 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700454 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700455 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800456 errno = ENOENT;
457 return -1;
458 }
459 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800460
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800461 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700462 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800463 return _fh_to_int(f);
464}
465
466/* ignore mode on Win32 */
467int adb_creat(const char* path, int mode)
468{
469 FH f;
470
471 f = _fh_alloc( &_fh_file_class );
472 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800473 return -1;
474 }
475
Spencer Low6815c072015-05-11 01:08:48 -0700476 f->fh_handle = CreateFileW( widen(path).c_str(), GENERIC_WRITE,
477 FILE_SHARE_READ | FILE_SHARE_WRITE,
478 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
479 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800480
481 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700482 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700484 D( "adb_creat: could not open '%s': ", path );
485 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800486 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700487 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800488 errno = ENOENT;
489 return -1;
490
491 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700492 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800493 errno = ENOTDIR;
494 return -1;
495
496 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700497 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700498 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800499 errno = ENOENT;
500 return -1;
501 }
502 }
503 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700504 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800505 return _fh_to_int(f);
506}
507
508
509int adb_read(int fd, void* buf, int len)
510{
Spencer Low3a2421b2015-05-22 20:09:06 -0700511 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800512
513 if (f == NULL) {
514 return -1;
515 }
516
517 return f->clazz->_fh_read( f, buf, len );
518}
519
520
521int adb_write(int fd, const void* buf, int len)
522{
Spencer Low3a2421b2015-05-22 20:09:06 -0700523 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800524
525 if (f == NULL) {
526 return -1;
527 }
528
529 return f->clazz->_fh_write(f, buf, len);
530}
531
532
533int adb_lseek(int fd, int pos, int where)
534{
Spencer Low3a2421b2015-05-22 20:09:06 -0700535 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800536
537 if (!f) {
538 return -1;
539 }
540
541 return f->clazz->_fh_lseek(f, pos, where);
542}
543
544
545int adb_close(int fd)
546{
Spencer Low3a2421b2015-05-22 20:09:06 -0700547 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800548
549 if (!f) {
550 return -1;
551 }
552
Yabin Cui815ad882015-09-02 17:44:28 -0700553 D( "adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800554 _fh_close(f);
555 return 0;
556}
557
558/**************************************************************************/
559/**************************************************************************/
560/***** *****/
561/***** socket-based file descriptors *****/
562/***** *****/
563/**************************************************************************/
564/**************************************************************************/
565
Spencer Low31aafa62015-01-25 14:40:16 -0800566#undef setsockopt
567
Spencer Low753d4852015-07-30 23:07:55 -0700568static void _socket_set_errno( const DWORD err ) {
569 // The Windows C Runtime (MSVCRT.DLL) strerror() does not support a lot of
570 // POSIX and socket error codes, so this can only meaningfully map so much.
571 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800572 case 0: errno = 0; break;
Spencer Low32625852015-08-11 16:45:32 -0700573 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
574 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
575 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800576 case WSAEWOULDBLOCK: errno = EAGAIN; break;
577 case WSAEINTR: errno = EINTR; break;
Spencer Low753d4852015-07-30 23:07:55 -0700578 case WSAEFAULT: errno = EFAULT; break;
579 case WSAEINVAL: errno = EINVAL; break;
580 case WSAEMFILE: errno = EMFILE; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800581 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800582 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700583 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700584 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800585 }
586}
587
Elliott Hughes6a096932015-04-16 16:47:02 -0700588static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800589 f->fh_socket = INVALID_SOCKET;
590 f->event = WSACreateEvent();
Spencer Low753d4852015-07-30 23:07:55 -0700591 if (f->event == WSA_INVALID_EVENT) {
Yabin Cui815ad882015-09-02 17:44:28 -0700592 D("WSACreateEvent failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700593 SystemErrorCodeToString(WSAGetLastError()).c_str());
594
595 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
596 // on failure, instead of NULL which is what Windows really returns on
597 // error. It might be better to change all the other code to look for
598 // NULL, but that is a much riskier change.
599 f->event = INVALID_HANDLE_VALUE;
600 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800601 f->mask = 0;
602}
603
Elliott Hughes6a096932015-04-16 16:47:02 -0700604static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700605 if (f->fh_socket != INVALID_SOCKET) {
606 /* gently tell any peer that we're closing the socket */
607 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
608 // If the socket is not connected, this returns an error. We want to
609 // minimize logging spam, so don't log these errors for now.
610#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700611 D("socket shutdown failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700612 SystemErrorCodeToString(WSAGetLastError()).c_str());
613#endif
614 }
615 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Yabin Cui815ad882015-09-02 17:44:28 -0700616 D("closesocket failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700617 SystemErrorCodeToString(WSAGetLastError()).c_str());
618 }
619 f->fh_socket = INVALID_SOCKET;
620 }
621 if (f->event != NULL) {
622 if (!CloseHandle(f->event)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700623 D("CloseHandle failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700624 SystemErrorCodeToString(GetLastError()).c_str());
625 }
626 f->event = NULL;
627 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800628 f->mask = 0;
629 return 0;
630}
631
Elliott Hughes6a096932015-04-16 16:47:02 -0700632static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800633 errno = EPIPE;
634 return -1;
635}
636
Elliott Hughes6a096932015-04-16 16:47:02 -0700637static int _fh_socket_read(FH f, void* buf, int len) {
638 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700640 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700641 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
642 // that to reduce spam and confusion.
643 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700644 D("recv fd %d failed: %s", _fh_to_int(f),
Spencer Low32625852015-08-11 16:45:32 -0700645 SystemErrorCodeToString(err).c_str());
646 }
Spencer Low753d4852015-07-30 23:07:55 -0700647 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800648 result = -1;
649 }
650 return result;
651}
652
Elliott Hughes6a096932015-04-16 16:47:02 -0700653static int _fh_socket_write(FH f, const void* buf, int len) {
654 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800655 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700656 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -0700657 D("send fd %d failed: %s", _fh_to_int(f),
Spencer Low753d4852015-07-30 23:07:55 -0700658 SystemErrorCodeToString(err).c_str());
659 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800660 result = -1;
661 }
662 return result;
663}
664
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800665/**************************************************************************/
666/**************************************************************************/
667/***** *****/
668/***** replacement for libs/cutils/socket_xxxx.c *****/
669/***** *****/
670/**************************************************************************/
671/**************************************************************************/
672
673#include <winsock2.h>
674
675static int _winsock_init;
676
677static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800678_init_winsock( void )
679{
Spencer Low753d4852015-07-30 23:07:55 -0700680 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700681 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800682 if (!_winsock_init) {
683 WSADATA wsaData;
684 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
685 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700686 fatal( "adb: could not initialize Winsock: %s",
687 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800688 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800689 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700690
691 // Note that we do not call atexit() to register WSACleanup to be called
692 // at normal process termination because:
693 // 1) When exit() is called, there are still threads actively using
694 // Winsock because we don't cleanly shutdown all threads, so it
695 // doesn't make sense to call WSACleanup() and may cause problems
696 // with those threads.
697 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
698 // calls WSACleanup() which tries to unload a DLL, which tries to
699 // grab the LoaderLock. This conflicts with the device_poll_thread
700 // which holds the LoaderLock because AdbWinApi.dll calls
701 // setupapi.dll which tries to load wintrust.dll which tries to load
702 // crypt32.dll which calls atexit() which tries to acquire the C
703 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800704 }
705}
706
Spencer Low753d4852015-07-30 23:07:55 -0700707int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800708 struct sockaddr_in addr;
709 SOCKET s;
710
Spencer Low753d4852015-07-30 23:07:55 -0700711 unique_fh f(_fh_alloc(&_fh_socket_class));
712 if (!f) {
713 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800714 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700715 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800716
717 if (!_winsock_init)
718 _init_winsock();
719
720 memset(&addr, 0, sizeof(addr));
721 addr.sin_family = AF_INET;
722 addr.sin_port = htons(port);
723 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
724
725 s = socket(AF_INET, type, 0);
726 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700727 *error = android::base::StringPrintf("cannot create socket: %s",
728 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700729 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700730 return -1;
731 }
732 f->fh_socket = s;
733
734 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700735 // Save err just in case inet_ntoa() or ntohs() changes the last error.
736 const DWORD err = WSAGetLastError();
737 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
738 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
739 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700740 D("could not connect to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700741 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800742 return -1;
743 }
744
Spencer Low753d4852015-07-30 23:07:55 -0700745 const int fd = _fh_to_int(f.get());
746 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
747 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700748 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700749 fd );
750 f.release();
751 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800752}
753
754#define LISTEN_BACKLOG 4
755
Spencer Low753d4852015-07-30 23:07:55 -0700756// interface_address is INADDR_LOOPBACK or INADDR_ANY.
757static int _network_server(int port, int type, u_long interface_address,
758 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800759 struct sockaddr_in addr;
760 SOCKET s;
761 int n;
762
Spencer Low753d4852015-07-30 23:07:55 -0700763 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800764 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700765 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800766 return -1;
767 }
768
769 if (!_winsock_init)
770 _init_winsock();
771
772 memset(&addr, 0, sizeof(addr));
773 addr.sin_family = AF_INET;
774 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700775 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800776
Spencer Low753d4852015-07-30 23:07:55 -0700777 // TODO: Consider using dual-stack socket that can simultaneously listen on
778 // IPv4 and IPv6.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800779 s = socket(AF_INET, type, 0);
Spencer Low753d4852015-07-30 23:07:55 -0700780 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700781 *error = android::base::StringPrintf("cannot create socket: %s",
782 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700783 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700784 return -1;
785 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800786
787 f->fh_socket = s;
788
Spencer Low32625852015-08-11 16:45:32 -0700789 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
790 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800791 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700792 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
793 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700794 *error = android::base::StringPrintf(
795 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
796 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700797 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700798 return -1;
799 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800800
Spencer Low32625852015-08-11 16:45:32 -0700801 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
802 // Save err just in case inet_ntoa() or ntohs() changes the last error.
803 const DWORD err = WSAGetLastError();
804 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
805 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
806 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700807 D("could not bind to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700808 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800809 return -1;
810 }
811 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700812 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700813 *error = android::base::StringPrintf("cannot listen on socket: %s",
814 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700815 D("could not listen on %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700816 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800817 return -1;
818 }
819 }
Spencer Low753d4852015-07-30 23:07:55 -0700820 const int fd = _fh_to_int(f.get());
821 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
822 interface_address == INADDR_LOOPBACK ? "lo" : "any",
823 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700824 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700825 fd );
826 f.release();
827 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800828}
829
Spencer Low753d4852015-07-30 23:07:55 -0700830int network_loopback_server(int port, int type, std::string* error) {
831 return _network_server(port, type, INADDR_LOOPBACK, error);
832}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800833
Spencer Low753d4852015-07-30 23:07:55 -0700834int network_inaddr_any_server(int port, int type, std::string* error) {
835 return _network_server(port, type, INADDR_ANY, error);
836}
837
838int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
839 unique_fh f(_fh_alloc(&_fh_socket_class));
840 if (!f) {
841 *error = strerror(errno);
842 return -1;
843 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800844
Elliott Hughes43df1092015-07-23 17:12:58 -0700845 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800846
Spencer Low753d4852015-07-30 23:07:55 -0700847 struct addrinfo hints;
848 memset(&hints, 0, sizeof(hints));
849 hints.ai_family = AF_UNSPEC;
850 hints.ai_socktype = type;
851
852 char port_str[16];
853 snprintf(port_str, sizeof(port_str), "%d", port);
854
855 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700856
857#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
858 // TODO: When the Android SDK tools increases the Windows system
859 // requirements >= WinXP SP2, switch to GetAddrInfoW(widen(host).c_str()).
860#else
861 // Otherwise, keep using getaddrinfo(), or do runtime API detection
862 // with GetProcAddress("GetAddrInfoW").
863#endif
Spencer Low753d4852015-07-30 23:07:55 -0700864 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -0700865 *error = android::base::StringPrintf(
866 "cannot resolve host '%s' and port %s: %s", host.c_str(),
867 port_str, SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700868 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800869 return -1;
870 }
Spencer Low753d4852015-07-30 23:07:55 -0700871 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
872 addrinfo(addrinfo_ptr, freeaddrinfo);
873 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800874
Spencer Low753d4852015-07-30 23:07:55 -0700875 // TODO: Try all the addresses if there's more than one? This just uses
876 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
877 // which tries all addresses, takes a timeout and more.
878 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
879 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800880 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700881 *error = android::base::StringPrintf("cannot create socket: %s",
882 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700883 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800884 return -1;
885 }
886 f->fh_socket = s;
887
Spencer Low753d4852015-07-30 23:07:55 -0700888 // TODO: Implement timeouts for Windows. Seems like the default in theory
889 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
890 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700891 // TODO: Use WSAAddressToString or inet_ntop on address.
892 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
893 host.c_str(), port_str,
894 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700895 D("could not connect to %s:%s:%s: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700896 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
897 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800898 return -1;
899 }
900
Spencer Low753d4852015-07-30 23:07:55 -0700901 const int fd = _fh_to_int(f.get());
902 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
903 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700904 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low753d4852015-07-30 23:07:55 -0700905 type != SOCK_STREAM ? "udp" : "tcp", fd );
906 f.release();
907 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800908}
909
910#undef accept
911int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
912{
Spencer Low3a2421b2015-05-22 20:09:06 -0700913 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200914
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800915 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700916 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -0700917 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800918 return -1;
919 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200920
Spencer Low753d4852015-07-30 23:07:55 -0700921 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800922 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700923 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
924 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800925 return -1;
926 }
927
928 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
929 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700930 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700931 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
932 " failed: " + SystemErrorCodeToString(err);
933 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800934 return -1;
935 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200936
Spencer Low753d4852015-07-30 23:07:55 -0700937 const int fd = _fh_to_int(fh.get());
938 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -0700939 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -0700940 fh.release();
941 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800942}
943
944
Spencer Low31aafa62015-01-25 14:40:16 -0800945int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800946{
Spencer Low3a2421b2015-05-22 20:09:06 -0700947 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200948
Spencer Low31aafa62015-01-25 14:40:16 -0800949 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700950 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700951 errno = EBADF;
952 return -1;
953 }
954 int result = setsockopt( fh->fh_socket, level, optname,
955 reinterpret_cast<const char*>(optval), optlen );
956 if ( result == SOCKET_ERROR ) {
957 const DWORD err = WSAGetLastError();
958 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
959 "failed: %s\n", fd, level, optname,
960 SystemErrorCodeToString(err).c_str() );
961 _socket_set_errno( err );
962 result = -1;
963 }
964 return result;
965}
966
967
968int adb_shutdown(int fd)
969{
970 FH f = _fh_from_int(fd, __func__);
971
972 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -0700973 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700974 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -0800975 return -1;
976 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800977
Yabin Cui815ad882015-09-02 17:44:28 -0700978 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -0700979 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
980 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -0700981 D("socket shutdown fd %d failed: %s", fd,
Spencer Low753d4852015-07-30 23:07:55 -0700982 SystemErrorCodeToString(err).c_str());
983 _socket_set_errno(err);
984 return -1;
985 }
986 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800987}
988
989/**************************************************************************/
990/**************************************************************************/
991/***** *****/
992/***** emulated socketpairs *****/
993/***** *****/
994/**************************************************************************/
995/**************************************************************************/
996
997/* we implement socketpairs directly in use space for the following reasons:
998 * - it avoids copying data from/to the Nt kernel
999 * - it allows us to implement fdevent hooks easily and cheaply, something
1000 * that is not possible with standard Win32 pipes !!
1001 *
1002 * basically, we use two circular buffers, each one corresponding to a given
1003 * direction.
1004 *
1005 * each buffer is implemented as two regions:
1006 *
1007 * region A which is (a_start,a_end)
1008 * region B which is (0, b_end) with b_end <= a_start
1009 *
1010 * an empty buffer has: a_start = a_end = b_end = 0
1011 *
1012 * a_start is the pointer where we start reading data
1013 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
1014 * then you start writing at b_end
1015 *
1016 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
1017 *
1018 * there is room when b_end < a_start || a_end < BUFER_SIZE
1019 *
1020 * when reading, a_start is incremented, it a_start meets a_end, then
1021 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1022 */
1023
1024#define BIP_BUFFER_SIZE 4096
1025
1026#if 0
1027#include <stdio.h>
1028# define BIPD(x) D x
1029# define BIPDUMP bip_dump_hex
1030
1031static void bip_dump_hex( const unsigned char* ptr, size_t len )
1032{
1033 int nn, len2 = len;
1034
1035 if (len2 > 8) len2 = 8;
1036
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001037 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001038 printf("%02x", ptr[nn]);
1039 printf(" ");
1040
1041 for (nn = 0; nn < len2; nn++) {
1042 int c = ptr[nn];
1043 if (c < 32 || c > 127)
1044 c = '.';
1045 printf("%c", c);
1046 }
1047 printf("\n");
1048 fflush(stdout);
1049}
1050
1051#else
1052# define BIPD(x) do {} while (0)
1053# define BIPDUMP(p,l) BIPD(p)
1054#endif
1055
1056typedef struct BipBufferRec_
1057{
1058 int a_start;
1059 int a_end;
1060 int b_end;
1061 int fdin;
1062 int fdout;
1063 int closed;
1064 int can_write; /* boolean */
1065 HANDLE evt_write; /* event signaled when one can write to a buffer */
1066 int can_read; /* boolean */
1067 HANDLE evt_read; /* event signaled when one can read from a buffer */
1068 CRITICAL_SECTION lock;
1069 unsigned char buff[ BIP_BUFFER_SIZE ];
1070
1071} BipBufferRec, *BipBuffer;
1072
1073static void
1074bip_buffer_init( BipBuffer buffer )
1075{
Yabin Cui815ad882015-09-02 17:44:28 -07001076 D( "bit_buffer_init %p", buffer );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001077 buffer->a_start = 0;
1078 buffer->a_end = 0;
1079 buffer->b_end = 0;
1080 buffer->can_write = 1;
1081 buffer->can_read = 0;
1082 buffer->fdin = 0;
1083 buffer->fdout = 0;
1084 buffer->closed = 0;
1085 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1086 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1087 InitializeCriticalSection( &buffer->lock );
1088}
1089
1090static void
1091bip_buffer_close( BipBuffer bip )
1092{
1093 bip->closed = 1;
1094
1095 if (!bip->can_read) {
1096 SetEvent( bip->evt_read );
1097 }
1098 if (!bip->can_write) {
1099 SetEvent( bip->evt_write );
1100 }
1101}
1102
1103static void
1104bip_buffer_done( BipBuffer bip )
1105{
Yabin Cui815ad882015-09-02 17:44:28 -07001106 BIPD(( "bip_buffer_done: %d->%d", bip->fdin, bip->fdout ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001107 CloseHandle( bip->evt_read );
1108 CloseHandle( bip->evt_write );
1109 DeleteCriticalSection( &bip->lock );
1110}
1111
1112static int
1113bip_buffer_write( BipBuffer bip, const void* src, int len )
1114{
1115 int avail, count = 0;
1116
1117 if (len <= 0)
1118 return 0;
1119
Yabin Cui815ad882015-09-02 17:44:28 -07001120 BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001121 BIPDUMP( src, len );
1122
1123 EnterCriticalSection( &bip->lock );
1124
1125 while (!bip->can_write) {
1126 int ret;
1127 LeaveCriticalSection( &bip->lock );
1128
1129 if (bip->closed) {
1130 errno = EPIPE;
1131 return -1;
1132 }
1133 /* spinlocking here is probably unfair, but let's live with it */
1134 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1135 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
Yabin Cui815ad882015-09-02 17:44:28 -07001136 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 -08001137 return 0;
1138 }
1139 if (bip->closed) {
1140 errno = EPIPE;
1141 return -1;
1142 }
1143 EnterCriticalSection( &bip->lock );
1144 }
1145
Yabin Cui815ad882015-09-02 17:44:28 -07001146 BIPD(( "bip_buffer_write: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001147
1148 avail = BIP_BUFFER_SIZE - bip->a_end;
1149 if (avail > 0)
1150 {
1151 /* we can append to region A */
1152 if (avail > len)
1153 avail = len;
1154
1155 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001156 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001157 count += avail;
1158 len -= avail;
1159
1160 bip->a_end += avail;
1161 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1162 bip->can_write = 0;
1163 ResetEvent( bip->evt_write );
1164 goto Exit;
1165 }
1166 }
1167
1168 if (len == 0)
1169 goto Exit;
1170
1171 avail = bip->a_start - bip->b_end;
1172 assert( avail > 0 ); /* since can_write is TRUE */
1173
1174 if (avail > len)
1175 avail = len;
1176
1177 memcpy( bip->buff + bip->b_end, src, avail );
1178 count += avail;
1179 bip->b_end += avail;
1180
1181 if (bip->b_end == bip->a_start) {
1182 bip->can_write = 0;
1183 ResetEvent( bip->evt_write );
1184 }
1185
1186Exit:
1187 assert( count > 0 );
1188
1189 if ( !bip->can_read ) {
1190 bip->can_read = 1;
1191 SetEvent( bip->evt_read );
1192 }
1193
Yabin Cui815ad882015-09-02 17:44:28 -07001194 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 -08001195 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1196 LeaveCriticalSection( &bip->lock );
1197
1198 return count;
1199 }
1200
1201static int
1202bip_buffer_read( BipBuffer bip, void* dst, int len )
1203{
1204 int avail, count = 0;
1205
1206 if (len <= 0)
1207 return 0;
1208
Yabin Cui815ad882015-09-02 17:44:28 -07001209 BIPD(( "bip_buffer_read: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001210
1211 EnterCriticalSection( &bip->lock );
1212 while ( !bip->can_read )
1213 {
1214#if 0
1215 LeaveCriticalSection( &bip->lock );
1216 errno = EAGAIN;
1217 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001218#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001219 int ret;
1220 LeaveCriticalSection( &bip->lock );
1221
1222 if (bip->closed) {
1223 errno = EPIPE;
1224 return -1;
1225 }
1226
1227 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1228 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
Yabin Cui815ad882015-09-02 17:44:28 -07001229 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 -08001230 return 0;
1231 }
1232 if (bip->closed) {
1233 errno = EPIPE;
1234 return -1;
1235 }
1236 EnterCriticalSection( &bip->lock );
1237#endif
1238 }
1239
Yabin Cui815ad882015-09-02 17:44:28 -07001240 BIPD(( "bip_buffer_read: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001241
1242 avail = bip->a_end - bip->a_start;
1243 assert( avail > 0 ); /* since can_read is TRUE */
1244
1245 if (avail > len)
1246 avail = len;
1247
1248 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001249 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001250 count += avail;
1251 len -= avail;
1252
1253 bip->a_start += avail;
1254 if (bip->a_start < bip->a_end)
1255 goto Exit;
1256
1257 bip->a_start = 0;
1258 bip->a_end = bip->b_end;
1259 bip->b_end = 0;
1260
1261 avail = bip->a_end;
1262 if (avail > 0) {
1263 if (avail > len)
1264 avail = len;
1265 memcpy( dst, bip->buff, avail );
1266 count += avail;
1267 bip->a_start += avail;
1268
1269 if ( bip->a_start < bip->a_end )
1270 goto Exit;
1271
1272 bip->a_start = bip->a_end = 0;
1273 }
1274
1275 bip->can_read = 0;
1276 ResetEvent( bip->evt_read );
1277
1278Exit:
1279 assert( count > 0 );
1280
1281 if (!bip->can_write ) {
1282 bip->can_write = 1;
1283 SetEvent( bip->evt_write );
1284 }
1285
1286 BIPDUMP( (const unsigned char*)dst - count, count );
Yabin Cui815ad882015-09-02 17:44:28 -07001287 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 -08001288 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1289 LeaveCriticalSection( &bip->lock );
1290
1291 return count;
1292}
1293
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001294typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001295{
1296 BipBufferRec a2b_bip;
1297 BipBufferRec b2a_bip;
1298 FH a_fd;
1299 int used;
1300
1301} SocketPairRec;
1302
1303void _fh_socketpair_init( FH f )
1304{
1305 f->fh_pair = NULL;
1306}
1307
1308static int
1309_fh_socketpair_close( FH f )
1310{
1311 if ( f->fh_pair ) {
1312 SocketPair pair = f->fh_pair;
1313
1314 if ( f == pair->a_fd ) {
1315 pair->a_fd = NULL;
1316 }
1317
1318 bip_buffer_close( &pair->b2a_bip );
1319 bip_buffer_close( &pair->a2b_bip );
1320
1321 if ( --pair->used == 0 ) {
1322 bip_buffer_done( &pair->b2a_bip );
1323 bip_buffer_done( &pair->a2b_bip );
1324 free( pair );
1325 }
1326 f->fh_pair = NULL;
1327 }
1328 return 0;
1329}
1330
1331static int
1332_fh_socketpair_lseek( FH f, int pos, int origin )
1333{
1334 errno = ESPIPE;
1335 return -1;
1336}
1337
1338static int
1339_fh_socketpair_read( FH f, void* buf, int len )
1340{
1341 SocketPair pair = f->fh_pair;
1342 BipBuffer bip;
1343
1344 if (!pair)
1345 return -1;
1346
1347 if ( f == pair->a_fd )
1348 bip = &pair->b2a_bip;
1349 else
1350 bip = &pair->a2b_bip;
1351
1352 return bip_buffer_read( bip, buf, len );
1353}
1354
1355static int
1356_fh_socketpair_write( FH f, const void* buf, int len )
1357{
1358 SocketPair pair = f->fh_pair;
1359 BipBuffer bip;
1360
1361 if (!pair)
1362 return -1;
1363
1364 if ( f == pair->a_fd )
1365 bip = &pair->a2b_bip;
1366 else
1367 bip = &pair->b2a_bip;
1368
1369 return bip_buffer_write( bip, buf, len );
1370}
1371
1372
1373static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1374
1375static const FHClassRec _fh_socketpair_class =
1376{
1377 _fh_socketpair_init,
1378 _fh_socketpair_close,
1379 _fh_socketpair_lseek,
1380 _fh_socketpair_read,
1381 _fh_socketpair_write,
1382 _fh_socketpair_hook
1383};
1384
1385
Elliott Hughes6a096932015-04-16 16:47:02 -07001386int adb_socketpair(int sv[2]) {
1387 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001388
Spencer Low753d4852015-07-30 23:07:55 -07001389 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1390 if (!fa) {
1391 return -1;
1392 }
1393 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1394 if (!fb) {
1395 return -1;
1396 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001397
Elliott Hughes6a096932015-04-16 16:47:02 -07001398 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001399 if (pair == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001400 D("adb_socketpair: not enough memory to allocate pipes" );
Spencer Low753d4852015-07-30 23:07:55 -07001401 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001402 }
1403
1404 bip_buffer_init( &pair->a2b_bip );
1405 bip_buffer_init( &pair->b2a_bip );
1406
1407 fa->fh_pair = pair;
1408 fb->fh_pair = pair;
1409 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001410 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001411
Spencer Low753d4852015-07-30 23:07:55 -07001412 sv[0] = _fh_to_int(fa.get());
1413 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001414
1415 pair->a2b_bip.fdin = sv[0];
1416 pair->a2b_bip.fdout = sv[1];
1417 pair->b2a_bip.fdin = sv[1];
1418 pair->b2a_bip.fdout = sv[0];
1419
1420 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1421 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
Yabin Cui815ad882015-09-02 17:44:28 -07001422 D( "adb_socketpair: returns (%d, %d)", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001423 fa.release();
1424 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001425 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001426}
1427
1428/**************************************************************************/
1429/**************************************************************************/
1430/***** *****/
1431/***** fdevents emulation *****/
1432/***** *****/
1433/***** this is a very simple implementation, we rely on the fact *****/
1434/***** that ADB doesn't use FDE_ERROR. *****/
1435/***** *****/
1436/**************************************************************************/
1437/**************************************************************************/
1438
1439#define FATAL(x...) fatal(__FUNCTION__, x)
1440
1441#if DEBUG
1442static void dump_fde(fdevent *fde, const char *info)
1443{
1444 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1445 fde->state & FDE_READ ? 'R' : ' ',
1446 fde->state & FDE_WRITE ? 'W' : ' ',
1447 fde->state & FDE_ERROR ? 'E' : ' ',
1448 info);
1449}
1450#else
1451#define dump_fde(fde, info) do { } while(0)
1452#endif
1453
1454#define FDE_EVENTMASK 0x00ff
1455#define FDE_STATEMASK 0xff00
1456
1457#define FDE_ACTIVE 0x0100
1458#define FDE_PENDING 0x0200
1459#define FDE_CREATED 0x0400
1460
1461static void fdevent_plist_enqueue(fdevent *node);
1462static void fdevent_plist_remove(fdevent *node);
1463static fdevent *fdevent_plist_dequeue(void);
1464
1465static fdevent list_pending = {
1466 .next = &list_pending,
1467 .prev = &list_pending,
1468};
1469
1470static fdevent **fd_table = 0;
1471static int fd_table_max = 0;
1472
1473typedef struct EventLooperRec_* EventLooper;
1474
1475typedef struct EventHookRec_
1476{
1477 EventHook next;
1478 FH fh;
1479 HANDLE h;
1480 int wanted; /* wanted event flags */
1481 int ready; /* ready event flags */
1482 void* aux;
1483 void (*prepare)( EventHook hook );
1484 int (*start) ( EventHook hook );
1485 void (*stop) ( EventHook hook );
1486 int (*check) ( EventHook hook );
1487 int (*peek) ( EventHook hook );
1488} EventHookRec;
1489
1490static EventHook _free_hooks;
1491
1492static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001493event_hook_alloc(FH fh) {
1494 EventHook hook = _free_hooks;
1495 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001496 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001497 } else {
1498 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001499 if (hook == NULL)
1500 fatal( "could not allocate event hook\n" );
1501 }
1502 hook->next = NULL;
1503 hook->fh = fh;
1504 hook->wanted = 0;
1505 hook->ready = 0;
1506 hook->h = INVALID_HANDLE_VALUE;
1507 hook->aux = NULL;
1508
1509 hook->prepare = NULL;
1510 hook->start = NULL;
1511 hook->stop = NULL;
1512 hook->check = NULL;
1513 hook->peek = NULL;
1514
1515 return hook;
1516}
1517
1518static void
1519event_hook_free( EventHook hook )
1520{
1521 hook->fh = NULL;
1522 hook->wanted = 0;
1523 hook->ready = 0;
1524 hook->next = _free_hooks;
1525 _free_hooks = hook;
1526}
1527
1528
1529static void
1530event_hook_signal( EventHook hook )
1531{
1532 FH f = hook->fh;
1533 int fd = _fh_to_int(f);
1534 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1535
1536 if (fde != NULL && fde->fd == fd) {
1537 if ((fde->state & FDE_PENDING) == 0) {
1538 fde->state |= FDE_PENDING;
1539 fdevent_plist_enqueue( fde );
1540 }
1541 fde->events |= hook->wanted;
1542 }
1543}
1544
1545
1546#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1547
1548typedef struct EventLooperRec_
1549{
1550 EventHook hooks;
1551 HANDLE htab[ MAX_LOOPER_HANDLES ];
1552 int htab_count;
1553
1554} EventLooperRec;
1555
1556static EventHook*
1557event_looper_find_p( EventLooper looper, FH fh )
1558{
1559 EventHook *pnode = &looper->hooks;
1560 EventHook node = *pnode;
1561 for (;;) {
1562 if ( node == NULL || node->fh == fh )
1563 break;
1564 pnode = &node->next;
1565 node = *pnode;
1566 }
1567 return pnode;
1568}
1569
1570static void
1571event_looper_hook( EventLooper looper, int fd, int events )
1572{
Spencer Low3a2421b2015-05-22 20:09:06 -07001573 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001574 EventHook *pnode;
1575 EventHook node;
1576
1577 if (f == NULL) /* invalid arg */ {
Yabin Cui815ad882015-09-02 17:44:28 -07001578 D("event_looper_hook: invalid fd=%d", fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001579 return;
1580 }
1581
1582 pnode = event_looper_find_p( looper, f );
1583 node = *pnode;
1584 if ( node == NULL ) {
1585 node = event_hook_alloc( f );
1586 node->next = *pnode;
1587 *pnode = node;
1588 }
1589
1590 if ( (node->wanted & events) != events ) {
1591 /* this should update start/stop/check/peek */
Yabin Cui815ad882015-09-02 17:44:28 -07001592 D("event_looper_hook: call hook for %d (new=%x, old=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001593 fd, node->wanted, events);
1594 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1595 node->wanted |= events;
1596 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07001597 D("event_looper_hook: ignoring events %x for %d wanted=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001598 events, fd, node->wanted);
1599 }
1600}
1601
1602static void
1603event_looper_unhook( EventLooper looper, int fd, int events )
1604{
Spencer Low3a2421b2015-05-22 20:09:06 -07001605 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001606 EventHook *pnode = event_looper_find_p( looper, fh );
1607 EventHook node = *pnode;
1608
1609 if (node != NULL) {
1610 int events2 = events & node->wanted;
1611 if ( events2 == 0 ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001612 D( "event_looper_unhook: events %x not registered for fd %d", events, fd );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001613 return;
1614 }
1615 node->wanted &= ~events2;
1616 if (!node->wanted) {
1617 *pnode = node->next;
1618 event_hook_free( node );
1619 }
1620 }
1621}
1622
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001623/*
1624 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1625 * handles to wait on.
1626 *
1627 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1628 * instance, this may happen if there are more than 64 processes running on a
1629 * device, or there are multiple devices connected (including the emulator) with
1630 * the combined number of running processes greater than 64. In this case using
1631 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1632 * because of the API limitations (64 handles max). So, we need to provide a way
1633 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1634 * easiest (and "Microsoft recommended") way to do that would be dividing the
1635 * handle array into chunks with the chunk size less than 64, and fire up as many
1636 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1637 * handles, and will report back to the caller which handle has been set.
1638 * Here is the implementation of that algorithm.
1639 */
1640
1641/* Number of handles to wait on in each wating thread. */
1642#define WAIT_ALL_CHUNK_SIZE 63
1643
1644/* Descriptor for a wating thread */
1645typedef struct WaitForAllParam {
1646 /* A handle to an event to signal when waiting is over. This handle is shared
1647 * accross all the waiting threads, so each waiting thread knows when any
1648 * other thread has exited, so it can exit too. */
1649 HANDLE main_event;
1650 /* Upon exit from a waiting thread contains the index of the handle that has
1651 * been signaled. The index is an absolute index of the signaled handle in
1652 * the original array. This pointer is shared accross all the waiting threads
1653 * and it's not guaranteed (due to a race condition) that when all the
1654 * waiting threads exit, the value contained here would indicate the first
1655 * handle that was signaled. This is fine, because the caller cares only
1656 * about any handle being signaled. It doesn't care about the order, nor
1657 * about the whole list of handles that were signaled. */
1658 LONG volatile *signaled_index;
1659 /* Array of handles to wait on in a waiting thread. */
1660 HANDLE* handles;
1661 /* Number of handles in 'handles' array to wait on. */
1662 int handles_count;
1663 /* Index inside the main array of the first handle in the 'handles' array. */
1664 int first_handle_index;
1665 /* Waiting thread handle. */
1666 HANDLE thread;
1667} WaitForAllParam;
1668
1669/* Waiting thread routine. */
1670static unsigned __stdcall
1671_in_waiter_thread(void* arg)
1672{
1673 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1674 int res;
1675 WaitForAllParam* const param = (WaitForAllParam*)arg;
1676
1677 /* We have to wait on the main_event in order to be notified when any of the
1678 * sibling threads is exiting. */
1679 wait_on[0] = param->main_event;
1680 /* The rest of the handles go behind the main event handle. */
1681 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1682
1683 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1684 if (res > 0 && res < (param->handles_count + 1)) {
1685 /* One of the original handles got signaled. Save its absolute index into
1686 * the output variable. */
1687 InterlockedCompareExchange(param->signaled_index,
1688 res - 1L + param->first_handle_index, -1L);
1689 }
1690
1691 /* Notify the caller (and the siblings) that the wait is over. */
1692 SetEvent(param->main_event);
1693
1694 _endthreadex(0);
1695 return 0;
1696}
1697
1698/* WaitForMultipeObjects fixer routine.
1699 * Param:
1700 * handles Array of handles to wait on.
1701 * handles_count Number of handles in the array.
1702 * Return:
1703 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1704 * WAIT_FAILED on an error.
1705 */
1706static int
1707_wait_for_all(HANDLE* handles, int handles_count)
1708{
1709 WaitForAllParam* threads;
1710 HANDLE main_event;
1711 int chunks, chunk, remains;
1712
1713 /* This variable is going to be accessed by several threads at the same time,
1714 * this is bound to fail randomly when the core is run on multi-core machines.
1715 * To solve this, we need to do the following (1 _and_ 2):
1716 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1717 * out the reads/writes in this function unexpectedly.
1718 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1719 * all accesses inside a critical section. But we can also use
1720 * InterlockedCompareExchange() which always provide a full memory barrier
1721 * on Win32.
1722 */
1723 volatile LONG sig_index = -1;
1724
1725 /* Calculate number of chunks, and allocate thread param array. */
1726 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1727 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1728 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1729 sizeof(WaitForAllParam));
1730 if (threads == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001731 D("Unable to allocate thread array for %d handles.", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001732 return (int)WAIT_FAILED;
1733 }
1734
1735 /* Create main event to wait on for all waiting threads. This is a "manualy
1736 * reset" event that will remain set once it was set. */
1737 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1738 if (main_event == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001739 D("Unable to create main event. Error: %ld", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001740 free(threads);
1741 return (int)WAIT_FAILED;
1742 }
1743
1744 /*
1745 * Initialize waiting thread parameters.
1746 */
1747
1748 for (chunk = 0; chunk < chunks; chunk++) {
1749 threads[chunk].main_event = main_event;
1750 threads[chunk].signaled_index = &sig_index;
1751 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1752 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1753 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1754 }
1755 if (remains) {
1756 threads[chunk].main_event = main_event;
1757 threads[chunk].signaled_index = &sig_index;
1758 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1759 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1760 threads[chunk].handles_count = remains;
1761 chunks++;
1762 }
1763
1764 /* Start the waiting threads. */
1765 for (chunk = 0; chunk < chunks; chunk++) {
1766 /* Note that using adb_thread_create is not appropriate here, since we
1767 * need a handle to wait on for thread termination. */
1768 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1769 &threads[chunk], 0, NULL);
1770 if (threads[chunk].thread == NULL) {
1771 /* Unable to create a waiter thread. Collapse. */
Yabin Cui815ad882015-09-02 17:44:28 -07001772 D("Unable to create a waiting thread %d of %d. errno=%d",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001773 chunk, chunks, errno);
1774 chunks = chunk;
1775 SetEvent(main_event);
1776 break;
1777 }
1778 }
1779
1780 /* Wait on any of the threads to get signaled. */
1781 WaitForSingleObject(main_event, INFINITE);
1782
1783 /* Wait on all the waiting threads to exit. */
1784 for (chunk = 0; chunk < chunks; chunk++) {
1785 WaitForSingleObject(threads[chunk].thread, INFINITE);
1786 CloseHandle(threads[chunk].thread);
1787 }
1788
1789 CloseHandle(main_event);
1790 free(threads);
1791
1792
1793 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1794 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1795}
1796
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001797static EventLooperRec win32_looper;
1798
1799static void fdevent_init(void)
1800{
1801 win32_looper.htab_count = 0;
1802 win32_looper.hooks = NULL;
1803}
1804
1805static void fdevent_connect(fdevent *fde)
1806{
1807 EventLooper looper = &win32_looper;
1808 int events = fde->state & FDE_EVENTMASK;
1809
1810 if (events != 0)
1811 event_looper_hook( looper, fde->fd, events );
1812}
1813
1814static void fdevent_disconnect(fdevent *fde)
1815{
1816 EventLooper looper = &win32_looper;
1817 int events = fde->state & FDE_EVENTMASK;
1818
1819 if (events != 0)
1820 event_looper_unhook( looper, fde->fd, events );
1821}
1822
1823static void fdevent_update(fdevent *fde, unsigned events)
1824{
1825 EventLooper looper = &win32_looper;
1826 unsigned events0 = fde->state & FDE_EVENTMASK;
1827
1828 if (events != events0) {
1829 int removes = events0 & ~events;
1830 int adds = events & ~events0;
1831 if (removes) {
Yabin Cui815ad882015-09-02 17:44:28 -07001832 D("fdevent_update: remove %x from %d", removes, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001833 event_looper_unhook( looper, fde->fd, removes );
1834 }
1835 if (adds) {
Yabin Cui815ad882015-09-02 17:44:28 -07001836 D("fdevent_update: add %x to %d", adds, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001837 event_looper_hook ( looper, fde->fd, adds );
1838 }
1839 }
1840}
1841
1842static void fdevent_process()
1843{
1844 EventLooper looper = &win32_looper;
1845 EventHook hook;
1846 int gotone = 0;
1847
1848 /* if we have at least one ready hook, execute it/them */
1849 for (hook = looper->hooks; hook; hook = hook->next) {
1850 hook->ready = 0;
1851 if (hook->prepare) {
1852 hook->prepare(hook);
1853 if (hook->ready != 0) {
1854 event_hook_signal( hook );
1855 gotone = 1;
1856 }
1857 }
1858 }
1859
1860 /* nothing's ready yet, so wait for something to happen */
1861 if (!gotone)
1862 {
1863 looper->htab_count = 0;
1864
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001865 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001866 {
1867 if (hook->start && !hook->start(hook)) {
Yabin Cui815ad882015-09-02 17:44:28 -07001868 D( "fdevent_process: error when starting a hook" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001869 return;
1870 }
1871 if (hook->h != INVALID_HANDLE_VALUE) {
1872 int nn;
1873
1874 for (nn = 0; nn < looper->htab_count; nn++)
1875 {
1876 if ( looper->htab[nn] == hook->h )
1877 goto DontAdd;
1878 }
1879 looper->htab[ looper->htab_count++ ] = hook->h;
1880 DontAdd:
1881 ;
1882 }
1883 }
1884
1885 if (looper->htab_count == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -07001886 D( "fdevent_process: nothing to wait for !!" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001887 return;
1888 }
1889
1890 do
1891 {
1892 int wait_ret;
1893
Yabin Cui815ad882015-09-02 17:44:28 -07001894 D( "adb_win32: waiting for %d events", looper->htab_count );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001895 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Yabin Cui815ad882015-09-02 17:44:28 -07001896 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.", looper->htab_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001897 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1898 } else {
1899 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001900 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001901 if (wait_ret == (int)WAIT_FAILED) {
Yabin Cui815ad882015-09-02 17:44:28 -07001902 D( "adb_win32: wait failed, error %ld", GetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001903 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07001904 D( "adb_win32: got one (index %d)", wait_ret );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001905
1906 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1907 * like mouse movements. we need to filter these with the "check" function
1908 */
1909 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1910 {
1911 for (hook = looper->hooks; hook; hook = hook->next)
1912 {
1913 if ( looper->htab[wait_ret] == hook->h &&
1914 (!hook->check || hook->check(hook)) )
1915 {
Yabin Cui815ad882015-09-02 17:44:28 -07001916 D( "adb_win32: signaling %s for %x", hook->fh->name, hook->ready );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001917 event_hook_signal( hook );
1918 gotone = 1;
1919 break;
1920 }
1921 }
1922 }
1923 }
1924 }
1925 while (!gotone);
1926
1927 for (hook = looper->hooks; hook; hook = hook->next) {
1928 if (hook->stop)
1929 hook->stop( hook );
1930 }
1931 }
1932
1933 for (hook = looper->hooks; hook; hook = hook->next) {
1934 if (hook->peek && hook->peek(hook))
1935 event_hook_signal( hook );
1936 }
1937}
1938
1939
1940static void fdevent_register(fdevent *fde)
1941{
1942 int fd = fde->fd - WIN32_FH_BASE;
1943
1944 if(fd < 0) {
1945 FATAL("bogus negative fd (%d)\n", fde->fd);
1946 }
1947
1948 if(fd >= fd_table_max) {
1949 int oldmax = fd_table_max;
1950 if(fde->fd > 32000) {
1951 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1952 }
1953 if(fd_table_max == 0) {
1954 fdevent_init();
1955 fd_table_max = 256;
1956 }
1957 while(fd_table_max <= fd) {
1958 fd_table_max *= 2;
1959 }
Elliott Hughes6a096932015-04-16 16:47:02 -07001960 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001961 if(fd_table == 0) {
1962 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1963 }
1964 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
1965 }
1966
1967 fd_table[fd] = fde;
1968}
1969
1970static void fdevent_unregister(fdevent *fde)
1971{
1972 int fd = fde->fd - WIN32_FH_BASE;
1973
1974 if((fd < 0) || (fd >= fd_table_max)) {
1975 FATAL("fd out of range (%d)\n", fde->fd);
1976 }
1977
1978 if(fd_table[fd] != fde) {
1979 FATAL("fd_table out of sync");
1980 }
1981
1982 fd_table[fd] = 0;
1983
1984 if(!(fde->state & FDE_DONT_CLOSE)) {
1985 dump_fde(fde, "close");
1986 adb_close(fde->fd);
1987 }
1988}
1989
1990static void fdevent_plist_enqueue(fdevent *node)
1991{
1992 fdevent *list = &list_pending;
1993
1994 node->next = list;
1995 node->prev = list->prev;
1996 node->prev->next = node;
1997 list->prev = node;
1998}
1999
2000static void fdevent_plist_remove(fdevent *node)
2001{
2002 node->prev->next = node->next;
2003 node->next->prev = node->prev;
2004 node->next = 0;
2005 node->prev = 0;
2006}
2007
2008static fdevent *fdevent_plist_dequeue(void)
2009{
2010 fdevent *list = &list_pending;
2011 fdevent *node = list->next;
2012
2013 if(node == list) return 0;
2014
2015 list->next = node->next;
2016 list->next->prev = list;
2017 node->next = 0;
2018 node->prev = 0;
2019
2020 return node;
2021}
2022
2023fdevent *fdevent_create(int fd, fd_func func, void *arg)
2024{
2025 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2026 if(fde == 0) return 0;
2027 fdevent_install(fde, fd, func, arg);
2028 fde->state |= FDE_CREATED;
2029 return fde;
2030}
2031
2032void fdevent_destroy(fdevent *fde)
2033{
2034 if(fde == 0) return;
2035 if(!(fde->state & FDE_CREATED)) {
2036 FATAL("fde %p not created by fdevent_create()\n", fde);
2037 }
2038 fdevent_remove(fde);
2039}
2040
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002041void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002042{
2043 memset(fde, 0, sizeof(fdevent));
2044 fde->state = FDE_ACTIVE;
2045 fde->fd = fd;
2046 fde->func = func;
2047 fde->arg = arg;
2048
2049 fdevent_register(fde);
2050 dump_fde(fde, "connect");
2051 fdevent_connect(fde);
2052 fde->state |= FDE_ACTIVE;
2053}
2054
2055void fdevent_remove(fdevent *fde)
2056{
2057 if(fde->state & FDE_PENDING) {
2058 fdevent_plist_remove(fde);
2059 }
2060
2061 if(fde->state & FDE_ACTIVE) {
2062 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002063 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002064 fdevent_unregister(fde);
2065 }
2066
2067 fde->state = 0;
2068 fde->events = 0;
2069}
2070
2071
2072void fdevent_set(fdevent *fde, unsigned events)
2073{
2074 events &= FDE_EVENTMASK;
2075
2076 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2077
2078 if(fde->state & FDE_ACTIVE) {
2079 fdevent_update(fde, events);
2080 dump_fde(fde, "update");
2081 }
2082
2083 fde->state = (fde->state & FDE_STATEMASK) | events;
2084
2085 if(fde->state & FDE_PENDING) {
2086 /* if we're pending, make sure
2087 ** we don't signal an event that
2088 ** is no longer wanted.
2089 */
2090 fde->events &= (~events);
2091 if(fde->events == 0) {
2092 fdevent_plist_remove(fde);
2093 fde->state &= (~FDE_PENDING);
2094 }
2095 }
2096}
2097
2098void fdevent_add(fdevent *fde, unsigned events)
2099{
2100 fdevent_set(
2101 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2102}
2103
2104void fdevent_del(fdevent *fde, unsigned events)
2105{
2106 fdevent_set(
2107 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2108}
2109
2110void fdevent_loop()
2111{
2112 fdevent *fde;
2113
2114 for(;;) {
2115#if DEBUG
2116 fprintf(stderr,"--- ---- waiting for events\n");
2117#endif
2118 fdevent_process();
2119
2120 while((fde = fdevent_plist_dequeue())) {
2121 unsigned events = fde->events;
2122 fde->events = 0;
2123 fde->state &= (~FDE_PENDING);
2124 dump_fde(fde, "callback");
2125 fde->func(fde->fd, events, fde->arg);
2126 }
2127 }
2128}
2129
2130/** FILE EVENT HOOKS
2131 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002132
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002133static void _event_file_prepare( EventHook hook )
2134{
2135 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2136 /* we can always read/write */
2137 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2138 }
2139}
2140
2141static int _event_file_peek( EventHook hook )
2142{
2143 return (hook->wanted & (FDE_READ|FDE_WRITE));
2144}
2145
2146static void _fh_file_hook( FH f, int events, EventHook hook )
2147{
2148 hook->h = f->fh_handle;
2149 hook->prepare = _event_file_prepare;
2150 hook->peek = _event_file_peek;
2151}
2152
2153/** SOCKET EVENT HOOKS
2154 **/
2155
2156static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2157{
2158 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2159 if (hook->wanted & FDE_READ)
2160 hook->ready |= FDE_READ;
2161 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2162 hook->ready |= FDE_ERROR;
2163 }
2164 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2165 if (hook->wanted & FDE_WRITE)
2166 hook->ready |= FDE_WRITE;
2167 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2168 hook->ready |= FDE_ERROR;
2169 }
2170 if ( evts->lNetworkEvents & FD_OOB ) {
2171 if (hook->wanted & FDE_ERROR)
2172 hook->ready |= FDE_ERROR;
2173 }
2174}
2175
2176static void _event_socket_prepare( EventHook hook )
2177{
2178 WSANETWORKEVENTS evts;
2179
2180 /* look if some of the events we want already happened ? */
2181 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2182 _event_socket_verify( hook, &evts );
2183}
2184
2185static int _socket_wanted_to_flags( int wanted )
2186{
2187 int flags = 0;
2188 if (wanted & FDE_READ)
2189 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2190
2191 if (wanted & FDE_WRITE)
2192 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2193
2194 if (wanted & FDE_ERROR)
2195 flags |= FD_OOB;
2196
2197 return flags;
2198}
2199
2200static int _event_socket_start( EventHook hook )
2201{
2202 /* create an event which we're going to wait for */
2203 FH fh = hook->fh;
2204 long flags = _socket_wanted_to_flags( hook->wanted );
2205
2206 hook->h = fh->event;
2207 if (hook->h == INVALID_HANDLE_VALUE) {
Yabin Cui815ad882015-09-02 17:44:28 -07002208 D( "_event_socket_start: no event for %s", fh->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002209 return 0;
2210 }
2211
2212 if ( flags != fh->mask ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002213 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 -08002214 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002215 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d", hook->fh->name, WSAGetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002216 CloseHandle( hook->h );
2217 hook->h = INVALID_HANDLE_VALUE;
2218 exit(1);
2219 return 0;
2220 }
2221 fh->mask = flags;
2222 }
2223 return 1;
2224}
2225
2226static void _event_socket_stop( EventHook hook )
2227{
2228 hook->h = INVALID_HANDLE_VALUE;
2229}
2230
2231static int _event_socket_check( EventHook hook )
2232{
2233 int result = 0;
2234 FH fh = hook->fh;
2235 WSANETWORKEVENTS evts;
2236
2237 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2238 _event_socket_verify( hook, &evts );
2239 result = (hook->ready != 0);
2240 if (result) {
2241 ResetEvent( hook->h );
2242 }
2243 }
Yabin Cui815ad882015-09-02 17:44:28 -07002244 D( "_event_socket_check %s returns %d", fh->name, result );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002245 return result;
2246}
2247
2248static int _event_socket_peek( EventHook hook )
2249{
2250 WSANETWORKEVENTS evts;
2251 FH fh = hook->fh;
2252
2253 /* look if some of the events we want already happened ? */
2254 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2255 _event_socket_verify( hook, &evts );
2256 if (hook->ready)
2257 ResetEvent( hook->h );
2258 }
2259
2260 return hook->ready != 0;
2261}
2262
2263
2264
2265static void _fh_socket_hook( FH f, int events, EventHook hook )
2266{
2267 hook->prepare = _event_socket_prepare;
2268 hook->start = _event_socket_start;
2269 hook->stop = _event_socket_stop;
2270 hook->check = _event_socket_check;
2271 hook->peek = _event_socket_peek;
2272
Spencer Low753d4852015-07-30 23:07:55 -07002273 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002274 _event_socket_start( hook );
2275}
2276
2277/** SOCKETPAIR EVENT HOOKS
2278 **/
2279
2280static void _event_socketpair_prepare( EventHook hook )
2281{
2282 FH fh = hook->fh;
2283 SocketPair pair = fh->fh_pair;
2284 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2285 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2286
2287 if (hook->wanted & FDE_READ && rbip->can_read)
2288 hook->ready |= FDE_READ;
2289
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002290 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002291 hook->ready |= FDE_WRITE;
2292 }
2293
2294 static int _event_socketpair_start( EventHook hook )
2295 {
2296 FH fh = hook->fh;
2297 SocketPair pair = fh->fh_pair;
2298 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2299 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2300
2301 if (hook->wanted == FDE_READ)
2302 hook->h = rbip->evt_read;
2303
2304 else if (hook->wanted == FDE_WRITE)
2305 hook->h = wbip->evt_write;
2306
2307 else {
Yabin Cui815ad882015-09-02 17:44:28 -07002308 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002309 return 0;
2310 }
Yabin Cui815ad882015-09-02 17:44:28 -07002311 D( "_event_socketpair_start: hook %s for %x wanted=%x",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002312 hook->fh->name, _fh_to_int(fh), hook->wanted);
2313 return 1;
2314}
2315
2316static int _event_socketpair_peek( EventHook hook )
2317{
2318 _event_socketpair_prepare( hook );
2319 return hook->ready != 0;
2320}
2321
2322static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2323{
2324 hook->prepare = _event_socketpair_prepare;
2325 hook->start = _event_socketpair_start;
2326 hook->peek = _event_socketpair_peek;
2327}
2328
2329
2330void
2331adb_sysdeps_init( void )
2332{
2333#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2334#include "mutex_list.h"
2335 InitializeCriticalSection( &_win32_lock );
2336}
2337
Spencer Lowbeb61982015-03-01 15:06:21 -08002338/**************************************************************************/
2339/**************************************************************************/
2340/***** *****/
2341/***** Console Window Terminal Emulation *****/
2342/***** *****/
2343/**************************************************************************/
2344/**************************************************************************/
2345
2346// This reads input from a Win32 console window and translates it into Unix
2347// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2348// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2349// is emulated instead of xterm because it is probably more popular than xterm:
2350// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2351// supports modern fonts, etc. It seems best to emulate the terminal that most
2352// Android developers use because they'll fix apps (the shell, etc.) to keep
2353// working with that terminal's emulation.
2354//
2355// The point of this emulation is not to be perfect or to solve all issues with
2356// console windows on Windows, but to be better than the original code which
2357// just called read() (which called ReadFile(), which called ReadConsoleA())
2358// which did not support Ctrl-C, tab completion, shell input line editing
2359// keys, server echo, and more.
2360//
2361// This implementation reconfigures the console with SetConsoleMode(), then
2362// calls ReadConsoleInput() to get raw input which it remaps to Unix
2363// terminal-style sequences which is returned via unix_read() which is used
2364// by the 'adb shell' command.
2365//
2366// Code organization:
2367//
2368// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2369// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2370// * _console_read() is the main code of the emulation.
2371
2372
2373// Read an input record from the console; one that should be processed.
2374static bool _get_interesting_input_record_uncached(const HANDLE console,
2375 INPUT_RECORD* const input_record) {
2376 for (;;) {
2377 DWORD read_count = 0;
2378 memset(input_record, 0, sizeof(*input_record));
2379 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2380 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
Spencer Low1711e012015-08-02 18:50:17 -07002381 "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002382 errno = EIO;
2383 return false;
2384 }
2385
2386 if (read_count == 0) { // should be impossible
2387 fatal("ReadConsoleInputA returned 0");
2388 }
2389
2390 if (read_count != 1) { // should be impossible
2391 fatal("ReadConsoleInputA did not return one input record");
2392 }
2393
2394 if ((input_record->EventType == KEY_EVENT) &&
2395 (input_record->Event.KeyEvent.bKeyDown)) {
2396 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2397 fatal("ReadConsoleInputA returned a key event with zero repeat"
2398 " count");
2399 }
2400
2401 // Got an interesting INPUT_RECORD, so return
2402 return true;
2403 }
2404 }
2405}
2406
2407// Cached input record (in case _console_read() is passed a buffer that doesn't
2408// have enough space to fit wRepeatCount number of key sequences). A non-zero
2409// wRepeatCount indicates that a record is cached.
2410static INPUT_RECORD _win32_input_record;
2411
2412// Get the next KEY_EVENT_RECORD that should be processed.
2413static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2414 // If nothing cached, read directly from the console until we get an
2415 // interesting record.
2416 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2417 if (!_get_interesting_input_record_uncached(console,
2418 &_win32_input_record)) {
2419 // There was an error, so make sure wRepeatCount is zero because
2420 // that signifies no cached input record.
2421 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2422 return NULL;
2423 }
2424 }
2425
2426 return &_win32_input_record.Event.KeyEvent;
2427}
2428
2429static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2430 return (control_key_state & SHIFT_PRESSED) != 0;
2431}
2432
2433static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2434 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2435}
2436
2437static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2438 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2439}
2440
2441static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2442 return (control_key_state & NUMLOCK_ON) != 0;
2443}
2444
2445static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2446 return (control_key_state & CAPSLOCK_ON) != 0;
2447}
2448
2449static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2450 return (control_key_state & ENHANCED_KEY) != 0;
2451}
2452
2453// Constants from MSDN for ToAscii().
2454static const BYTE TOASCII_KEY_OFF = 0x00;
2455static const BYTE TOASCII_KEY_DOWN = 0x80;
2456static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2457
2458// Given a key event, ignore a modifier key and return the character that was
2459// entered without the modifier. Writes to *ch and returns the number of bytes
2460// written.
2461static size_t _get_char_ignoring_modifier(char* const ch,
2462 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2463 const WORD modifier) {
2464 // If there is no character from Windows, try ignoring the specified
2465 // modifier and look for a character. Note that if AltGr is being used,
2466 // there will be a character from Windows.
2467 if (key_event->uChar.AsciiChar == '\0') {
2468 // Note that we read the control key state from the passed in argument
2469 // instead of from key_event since the argument has been normalized.
2470 if (((modifier == VK_SHIFT) &&
2471 _is_shift_pressed(control_key_state)) ||
2472 ((modifier == VK_CONTROL) &&
2473 _is_ctrl_pressed(control_key_state)) ||
2474 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2475
2476 BYTE key_state[256] = {0};
2477 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2478 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2479 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2480 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2481 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2482 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2483 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2484 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2485
2486 // cause this modifier to be ignored
2487 key_state[modifier] = TOASCII_KEY_OFF;
2488
2489 WORD translated = 0;
2490 if (ToAscii(key_event->wVirtualKeyCode,
2491 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2492 // Ignoring the modifier, we found a character.
2493 *ch = (CHAR)translated;
2494 return 1;
2495 }
2496 }
2497 }
2498
2499 // Just use whatever Windows told us originally.
2500 *ch = key_event->uChar.AsciiChar;
2501
2502 // If the character from Windows is NULL, return a size of zero.
2503 return (*ch == '\0') ? 0 : 1;
2504}
2505
2506// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2507// but taking into account the shift key. This is because for a sequence like
2508// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2509// we want to find the character ')'.
2510//
2511// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2512// because it is the default key-sequence to switch the input language.
2513// This is configurable in the Region and Language control panel.
2514static __inline__ size_t _get_non_control_char(char* const ch,
2515 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2516 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2517 VK_CONTROL);
2518}
2519
2520// Get without Alt.
2521static __inline__ size_t _get_non_alt_char(char* const ch,
2522 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2523 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2524 VK_MENU);
2525}
2526
2527// Ignore the control key, find the character from Windows, and apply any
2528// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2529// *pch and returns number of bytes written.
2530static size_t _get_control_character(char* const pch,
2531 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2532 const size_t len = _get_non_control_char(pch, key_event,
2533 control_key_state);
2534
2535 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2536 char ch = *pch;
2537 switch (ch) {
2538 case '2':
2539 case '@':
2540 case '`':
2541 ch = '\0';
2542 break;
2543 case '3':
2544 case '[':
2545 case '{':
2546 ch = '\x1b';
2547 break;
2548 case '4':
2549 case '\\':
2550 case '|':
2551 ch = '\x1c';
2552 break;
2553 case '5':
2554 case ']':
2555 case '}':
2556 ch = '\x1d';
2557 break;
2558 case '6':
2559 case '^':
2560 case '~':
2561 ch = '\x1e';
2562 break;
2563 case '7':
2564 case '-':
2565 case '_':
2566 ch = '\x1f';
2567 break;
2568 case '8':
2569 ch = '\x7f';
2570 break;
2571 case '/':
2572 if (!_is_alt_pressed(control_key_state)) {
2573 ch = '\x1f';
2574 }
2575 break;
2576 case '?':
2577 if (!_is_alt_pressed(control_key_state)) {
2578 ch = '\x7f';
2579 }
2580 break;
2581 }
2582 *pch = ch;
2583 }
2584
2585 return len;
2586}
2587
2588static DWORD _normalize_altgr_control_key_state(
2589 const KEY_EVENT_RECORD* const key_event) {
2590 DWORD control_key_state = key_event->dwControlKeyState;
2591
2592 // If we're in an AltGr situation where the AltGr key is down (depending on
2593 // the keyboard layout, that might be the physical right alt key which
2594 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2595 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2596 // a character (which indicates that there was an AltGr mapping), then act
2597 // as if alt and control are not really down for the purposes of modifiers.
2598 // This makes it so that if the user with, say, a German keyboard layout
2599 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2600 // output the key and we don't see the Alt and Ctrl keys.
2601 if (_is_ctrl_pressed(control_key_state) &&
2602 _is_alt_pressed(control_key_state)
2603 && (key_event->uChar.AsciiChar != '\0')) {
2604 // Try to remove as few bits as possible to improve our chances of
2605 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2606 // Left-Alt + Right-Ctrl + AltGr.
2607 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2608 // Remove Right-Alt.
2609 control_key_state &= ~RIGHT_ALT_PRESSED;
2610 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2611 // pressed, Left-Ctrl is almost always set, except if the user
2612 // presses Right-Ctrl, then AltGr (in that specific order) for
2613 // whatever reason. At any rate, make sure the bit is not set.
2614 control_key_state &= ~LEFT_CTRL_PRESSED;
2615 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2616 // Remove Left-Alt.
2617 control_key_state &= ~LEFT_ALT_PRESSED;
2618 // Whichever Ctrl key is down, remove it from the state. We only
2619 // remove one key, to improve our chances of detecting the
2620 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2621 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2622 // Remove Left-Ctrl.
2623 control_key_state &= ~LEFT_CTRL_PRESSED;
2624 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2625 // Remove Right-Ctrl.
2626 control_key_state &= ~RIGHT_CTRL_PRESSED;
2627 }
2628 }
2629
2630 // Note that this logic isn't 100% perfect because Windows doesn't
2631 // allow us to detect all combinations because a physical AltGr key
2632 // press shows up as two bits, plus some combinations are ambiguous
2633 // about what is actually physically pressed.
2634 }
2635
2636 return control_key_state;
2637}
2638
2639// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2640// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2641// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2642// appropriately.
2643static DWORD _normalize_keypad_control_key_state(const WORD vk,
2644 const DWORD control_key_state) {
2645 if (!_is_numlock_on(control_key_state)) {
2646 return control_key_state;
2647 }
2648 if (!_is_enhanced_key(control_key_state)) {
2649 switch (vk) {
2650 case VK_INSERT: // 0
2651 case VK_DELETE: // .
2652 case VK_END: // 1
2653 case VK_DOWN: // 2
2654 case VK_NEXT: // 3
2655 case VK_LEFT: // 4
2656 case VK_CLEAR: // 5
2657 case VK_RIGHT: // 6
2658 case VK_HOME: // 7
2659 case VK_UP: // 8
2660 case VK_PRIOR: // 9
2661 return control_key_state | SHIFT_PRESSED;
2662 }
2663 }
2664
2665 return control_key_state;
2666}
2667
2668static const char* _get_keypad_sequence(const DWORD control_key_state,
2669 const char* const normal, const char* const shifted) {
2670 if (_is_shift_pressed(control_key_state)) {
2671 // Shift is pressed and NumLock is off
2672 return shifted;
2673 } else {
2674 // Shift is not pressed and NumLock is off, or,
2675 // Shift is pressed and NumLock is on, in which case we want the
2676 // NumLock and Shift to neutralize each other, thus, we want the normal
2677 // sequence.
2678 return normal;
2679 }
2680 // If Shift is not pressed and NumLock is on, a different virtual key code
2681 // is returned by Windows, which can be taken care of by a different case
2682 // statement in _console_read().
2683}
2684
2685// Write sequence to buf and return the number of bytes written.
2686static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2687 DWORD control_key_state, const char* const normal) {
2688 // Copy the base sequence into buf.
2689 const size_t len = strlen(normal);
2690 memcpy(buf, normal, len);
2691
2692 int code = 0;
2693
2694 control_key_state = _normalize_keypad_control_key_state(vk,
2695 control_key_state);
2696
2697 if (_is_shift_pressed(control_key_state)) {
2698 code |= 0x1;
2699 }
2700 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2701 code |= 0x2;
2702 }
2703 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2704 code |= 0x4;
2705 }
2706 // If some modifier was held down, then we need to insert the modifier code
2707 if (code != 0) {
2708 if (len == 0) {
2709 // Should be impossible because caller should pass a string of
2710 // non-zero length.
2711 return 0;
2712 }
2713 size_t index = len - 1;
2714 const char lastChar = buf[index];
2715 if (lastChar != '~') {
2716 buf[index++] = '1';
2717 }
2718 buf[index++] = ';'; // modifier separator
2719 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2720 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2721 buf[index++] = '1' + code;
2722 buf[index++] = lastChar; // move ~ (or other last char) to the end
2723 return index;
2724 }
2725 return len;
2726}
2727
2728// Write sequence to buf and return the number of bytes written.
2729static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2730 const DWORD control_key_state, const char* const normal,
2731 const char shifted) {
2732 if (_is_shift_pressed(control_key_state)) {
2733 // Shift is pressed and NumLock is off
2734 if (shifted != '\0') {
2735 buf[0] = shifted;
2736 return sizeof(buf[0]);
2737 } else {
2738 return 0;
2739 }
2740 } else {
2741 // Shift is not pressed and NumLock is off, or,
2742 // Shift is pressed and NumLock is on, in which case we want the
2743 // NumLock and Shift to neutralize each other, thus, we want the normal
2744 // sequence.
2745 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2746 }
2747 // If Shift is not pressed and NumLock is on, a different virtual key code
2748 // is returned by Windows, which can be taken care of by a different case
2749 // statement in _console_read().
2750}
2751
2752// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2753// Standard German. Figure this out at runtime so we know what to output for
2754// Shift-VK_DELETE.
2755static char _get_decimal_char() {
2756 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2757}
2758
2759// Prefix the len bytes in buf with the escape character, and then return the
2760// new buffer length.
2761size_t _escape_prefix(char* const buf, const size_t len) {
2762 // If nothing to prefix, don't do anything. We might be called with
2763 // len == 0, if alt was held down with a dead key which produced nothing.
2764 if (len == 0) {
2765 return 0;
2766 }
2767
2768 memmove(&buf[1], buf, len);
2769 buf[0] = '\x1b';
2770 return len + 1;
2771}
2772
2773// Writes to buffer buf (of length len), returning number of bytes written or
2774// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2775// (as far as I can tell).
2776static int _console_read(const HANDLE console, void* buf, size_t len) {
2777 for (;;) {
2778 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2779 if (key_event == NULL) {
2780 return -1;
2781 }
2782
2783 const WORD vk = key_event->wVirtualKeyCode;
2784 const CHAR ch = key_event->uChar.AsciiChar;
2785 const DWORD control_key_state = _normalize_altgr_control_key_state(
2786 key_event);
2787
2788 // The following emulation code should write the output sequence to
2789 // either seqstr or to seqbuf and seqbuflen.
2790 const char* seqstr = NULL; // NULL terminated C-string
2791 // Enough space for max sequence string below, plus modifiers and/or
2792 // escape prefix.
2793 char seqbuf[16];
2794 size_t seqbuflen = 0; // Space used in seqbuf.
2795
2796#define MATCH(vk, normal) \
2797 case (vk): \
2798 { \
2799 seqstr = (normal); \
2800 } \
2801 break;
2802
2803 // Modifier keys should affect the output sequence.
2804#define MATCH_MODIFIER(vk, normal) \
2805 case (vk): \
2806 { \
2807 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2808 control_key_state, (normal)); \
2809 } \
2810 break;
2811
2812 // The shift key should affect the output sequence.
2813#define MATCH_KEYPAD(vk, normal, shifted) \
2814 case (vk): \
2815 { \
2816 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2817 (shifted)); \
2818 } \
2819 break;
2820
2821 // The shift key and other modifier keys should affect the output
2822 // sequence.
2823#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2824 case (vk): \
2825 { \
2826 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2827 control_key_state, (normal), (shifted)); \
2828 } \
2829 break;
2830
2831#define ESC "\x1b"
2832#define CSI ESC "["
2833#define SS3 ESC "O"
2834
2835 // Only support normal mode, not application mode.
2836
2837 // Enhanced keys:
2838 // * 6-pack: insert, delete, home, end, page up, page down
2839 // * cursor keys: up, down, right, left
2840 // * keypad: divide, enter
2841 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2842 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2843 if (_is_enhanced_key(control_key_state)) {
2844 switch (vk) {
2845 case VK_RETURN: // Enter key on keypad
2846 if (_is_ctrl_pressed(control_key_state)) {
2847 seqstr = "\n";
2848 } else {
2849 seqstr = "\r";
2850 }
2851 break;
2852
2853 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2854 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2855
2856 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2857 // will be fixed soon to match xterm which sends CSI "F" and
2858 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2859 MATCH(VK_END, CSI "F");
2860 MATCH(VK_HOME, CSI "H");
2861
2862 MATCH_MODIFIER(VK_LEFT, CSI "D");
2863 MATCH_MODIFIER(VK_UP, CSI "A");
2864 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2865 MATCH_MODIFIER(VK_DOWN, CSI "B");
2866
2867 MATCH_MODIFIER(VK_INSERT, CSI "2~");
2868 MATCH_MODIFIER(VK_DELETE, CSI "3~");
2869
2870 MATCH(VK_DIVIDE, "/");
2871 }
2872 } else { // Non-enhanced keys:
2873 switch (vk) {
2874 case VK_BACK: // backspace
2875 if (_is_alt_pressed(control_key_state)) {
2876 seqstr = ESC "\x7f";
2877 } else {
2878 seqstr = "\x7f";
2879 }
2880 break;
2881
2882 case VK_TAB:
2883 if (_is_shift_pressed(control_key_state)) {
2884 seqstr = CSI "Z";
2885 } else {
2886 seqstr = "\t";
2887 }
2888 break;
2889
2890 // Number 5 key in keypad when NumLock is off, or if NumLock is
2891 // on and Shift is down.
2892 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2893
2894 case VK_RETURN: // Enter key on main keyboard
2895 if (_is_alt_pressed(control_key_state)) {
2896 seqstr = ESC "\n";
2897 } else if (_is_ctrl_pressed(control_key_state)) {
2898 seqstr = "\n";
2899 } else {
2900 seqstr = "\r";
2901 }
2902 break;
2903
2904 // VK_ESCAPE: Don't do any special handling. The OS uses many
2905 // of the sequences with Escape and many of the remaining
2906 // sequences don't produce bKeyDown messages, only !bKeyDown
2907 // for whatever reason.
2908
2909 case VK_SPACE:
2910 if (_is_alt_pressed(control_key_state)) {
2911 seqstr = ESC " ";
2912 } else if (_is_ctrl_pressed(control_key_state)) {
2913 seqbuf[0] = '\0'; // NULL char
2914 seqbuflen = 1;
2915 } else {
2916 seqstr = " ";
2917 }
2918 break;
2919
2920 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2921 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
2922
2923 MATCH_KEYPAD(VK_END, CSI "4~", "1");
2924 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2925
2926 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
2927 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
2928 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2929 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
2930
2931 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2932 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2933 _get_decimal_char());
2934
2935 case 0x30: // 0
2936 case 0x31: // 1
2937 case 0x39: // 9
2938 case VK_OEM_1: // ;:
2939 case VK_OEM_PLUS: // =+
2940 case VK_OEM_COMMA: // ,<
2941 case VK_OEM_PERIOD: // .>
2942 case VK_OEM_7: // '"
2943 case VK_OEM_102: // depends on keyboard, could be <> or \|
2944 case VK_OEM_2: // /?
2945 case VK_OEM_3: // `~
2946 case VK_OEM_4: // [{
2947 case VK_OEM_5: // \|
2948 case VK_OEM_6: // ]}
2949 {
2950 seqbuflen = _get_control_character(seqbuf, key_event,
2951 control_key_state);
2952
2953 if (_is_alt_pressed(control_key_state)) {
2954 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2955 }
2956 }
2957 break;
2958
2959 case 0x32: // 2
2960 case 0x36: // 6
2961 case VK_OEM_MINUS: // -_
2962 {
2963 seqbuflen = _get_control_character(seqbuf, key_event,
2964 control_key_state);
2965
2966 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2967 // prefix with escape.
2968 if (_is_alt_pressed(control_key_state) &&
2969 !(_is_ctrl_pressed(control_key_state) &&
2970 !_is_shift_pressed(control_key_state))) {
2971 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2972 }
2973 }
2974 break;
2975
2976 case 0x33: // 3
2977 case 0x34: // 4
2978 case 0x35: // 5
2979 case 0x37: // 7
2980 case 0x38: // 8
2981 {
2982 seqbuflen = _get_control_character(seqbuf, key_event,
2983 control_key_state);
2984
2985 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2986 // prefix with escape.
2987 if (_is_alt_pressed(control_key_state) &&
2988 !(_is_ctrl_pressed(control_key_state) &&
2989 !_is_shift_pressed(control_key_state))) {
2990 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2991 }
2992 }
2993 break;
2994
2995 case 0x41: // a
2996 case 0x42: // b
2997 case 0x43: // c
2998 case 0x44: // d
2999 case 0x45: // e
3000 case 0x46: // f
3001 case 0x47: // g
3002 case 0x48: // h
3003 case 0x49: // i
3004 case 0x4a: // j
3005 case 0x4b: // k
3006 case 0x4c: // l
3007 case 0x4d: // m
3008 case 0x4e: // n
3009 case 0x4f: // o
3010 case 0x50: // p
3011 case 0x51: // q
3012 case 0x52: // r
3013 case 0x53: // s
3014 case 0x54: // t
3015 case 0x55: // u
3016 case 0x56: // v
3017 case 0x57: // w
3018 case 0x58: // x
3019 case 0x59: // y
3020 case 0x5a: // z
3021 {
3022 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3023 control_key_state);
3024
3025 // If Alt is pressed, then prefix with escape.
3026 if (_is_alt_pressed(control_key_state)) {
3027 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3028 }
3029 }
3030 break;
3031
3032 // These virtual key codes are generated by the keys on the
3033 // keypad *when NumLock is on* and *Shift is up*.
3034 MATCH(VK_NUMPAD0, "0");
3035 MATCH(VK_NUMPAD1, "1");
3036 MATCH(VK_NUMPAD2, "2");
3037 MATCH(VK_NUMPAD3, "3");
3038 MATCH(VK_NUMPAD4, "4");
3039 MATCH(VK_NUMPAD5, "5");
3040 MATCH(VK_NUMPAD6, "6");
3041 MATCH(VK_NUMPAD7, "7");
3042 MATCH(VK_NUMPAD8, "8");
3043 MATCH(VK_NUMPAD9, "9");
3044
3045 MATCH(VK_MULTIPLY, "*");
3046 MATCH(VK_ADD, "+");
3047 MATCH(VK_SUBTRACT, "-");
3048 // VK_DECIMAL is generated by the . key on the keypad *when
3049 // NumLock is on* and *Shift is up* and the sequence is not
3050 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3051 // Windows Security screen to come up).
3052 case VK_DECIMAL:
3053 // U.S. English uses '.', Germany German uses ','.
3054 seqbuflen = _get_non_control_char(seqbuf, key_event,
3055 control_key_state);
3056 break;
3057
3058 MATCH_MODIFIER(VK_F1, SS3 "P");
3059 MATCH_MODIFIER(VK_F2, SS3 "Q");
3060 MATCH_MODIFIER(VK_F3, SS3 "R");
3061 MATCH_MODIFIER(VK_F4, SS3 "S");
3062 MATCH_MODIFIER(VK_F5, CSI "15~");
3063 MATCH_MODIFIER(VK_F6, CSI "17~");
3064 MATCH_MODIFIER(VK_F7, CSI "18~");
3065 MATCH_MODIFIER(VK_F8, CSI "19~");
3066 MATCH_MODIFIER(VK_F9, CSI "20~");
3067 MATCH_MODIFIER(VK_F10, CSI "21~");
3068 MATCH_MODIFIER(VK_F11, CSI "23~");
3069 MATCH_MODIFIER(VK_F12, CSI "24~");
3070
3071 MATCH_MODIFIER(VK_F13, CSI "25~");
3072 MATCH_MODIFIER(VK_F14, CSI "26~");
3073 MATCH_MODIFIER(VK_F15, CSI "28~");
3074 MATCH_MODIFIER(VK_F16, CSI "29~");
3075 MATCH_MODIFIER(VK_F17, CSI "31~");
3076 MATCH_MODIFIER(VK_F18, CSI "32~");
3077 MATCH_MODIFIER(VK_F19, CSI "33~");
3078 MATCH_MODIFIER(VK_F20, CSI "34~");
3079
3080 // MATCH_MODIFIER(VK_F21, ???);
3081 // MATCH_MODIFIER(VK_F22, ???);
3082 // MATCH_MODIFIER(VK_F23, ???);
3083 // MATCH_MODIFIER(VK_F24, ???);
3084 }
3085 }
3086
3087#undef MATCH
3088#undef MATCH_MODIFIER
3089#undef MATCH_KEYPAD
3090#undef MATCH_MODIFIER_KEYPAD
3091#undef ESC
3092#undef CSI
3093#undef SS3
3094
3095 const char* out;
3096 size_t outlen;
3097
3098 // Check for output in any of:
3099 // * seqstr is set (and strlen can be used to determine the length).
3100 // * seqbuf and seqbuflen are set
3101 // Fallback to ch from Windows.
3102 if (seqstr != NULL) {
3103 out = seqstr;
3104 outlen = strlen(seqstr);
3105 } else if (seqbuflen > 0) {
3106 out = seqbuf;
3107 outlen = seqbuflen;
3108 } else if (ch != '\0') {
3109 // Use whatever Windows told us it is.
3110 seqbuf[0] = ch;
3111 seqbuflen = 1;
3112 out = seqbuf;
3113 outlen = seqbuflen;
3114 } else {
3115 // No special handling for the virtual key code and Windows isn't
3116 // telling us a character code, then we don't know how to translate
3117 // the key press.
3118 //
3119 // Consume the input and 'continue' to cause us to get a new key
3120 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07003121 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08003122 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3123 key_event->wRepeatCount = 0;
3124 continue;
3125 }
3126
3127 int bytesRead = 0;
3128
3129 // put output wRepeatCount times into buf/len
3130 while (key_event->wRepeatCount > 0) {
3131 if (len >= outlen) {
3132 // Write to buf/len
3133 memcpy(buf, out, outlen);
3134 buf = (void*)((char*)buf + outlen);
3135 len -= outlen;
3136 bytesRead += outlen;
3137
3138 // consume the input
3139 --key_event->wRepeatCount;
3140 } else {
3141 // Not enough space, so just leave it in _win32_input_record
3142 // for a subsequent retrieval.
3143 if (bytesRead == 0) {
3144 // We didn't write anything because there wasn't enough
3145 // space to even write one sequence. This should never
3146 // happen if the caller uses sensible buffer sizes
3147 // (i.e. >= maximum sequence length which is probably a
3148 // few bytes long).
3149 D("_console_read: no buffer space to write one sequence; "
3150 "buffer: %ld, sequence: %ld\n", (long)len,
3151 (long)outlen);
3152 errno = ENOMEM;
3153 return -1;
3154 } else {
3155 // Stop trying to write to buf/len, just return whatever
3156 // we wrote so far.
3157 break;
3158 }
3159 }
3160 }
3161
3162 return bytesRead;
3163 }
3164}
3165
3166static DWORD _old_console_mode; // previous GetConsoleMode() result
3167static HANDLE _console_handle; // when set, console mode should be restored
3168
3169void stdin_raw_init(const int fd) {
3170 if (STDIN_FILENO == fd) {
3171 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3172 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3173 return;
3174 }
3175
3176 if (GetFileType(in) != FILE_TYPE_CHAR) {
3177 // stdin might be a file or pipe.
3178 return;
3179 }
3180
3181 if (!GetConsoleMode(in, &_old_console_mode)) {
3182 // If GetConsoleMode() fails, stdin is probably is not a console.
3183 return;
3184 }
3185
3186 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3187 // calling the process Ctrl-C routine (configured by
3188 // SetConsoleCtrlHandler()).
3189 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3190 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3191 // flag also seems necessary to have proper line-ending processing.
3192 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3193 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3194 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003195 D("stdin_raw_init: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003196 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003197 }
3198
3199 // Once this is set, it means that stdin has been configured for
3200 // reading from and that the old console mode should be restored later.
3201 _console_handle = in;
3202
3203 // Note that we don't need to configure C Runtime line-ending
3204 // translation because _console_read() does not call the C Runtime to
3205 // read from the console.
3206 }
3207}
3208
3209void stdin_raw_restore(const int fd) {
3210 if (STDIN_FILENO == fd) {
3211 if (_console_handle != NULL) {
3212 const HANDLE in = _console_handle;
3213 _console_handle = NULL; // clear state
3214
3215 if (!SetConsoleMode(in, _old_console_mode)) {
3216 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003217 D("stdin_raw_restore: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003218 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003219 }
3220 }
3221 }
3222}
3223
Spencer Low3a2421b2015-05-22 20:09:06 -07003224// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003225int unix_read(int fd, void* buf, size_t len) {
3226 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3227 // If it is a request to read from stdin, and stdin_raw_init() has been
3228 // called, and it successfully configured the console, then read from
3229 // the console using Win32 console APIs and partially emulate a unix
3230 // terminal.
3231 return _console_read(_console_handle, buf, len);
3232 } else {
3233 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003234 // can do LF/CR translation (which is overridable with _setmode()).
3235 // Undefine the macro that is set in sysdeps.h which bans calls to
3236 // plain read() in favor of unix_read() or adb_read().
3237#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003238#undef read
3239 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003240#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003241 }
3242}
Spencer Low6815c072015-05-11 01:08:48 -07003243
3244/**************************************************************************/
3245/**************************************************************************/
3246/***** *****/
3247/***** Unicode support *****/
3248/***** *****/
3249/**************************************************************************/
3250/**************************************************************************/
3251
3252// This implements support for using files with Unicode filenames and for
3253// outputting Unicode text to a Win32 console window. This is inspired from
3254// http://utf8everywhere.org/.
3255//
3256// Background
3257// ----------
3258//
3259// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3260// filenames to APIs such as open(). This works because filenames are largely
3261// opaque 'cookies' (perhaps excluding path separators).
3262//
3263// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3264// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3265// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3266// CreateFile() API is really just a macro that adds the W/A based on whether
3267// the UNICODE preprocessor symbol is defined).
3268//
3269// Options
3270// -------
3271//
3272// Thus, to write a portable program, there are a few options:
3273//
3274// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3275// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3276// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3277// open() API.
3278//
3279// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3280// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3281// potentially touching a lot of code.
3282//
3283// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3284// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3285// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3286// or C Runtime API.
3287//
3288// The Choice
3289// ----------
3290//
3291// The code below chooses option 3, the UTF-8 everywhere strategy. It
3292// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3293// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3294// args that are passed to main() at the beginning of program startup. We also
3295// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3296// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3297//
3298// Unicode console output
3299// ----------------------
3300//
3301// The way to output Unicode to a Win32 console window is to call
3302// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003303// such as Lucida Console or Consolas, and in the case of East Asian languages
3304// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3305// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3306// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003307//
3308// The problem is getting the C Runtime to make fprintf and related APIs call
3309// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3310// promising, but the various modes have issues:
3311//
3312// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3313// UTF-16 do not display properly.
3314// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3315// totally wrong.
3316// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3317// handler to be called (upon a later I/O call), aborting the process.
3318// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3319// to output nothing.
3320//
3321// So the only solution is to write our own adb_fprintf() that converts UTF-8
3322// to UTF-16 and then calls WriteConsoleW().
3323
3324
3325// Function prototype because attributes cannot be placed on func definitions.
3326static void _widen_fatal(const char *fmt, ...)
3327 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3328
3329// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3330// called from those functions.
3331static void _widen_fatal(const char *fmt, ...) {
3332 va_list ap;
3333 va_start(ap, fmt);
3334 // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3335 // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3336 // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3337 // By directly calling real C Runtime APIs that don't properly output
3338 // Unicode, but will be able to get a comprehendible message out. To do
3339 // this, make sure we don't call (v)fprintf macros by undefining them.
3340#pragma push_macro("fprintf")
3341#pragma push_macro("vfprintf")
3342#undef fprintf
3343#undef vfprintf
3344 fprintf(stderr, "error: ");
3345 vfprintf(stderr, fmt, ap);
3346 fprintf(stderr, "\n");
3347#pragma pop_macro("vfprintf")
3348#pragma pop_macro("fprintf")
3349 va_end(ap);
3350 exit(-1);
3351}
3352
3353// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3354// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3355
3356// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3357// string. Any other size specifies the number of chars to convert, excluding
3358// any NULL terminator (if you're passing an explicit size, you probably don't
3359// have a NULL terminated string in the first place).
3360std::wstring widen(const char* utf8, const int size) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003361 // Note: Do not call SystemErrorCodeToString() from widen() because
3362 // SystemErrorCodeToString() calls narrow() which may call fatal() which
3363 // calls adb_vfprintf() which calls widen(), potentially causing infinite
3364 // recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003365 const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3366 NULL, 0);
3367 if (chars_to_convert <= 0) {
3368 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3369 _widen_fatal("MultiByteToWideChar failed counting: %d, "
3370 "GetLastError: %lu", chars_to_convert, GetLastError());
3371 }
3372
3373 std::wstring utf16;
3374 size_t chars_to_allocate = chars_to_convert;
3375 if (size == -1) {
3376 // chars_to_convert includes a NULL terminator, so subtract space
3377 // for that because resize() includes that itself.
3378 --chars_to_allocate;
3379 }
3380 utf16.resize(chars_to_allocate);
3381
3382 // This uses &string[0] to get write-access to the entire string buffer
3383 // which may be assuming that the chars are all contiguous, but it seems
3384 // to work and saves us the hassle of using a temporary
3385 // std::vector<wchar_t>.
3386 const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3387 chars_to_convert);
3388 if (result != chars_to_convert) {
3389 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3390 _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3391 "GetLastError: %lu", result, GetLastError());
3392 }
3393
3394 // If a size was passed in (size != -1), then the string is NULL terminated
3395 // by a NULL char that was written by std::string::resize(). If size == -1,
3396 // then MultiByteToWideChar() read a NULL terminator from the original
3397 // string and converted it to a NULL UTF-16 char in the output.
3398
3399 return utf16;
3400}
3401
3402// Convert a NULL terminated string from UTF-8 to UTF-16.
3403std::wstring widen(const char* utf8) {
3404 // Pass -1 to let widen() determine the string length.
3405 return widen(utf8, -1);
3406}
3407
3408// Convert from UTF-8 to UTF-16.
3409std::wstring widen(const std::string& utf8) {
3410 return widen(utf8.c_str(), utf8.length());
3411}
3412
3413// Convert from UTF-16 to UTF-8.
3414std::string narrow(const std::wstring& utf16) {
3415 return narrow(utf16.c_str());
3416}
3417
3418// Convert from UTF-16 to UTF-8.
3419std::string narrow(const wchar_t* utf16) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003420 // Note: Do not call SystemErrorCodeToString() from narrow() because
Elliott Hughes1ba53092015-08-03 16:26:13 -07003421 // SystemErrorCodeToString() calls narrow() and we don't want potential
Spencer Lowcc467f12015-08-02 18:13:54 -07003422 // infinite recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003423 const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3424 0, NULL, NULL);
3425 if (chars_required <= 0) {
3426 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003427 fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003428 chars_required, GetLastError());
3429 }
3430
3431 std::string utf8;
3432 // Subtract space for the NULL terminator because resize() includes
3433 // that itself. Note that this could potentially throw a std::bad_alloc
3434 // exception.
3435 utf8.resize(chars_required - 1);
3436
3437 // This uses &string[0] to get write-access to the entire string buffer
3438 // which may be assuming that the chars are all contiguous, but it seems
3439 // to work and saves us the hassle of using a temporary
3440 // std::vector<char>.
3441 const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3442 chars_required, NULL, NULL);
3443 if (result != chars_required) {
3444 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003445 fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003446 result, GetLastError());
3447 }
3448
3449 return utf8;
3450}
3451
3452// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3453// be passed to main().
3454NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3455 narrow_args = new char*[argc + 1];
3456
3457 for (int i = 0; i < argc; ++i) {
3458 narrow_args[i] = strdup(narrow(argv[i]).c_str());
3459 }
3460 narrow_args[argc] = nullptr; // terminate
3461}
3462
3463NarrowArgs::~NarrowArgs() {
3464 if (narrow_args != nullptr) {
3465 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3466 free(*argp);
3467 }
3468 delete[] narrow_args;
3469 narrow_args = nullptr;
3470 }
3471}
3472
3473int unix_open(const char* path, int options, ...) {
3474 if ((options & O_CREAT) == 0) {
3475 return _wopen(widen(path).c_str(), options);
3476 } else {
3477 int mode;
3478 va_list args;
3479 va_start(args, options);
3480 mode = va_arg(args, int);
3481 va_end(args);
3482 return _wopen(widen(path).c_str(), options, mode);
3483 }
3484}
3485
3486// Version of stat() that takes a UTF-8 path.
3487int adb_stat(const char* f, struct adb_stat* s) {
3488#pragma push_macro("wstat")
3489// This definition of wstat seems to be missing from <sys/stat.h>.
3490#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3491#ifdef _USE_32BIT_TIME_T
3492#define wstat _wstat32i64
3493#else
3494#define wstat _wstat64
3495#endif
3496#else
3497// <sys/stat.h> has a function prototype for wstat() that should be available.
3498#endif
3499
3500 return wstat(widen(f).c_str(), s);
3501
3502#pragma pop_macro("wstat")
3503}
3504
3505// Version of opendir() that takes a UTF-8 path.
3506DIR* adb_opendir(const char* name) {
3507 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3508 // the fields, but right now all the callers treat the structure as
3509 // opaque.
3510 return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3511}
3512
3513// Version of readdir() that returns UTF-8 paths.
3514struct dirent* adb_readdir(DIR* dir) {
3515 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3516 struct _wdirent* const went = _wreaddir(wdir);
3517 if (went == nullptr) {
3518 return nullptr;
3519 }
3520 // Convert from UTF-16 to UTF-8.
3521 const std::string name_utf8(narrow(went->d_name));
3522
3523 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3524 // space for UTF-16 wchar_t's) with UTF-8 char's.
3525 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3526
3527 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3528 // Name too big to fit in existing buffer.
3529 errno = ENOMEM;
3530 return nullptr;
3531 }
3532
3533 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3534 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3535 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3536 // bigger than the caller expects because they expect a dirent structure
3537 // which has a smaller d_name field. Ignore this since the caller should be
3538 // resilient.
3539
3540 // Rewrite the UTF-16 d_name field to UTF-8.
3541 strcpy(ent->d_name, name_utf8.c_str());
3542
3543 return ent;
3544}
3545
3546// Version of closedir() to go with our version of adb_opendir().
3547int adb_closedir(DIR* dir) {
3548 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3549}
3550
3551// Version of unlink() that takes a UTF-8 path.
3552int adb_unlink(const char* path) {
3553 const std::wstring wpath(widen(path));
3554
3555 int rc = _wunlink(wpath.c_str());
3556
3557 if (rc == -1 && errno == EACCES) {
3558 /* unlink returns EACCES when the file is read-only, so we first */
3559 /* try to make it writable, then unlink again... */
3560 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3561 if (rc == 0)
3562 rc = _wunlink(wpath.c_str());
3563 }
3564 return rc;
3565}
3566
3567// Version of mkdir() that takes a UTF-8 path.
3568int adb_mkdir(const std::string& path, int mode) {
3569 return _wmkdir(widen(path.c_str()).c_str());
3570}
3571
3572// Version of utime() that takes a UTF-8 path.
3573int adb_utime(const char* path, struct utimbuf* u) {
3574 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3575 "utimbuf and _utimbuf should be the same size because they both "
3576 "contain the same types, namely time_t");
3577 return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3578}
3579
3580// Version of chmod() that takes a UTF-8 path.
3581int adb_chmod(const char* path, int mode) {
3582 return _wchmod(widen(path).c_str(), mode);
3583}
3584
3585// Internal function to get a Win32 console HANDLE from a C Runtime FILE*.
3586static HANDLE _get_console_handle(FILE* const stream) {
3587 // Get a C Runtime file descriptor number from the FILE* structure.
3588 const int fd = fileno(stream);
3589 if (fd < 0) {
3590 return NULL;
3591 }
3592
3593 // If it is not a "character device", it is probably a file and not a
3594 // console. Do this check early because it is probably cheap. Still do more
3595 // checks after this since there are devices that pass this test, but are
3596 // not a console, such as NUL, the Windows /dev/null equivalent (I think).
3597 if (!isatty(fd)) {
3598 return NULL;
3599 }
3600
3601 // Given a C Runtime file descriptor number, get the underlying OS
3602 // file handle.
3603 const intptr_t osfh = _get_osfhandle(fd);
3604 if (osfh == -1) {
3605 return NULL;
3606 }
3607
3608 const HANDLE h = reinterpret_cast<const HANDLE>(osfh);
3609
3610 DWORD old_mode = 0;
3611 if (!GetConsoleMode(h, &old_mode)) {
3612 return NULL;
3613 }
3614
3615 // If GetConsoleMode() was successful, assume this is a console.
3616 return h;
3617}
3618
3619// Internal helper function to write UTF-8 bytes to a console. Returns -1
3620// on error.
3621static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3622 HANDLE console) {
3623 // Convert from UTF-8 to UTF-16.
3624 // This could throw std::bad_alloc.
3625 const std::wstring output(widen(buf, size));
3626
3627 // Note that this does not do \n => \r\n translation because that
3628 // doesn't seem necessary for the Windows console. For the Windows
3629 // console \r moves to the beginning of the line and \n moves to a new
3630 // line.
3631
3632 // Flush any stream buffering so that our output is afterwards which
3633 // makes sense because our call is afterwards.
3634 (void)fflush(stream);
3635
3636 // Write UTF-16 to the console.
3637 DWORD written = 0;
3638 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3639 NULL)) {
3640 errno = EIO;
3641 return -1;
3642 }
3643
3644 // This is the number of UTF-16 chars written, which might be different
3645 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3646 // get this count correct.
3647 return written;
3648}
3649
3650// Function prototype because attributes cannot be placed on func definitions.
3651static int _console_vfprintf(const HANDLE console, FILE* stream,
3652 const char *format, va_list ap)
3653 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3654
3655// Internal function to format a UTF-8 string and write it to a Win32 console.
3656// Returns -1 on error.
3657static int _console_vfprintf(const HANDLE console, FILE* stream,
3658 const char *format, va_list ap) {
3659 std::string output_utf8;
3660
3661 // Format the string.
3662 // This could throw std::bad_alloc.
3663 android::base::StringAppendV(&output_utf8, format, ap);
3664
3665 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3666 stream, console);
3667}
3668
3669// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3670// Windows console.
3671int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3672 const HANDLE console = _get_console_handle(stream);
3673
3674 // If there is an associated Win32 console, write to it specially,
3675 // otherwise defer to the regular C Runtime, passing it UTF-8.
3676 if (console != NULL) {
3677 return _console_vfprintf(console, stream, format, ap);
3678 } else {
3679 // If vfprintf is a macro, undefine it, so we can call the real
3680 // C Runtime API.
3681#pragma push_macro("vfprintf")
3682#undef vfprintf
3683 return vfprintf(stream, format, ap);
3684#pragma pop_macro("vfprintf")
3685 }
3686}
3687
3688// Version of fprintf() that takes UTF-8 and can write Unicode to a
3689// Windows console.
3690int adb_fprintf(FILE *stream, const char *format, ...) {
3691 va_list ap;
3692 va_start(ap, format);
3693 const int result = adb_vfprintf(stream, format, ap);
3694 va_end(ap);
3695
3696 return result;
3697}
3698
3699// Version of printf() that takes UTF-8 and can write Unicode to a
3700// Windows console.
3701int adb_printf(const char *format, ...) {
3702 va_list ap;
3703 va_start(ap, format);
3704 const int result = adb_vfprintf(stdout, format, ap);
3705 va_end(ap);
3706
3707 return result;
3708}
3709
3710// Version of fputs() that takes UTF-8 and can write Unicode to a
3711// Windows console.
3712int adb_fputs(const char* buf, FILE* stream) {
3713 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3714 // which fputs (and hence adb_fputs) should return on error.
3715 return adb_fprintf(stream, "%s", buf);
3716}
3717
3718// Version of fputc() that takes UTF-8 and can write Unicode to a
3719// Windows console.
3720int adb_fputc(int ch, FILE* stream) {
3721 const int result = adb_fprintf(stream, "%c", ch);
3722 if (result <= 0) {
3723 // If there was an error, or if nothing was printed (which should be an
3724 // error), return an error, which fprintf signifies with EOF.
3725 return EOF;
3726 }
3727 // For success, fputc returns the char, cast to unsigned char, then to int.
3728 return static_cast<unsigned char>(ch);
3729}
3730
3731// Internal function to write UTF-8 to a Win32 console. Returns the number of
3732// items (of length size) written. On error, returns a short item count or 0.
3733static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3734 FILE* stream, HANDLE console) {
3735 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3736 // if we're passed only some of the bytes of a character (for example, from
3737 // the network socket for adb shell), we won't be able to convert the char
3738 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3739 // right.
3740 //
3741 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3742 //
3743 // For now we ignore this problem because the alternative is that we'd have
3744 // to parse UTF-8 and buffer things up (doable). At least this is better
3745 // than what we had before -- always incorrect multi-byte UTF-8 output.
3746 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3747 size * nmemb, stream, console);
3748 if (result == -1) {
3749 return 0;
3750 }
3751 return result / size;
3752}
3753
3754// Version of fwrite() that takes UTF-8 and can write Unicode to a
3755// Windows console.
3756size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3757 const HANDLE console = _get_console_handle(stream);
3758
3759 // If there is an associated Win32 console, write to it specially,
3760 // otherwise defer to the regular C Runtime, passing it UTF-8.
3761 if (console != NULL) {
3762 return _console_fwrite(ptr, size, nmemb, stream, console);
3763 } else {
3764 // If fwrite is a macro, undefine it, so we can call the real
3765 // C Runtime API.
3766#pragma push_macro("fwrite")
3767#undef fwrite
3768 return fwrite(ptr, size, nmemb, stream);
3769#pragma pop_macro("fwrite")
3770 }
3771}
3772
3773// Version of fopen() that takes a UTF-8 filename and can access a file with
3774// a Unicode filename.
3775FILE* adb_fopen(const char* f, const char* m) {
3776 return _wfopen(widen(f).c_str(), widen(m).c_str());
3777}
3778
3779// Shadow UTF-8 environment variable name/value pairs that are created from
3780// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003781// currently updated if putenv, setenv, unsetenv are called. Note that no
3782// thread synchronization is done, but we're called early enough in
3783// single-threaded startup that things work ok.
Spencer Low6815c072015-05-11 01:08:48 -07003784static std::unordered_map<std::string, char*> g_environ_utf8;
3785
3786// Make sure that shadow UTF-8 environment variables are setup.
3787static void _ensure_env_setup() {
3788 // If some name/value pairs exist, then we've already done the setup below.
3789 if (g_environ_utf8.size() != 0) {
3790 return;
3791 }
3792
3793 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3794 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3795 // to use the D() macro here because that tracing only works if the
3796 // ADB_TRACE environment variable is setup, but that env var can't be read
3797 // until this code completes.
3798 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3799 wchar_t* const equal = wcschr(*env, L'=');
3800 if (equal == nullptr) {
3801 // Malformed environment variable with no equal sign. Shouldn't
3802 // really happen, but we should be resilient to this.
3803 continue;
3804 }
3805
3806 const std::string name_utf8(narrow(std::wstring(*env, equal - *env)));
3807 char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3808
3809 // Overwrite any duplicate name, but there shouldn't be a dup in the
3810 // first place.
3811 g_environ_utf8[name_utf8] = value_utf8;
3812 }
3813}
3814
3815// Version of getenv() that takes a UTF-8 environment variable name and
3816// retrieves a UTF-8 value.
3817char* adb_getenv(const char* name) {
3818 _ensure_env_setup();
3819
Spencer Lowcc467f12015-08-02 18:13:54 -07003820 const auto it = g_environ_utf8.find(std::string(name));
Spencer Low6815c072015-05-11 01:08:48 -07003821 if (it == g_environ_utf8.end()) {
3822 return nullptr;
3823 }
3824
3825 return it->second;
3826}
3827
3828// Version of getcwd() that returns the current working directory in UTF-8.
3829char* adb_getcwd(char* buf, int size) {
3830 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3831 if (wbuf == nullptr) {
3832 return nullptr;
3833 }
3834
3835 const std::string buf_utf8(narrow(wbuf));
3836 free(wbuf);
3837 wbuf = nullptr;
3838
3839 // If size was specified, make sure all the chars will fit.
3840 if (size != 0) {
3841 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3842 errno = ERANGE;
3843 return nullptr;
3844 }
3845 }
3846
3847 // If buf was not specified, allocate storage.
3848 if (buf == nullptr) {
3849 if (size == 0) {
3850 size = buf_utf8.length() + 1;
3851 }
3852 buf = reinterpret_cast<char*>(malloc(size));
3853 if (buf == nullptr) {
3854 return nullptr;
3855 }
3856 }
3857
3858 // Destination buffer was allocated with enough space, or we've already
3859 // checked an existing buffer size for enough space.
3860 strcpy(buf, buf_utf8.c_str());
3861
3862 return buf;
3863}