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