blob: c3889b6868c0992adc272bc4d496de1bed35a49d [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
2591 if ((input_record->EventType == KEY_EVENT) &&
2592 (input_record->Event.KeyEvent.bKeyDown)) {
2593 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2594 fatal("ReadConsoleInputA returned a key event with zero repeat"
2595 " count");
2596 }
2597
2598 // Got an interesting INPUT_RECORD, so return
2599 return true;
2600 }
2601 }
2602}
2603
Spencer Low50184062015-03-01 15:06:21 -08002604static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2605 return (control_key_state & SHIFT_PRESSED) != 0;
2606}
2607
2608static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2609 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2610}
2611
2612static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2613 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2614}
2615
2616static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2617 return (control_key_state & NUMLOCK_ON) != 0;
2618}
2619
2620static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2621 return (control_key_state & CAPSLOCK_ON) != 0;
2622}
2623
2624static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2625 return (control_key_state & ENHANCED_KEY) != 0;
2626}
2627
2628// Constants from MSDN for ToAscii().
2629static const BYTE TOASCII_KEY_OFF = 0x00;
2630static const BYTE TOASCII_KEY_DOWN = 0x80;
2631static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2632
2633// Given a key event, ignore a modifier key and return the character that was
2634// entered without the modifier. Writes to *ch and returns the number of bytes
2635// written.
2636static size_t _get_char_ignoring_modifier(char* const ch,
2637 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2638 const WORD modifier) {
2639 // If there is no character from Windows, try ignoring the specified
2640 // modifier and look for a character. Note that if AltGr is being used,
2641 // there will be a character from Windows.
2642 if (key_event->uChar.AsciiChar == '\0') {
2643 // Note that we read the control key state from the passed in argument
2644 // instead of from key_event since the argument has been normalized.
2645 if (((modifier == VK_SHIFT) &&
2646 _is_shift_pressed(control_key_state)) ||
2647 ((modifier == VK_CONTROL) &&
2648 _is_ctrl_pressed(control_key_state)) ||
2649 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2650
2651 BYTE key_state[256] = {0};
2652 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2653 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2654 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2655 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2656 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2657 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2658 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2659 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2660
2661 // cause this modifier to be ignored
2662 key_state[modifier] = TOASCII_KEY_OFF;
2663
2664 WORD translated = 0;
2665 if (ToAscii(key_event->wVirtualKeyCode,
2666 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2667 // Ignoring the modifier, we found a character.
2668 *ch = (CHAR)translated;
2669 return 1;
2670 }
2671 }
2672 }
2673
2674 // Just use whatever Windows told us originally.
2675 *ch = key_event->uChar.AsciiChar;
2676
2677 // If the character from Windows is NULL, return a size of zero.
2678 return (*ch == '\0') ? 0 : 1;
2679}
2680
2681// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2682// but taking into account the shift key. This is because for a sequence like
2683// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2684// we want to find the character ')'.
2685//
2686// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2687// because it is the default key-sequence to switch the input language.
2688// This is configurable in the Region and Language control panel.
2689static __inline__ size_t _get_non_control_char(char* const ch,
2690 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2691 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2692 VK_CONTROL);
2693}
2694
2695// Get without Alt.
2696static __inline__ size_t _get_non_alt_char(char* const ch,
2697 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2698 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2699 VK_MENU);
2700}
2701
2702// Ignore the control key, find the character from Windows, and apply any
2703// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2704// *pch and returns number of bytes written.
2705static size_t _get_control_character(char* const pch,
2706 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2707 const size_t len = _get_non_control_char(pch, key_event,
2708 control_key_state);
2709
2710 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2711 char ch = *pch;
2712 switch (ch) {
2713 case '2':
2714 case '@':
2715 case '`':
2716 ch = '\0';
2717 break;
2718 case '3':
2719 case '[':
2720 case '{':
2721 ch = '\x1b';
2722 break;
2723 case '4':
2724 case '\\':
2725 case '|':
2726 ch = '\x1c';
2727 break;
2728 case '5':
2729 case ']':
2730 case '}':
2731 ch = '\x1d';
2732 break;
2733 case '6':
2734 case '^':
2735 case '~':
2736 ch = '\x1e';
2737 break;
2738 case '7':
2739 case '-':
2740 case '_':
2741 ch = '\x1f';
2742 break;
2743 case '8':
2744 ch = '\x7f';
2745 break;
2746 case '/':
2747 if (!_is_alt_pressed(control_key_state)) {
2748 ch = '\x1f';
2749 }
2750 break;
2751 case '?':
2752 if (!_is_alt_pressed(control_key_state)) {
2753 ch = '\x7f';
2754 }
2755 break;
2756 }
2757 *pch = ch;
2758 }
2759
2760 return len;
2761}
2762
2763static DWORD _normalize_altgr_control_key_state(
2764 const KEY_EVENT_RECORD* const key_event) {
2765 DWORD control_key_state = key_event->dwControlKeyState;
2766
2767 // If we're in an AltGr situation where the AltGr key is down (depending on
2768 // the keyboard layout, that might be the physical right alt key which
2769 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2770 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2771 // a character (which indicates that there was an AltGr mapping), then act
2772 // as if alt and control are not really down for the purposes of modifiers.
2773 // This makes it so that if the user with, say, a German keyboard layout
2774 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2775 // output the key and we don't see the Alt and Ctrl keys.
2776 if (_is_ctrl_pressed(control_key_state) &&
2777 _is_alt_pressed(control_key_state)
2778 && (key_event->uChar.AsciiChar != '\0')) {
2779 // Try to remove as few bits as possible to improve our chances of
2780 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2781 // Left-Alt + Right-Ctrl + AltGr.
2782 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2783 // Remove Right-Alt.
2784 control_key_state &= ~RIGHT_ALT_PRESSED;
2785 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2786 // pressed, Left-Ctrl is almost always set, except if the user
2787 // presses Right-Ctrl, then AltGr (in that specific order) for
2788 // whatever reason. At any rate, make sure the bit is not set.
2789 control_key_state &= ~LEFT_CTRL_PRESSED;
2790 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2791 // Remove Left-Alt.
2792 control_key_state &= ~LEFT_ALT_PRESSED;
2793 // Whichever Ctrl key is down, remove it from the state. We only
2794 // remove one key, to improve our chances of detecting the
2795 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2796 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2797 // Remove Left-Ctrl.
2798 control_key_state &= ~LEFT_CTRL_PRESSED;
2799 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2800 // Remove Right-Ctrl.
2801 control_key_state &= ~RIGHT_CTRL_PRESSED;
2802 }
2803 }
2804
2805 // Note that this logic isn't 100% perfect because Windows doesn't
2806 // allow us to detect all combinations because a physical AltGr key
2807 // press shows up as two bits, plus some combinations are ambiguous
2808 // about what is actually physically pressed.
2809 }
2810
2811 return control_key_state;
2812}
2813
2814// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2815// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2816// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2817// appropriately.
2818static DWORD _normalize_keypad_control_key_state(const WORD vk,
2819 const DWORD control_key_state) {
2820 if (!_is_numlock_on(control_key_state)) {
2821 return control_key_state;
2822 }
2823 if (!_is_enhanced_key(control_key_state)) {
2824 switch (vk) {
2825 case VK_INSERT: // 0
2826 case VK_DELETE: // .
2827 case VK_END: // 1
2828 case VK_DOWN: // 2
2829 case VK_NEXT: // 3
2830 case VK_LEFT: // 4
2831 case VK_CLEAR: // 5
2832 case VK_RIGHT: // 6
2833 case VK_HOME: // 7
2834 case VK_UP: // 8
2835 case VK_PRIOR: // 9
2836 return control_key_state | SHIFT_PRESSED;
2837 }
2838 }
2839
2840 return control_key_state;
2841}
2842
2843static const char* _get_keypad_sequence(const DWORD control_key_state,
2844 const char* const normal, const char* const shifted) {
2845 if (_is_shift_pressed(control_key_state)) {
2846 // Shift is pressed and NumLock is off
2847 return shifted;
2848 } else {
2849 // Shift is not pressed and NumLock is off, or,
2850 // Shift is pressed and NumLock is on, in which case we want the
2851 // NumLock and Shift to neutralize each other, thus, we want the normal
2852 // sequence.
2853 return normal;
2854 }
2855 // If Shift is not pressed and NumLock is on, a different virtual key code
2856 // is returned by Windows, which can be taken care of by a different case
2857 // statement in _console_read().
2858}
2859
2860// Write sequence to buf and return the number of bytes written.
2861static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2862 DWORD control_key_state, const char* const normal) {
2863 // Copy the base sequence into buf.
2864 const size_t len = strlen(normal);
2865 memcpy(buf, normal, len);
2866
2867 int code = 0;
2868
2869 control_key_state = _normalize_keypad_control_key_state(vk,
2870 control_key_state);
2871
2872 if (_is_shift_pressed(control_key_state)) {
2873 code |= 0x1;
2874 }
2875 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2876 code |= 0x2;
2877 }
2878 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2879 code |= 0x4;
2880 }
2881 // If some modifier was held down, then we need to insert the modifier code
2882 if (code != 0) {
2883 if (len == 0) {
2884 // Should be impossible because caller should pass a string of
2885 // non-zero length.
2886 return 0;
2887 }
2888 size_t index = len - 1;
2889 const char lastChar = buf[index];
2890 if (lastChar != '~') {
2891 buf[index++] = '1';
2892 }
2893 buf[index++] = ';'; // modifier separator
2894 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2895 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2896 buf[index++] = '1' + code;
2897 buf[index++] = lastChar; // move ~ (or other last char) to the end
2898 return index;
2899 }
2900 return len;
2901}
2902
2903// Write sequence to buf and return the number of bytes written.
2904static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2905 const DWORD control_key_state, const char* const normal,
2906 const char shifted) {
2907 if (_is_shift_pressed(control_key_state)) {
2908 // Shift is pressed and NumLock is off
2909 if (shifted != '\0') {
2910 buf[0] = shifted;
2911 return sizeof(buf[0]);
2912 } else {
2913 return 0;
2914 }
2915 } else {
2916 // Shift is not pressed and NumLock is off, or,
2917 // Shift is pressed and NumLock is on, in which case we want the
2918 // NumLock and Shift to neutralize each other, thus, we want the normal
2919 // sequence.
2920 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2921 }
2922 // If Shift is not pressed and NumLock is on, a different virtual key code
2923 // is returned by Windows, which can be taken care of by a different case
2924 // statement in _console_read().
2925}
2926
2927// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2928// Standard German. Figure this out at runtime so we know what to output for
2929// Shift-VK_DELETE.
2930static char _get_decimal_char() {
2931 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2932}
2933
2934// Prefix the len bytes in buf with the escape character, and then return the
2935// new buffer length.
2936size_t _escape_prefix(char* const buf, const size_t len) {
2937 // If nothing to prefix, don't do anything. We might be called with
2938 // len == 0, if alt was held down with a dead key which produced nothing.
2939 if (len == 0) {
2940 return 0;
2941 }
2942
2943 memmove(&buf[1], buf, len);
2944 buf[0] = '\x1b';
2945 return len + 1;
2946}
2947
Spencer Low32762f42015-11-10 19:17:16 -08002948// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002949static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08002950
2951// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
2952// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08002953static int _console_read(const HANDLE console, void* buf, size_t len) {
2954 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08002955 // Read of zero bytes should not block waiting for something from the console.
2956 if (len == 0) {
2957 return 0;
2958 }
2959
2960 // Flush as much as possible from input buffer.
2961 if (!g_console_input_buffer.empty()) {
2962 const int bytes_read = std::min(len, g_console_input_buffer.size());
2963 memcpy(buf, g_console_input_buffer.data(), bytes_read);
2964 const auto begin = g_console_input_buffer.begin();
2965 g_console_input_buffer.erase(begin, begin + bytes_read);
2966 return bytes_read;
2967 }
2968
2969 // Read from the actual console. This may block until input.
2970 INPUT_RECORD input_record;
2971 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08002972 return -1;
2973 }
2974
Spencer Low32762f42015-11-10 19:17:16 -08002975 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08002976 const WORD vk = key_event->wVirtualKeyCode;
2977 const CHAR ch = key_event->uChar.AsciiChar;
2978 const DWORD control_key_state = _normalize_altgr_control_key_state(
2979 key_event);
2980
2981 // The following emulation code should write the output sequence to
2982 // either seqstr or to seqbuf and seqbuflen.
2983 const char* seqstr = NULL; // NULL terminated C-string
2984 // Enough space for max sequence string below, plus modifiers and/or
2985 // escape prefix.
2986 char seqbuf[16];
2987 size_t seqbuflen = 0; // Space used in seqbuf.
2988
2989#define MATCH(vk, normal) \
2990 case (vk): \
2991 { \
2992 seqstr = (normal); \
2993 } \
2994 break;
2995
2996 // Modifier keys should affect the output sequence.
2997#define MATCH_MODIFIER(vk, normal) \
2998 case (vk): \
2999 { \
3000 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
3001 control_key_state, (normal)); \
3002 } \
3003 break;
3004
3005 // The shift key should affect the output sequence.
3006#define MATCH_KEYPAD(vk, normal, shifted) \
3007 case (vk): \
3008 { \
3009 seqstr = _get_keypad_sequence(control_key_state, (normal), \
3010 (shifted)); \
3011 } \
3012 break;
3013
3014 // The shift key and other modifier keys should affect the output
3015 // sequence.
3016#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
3017 case (vk): \
3018 { \
3019 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
3020 control_key_state, (normal), (shifted)); \
3021 } \
3022 break;
3023
3024#define ESC "\x1b"
3025#define CSI ESC "["
3026#define SS3 ESC "O"
3027
3028 // Only support normal mode, not application mode.
3029
3030 // Enhanced keys:
3031 // * 6-pack: insert, delete, home, end, page up, page down
3032 // * cursor keys: up, down, right, left
3033 // * keypad: divide, enter
3034 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
3035 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
3036 if (_is_enhanced_key(control_key_state)) {
3037 switch (vk) {
3038 case VK_RETURN: // Enter key on keypad
3039 if (_is_ctrl_pressed(control_key_state)) {
3040 seqstr = "\n";
3041 } else {
3042 seqstr = "\r";
3043 }
3044 break;
3045
3046 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
3047 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
3048
3049 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
3050 // will be fixed soon to match xterm which sends CSI "F" and
3051 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
3052 MATCH(VK_END, CSI "F");
3053 MATCH(VK_HOME, CSI "H");
3054
3055 MATCH_MODIFIER(VK_LEFT, CSI "D");
3056 MATCH_MODIFIER(VK_UP, CSI "A");
3057 MATCH_MODIFIER(VK_RIGHT, CSI "C");
3058 MATCH_MODIFIER(VK_DOWN, CSI "B");
3059
3060 MATCH_MODIFIER(VK_INSERT, CSI "2~");
3061 MATCH_MODIFIER(VK_DELETE, CSI "3~");
3062
3063 MATCH(VK_DIVIDE, "/");
3064 }
3065 } else { // Non-enhanced keys:
3066 switch (vk) {
3067 case VK_BACK: // backspace
3068 if (_is_alt_pressed(control_key_state)) {
3069 seqstr = ESC "\x7f";
3070 } else {
3071 seqstr = "\x7f";
3072 }
3073 break;
3074
3075 case VK_TAB:
3076 if (_is_shift_pressed(control_key_state)) {
3077 seqstr = CSI "Z";
3078 } else {
3079 seqstr = "\t";
3080 }
3081 break;
3082
3083 // Number 5 key in keypad when NumLock is off, or if NumLock is
3084 // on and Shift is down.
3085 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
3086
3087 case VK_RETURN: // Enter key on main keyboard
3088 if (_is_alt_pressed(control_key_state)) {
3089 seqstr = ESC "\n";
3090 } else if (_is_ctrl_pressed(control_key_state)) {
3091 seqstr = "\n";
3092 } else {
3093 seqstr = "\r";
3094 }
3095 break;
3096
3097 // VK_ESCAPE: Don't do any special handling. The OS uses many
3098 // of the sequences with Escape and many of the remaining
3099 // sequences don't produce bKeyDown messages, only !bKeyDown
3100 // for whatever reason.
3101
3102 case VK_SPACE:
3103 if (_is_alt_pressed(control_key_state)) {
3104 seqstr = ESC " ";
3105 } else if (_is_ctrl_pressed(control_key_state)) {
3106 seqbuf[0] = '\0'; // NULL char
3107 seqbuflen = 1;
3108 } else {
3109 seqstr = " ";
3110 }
3111 break;
3112
3113 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
3114 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
3115
3116 MATCH_KEYPAD(VK_END, CSI "4~", "1");
3117 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
3118
3119 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
3120 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
3121 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
3122 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
3123
3124 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
3125 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
3126 _get_decimal_char());
3127
3128 case 0x30: // 0
3129 case 0x31: // 1
3130 case 0x39: // 9
3131 case VK_OEM_1: // ;:
3132 case VK_OEM_PLUS: // =+
3133 case VK_OEM_COMMA: // ,<
3134 case VK_OEM_PERIOD: // .>
3135 case VK_OEM_7: // '"
3136 case VK_OEM_102: // depends on keyboard, could be <> or \|
3137 case VK_OEM_2: // /?
3138 case VK_OEM_3: // `~
3139 case VK_OEM_4: // [{
3140 case VK_OEM_5: // \|
3141 case VK_OEM_6: // ]}
3142 {
3143 seqbuflen = _get_control_character(seqbuf, key_event,
3144 control_key_state);
3145
3146 if (_is_alt_pressed(control_key_state)) {
3147 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3148 }
3149 }
3150 break;
3151
3152 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08003153 case 0x33: // 3
3154 case 0x34: // 4
3155 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08003156 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08003157 case 0x37: // 7
3158 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08003159 case VK_OEM_MINUS: // -_
3160 {
3161 seqbuflen = _get_control_character(seqbuf, key_event,
3162 control_key_state);
3163
3164 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3165 // prefix with escape.
3166 if (_is_alt_pressed(control_key_state) &&
3167 !(_is_ctrl_pressed(control_key_state) &&
3168 !_is_shift_pressed(control_key_state))) {
3169 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3170 }
3171 }
3172 break;
3173
Spencer Low50184062015-03-01 15:06:21 -08003174 case 0x41: // a
3175 case 0x42: // b
3176 case 0x43: // c
3177 case 0x44: // d
3178 case 0x45: // e
3179 case 0x46: // f
3180 case 0x47: // g
3181 case 0x48: // h
3182 case 0x49: // i
3183 case 0x4a: // j
3184 case 0x4b: // k
3185 case 0x4c: // l
3186 case 0x4d: // m
3187 case 0x4e: // n
3188 case 0x4f: // o
3189 case 0x50: // p
3190 case 0x51: // q
3191 case 0x52: // r
3192 case 0x53: // s
3193 case 0x54: // t
3194 case 0x55: // u
3195 case 0x56: // v
3196 case 0x57: // w
3197 case 0x58: // x
3198 case 0x59: // y
3199 case 0x5a: // z
3200 {
3201 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3202 control_key_state);
3203
3204 // If Alt is pressed, then prefix with escape.
3205 if (_is_alt_pressed(control_key_state)) {
3206 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3207 }
3208 }
3209 break;
3210
3211 // These virtual key codes are generated by the keys on the
3212 // keypad *when NumLock is on* and *Shift is up*.
3213 MATCH(VK_NUMPAD0, "0");
3214 MATCH(VK_NUMPAD1, "1");
3215 MATCH(VK_NUMPAD2, "2");
3216 MATCH(VK_NUMPAD3, "3");
3217 MATCH(VK_NUMPAD4, "4");
3218 MATCH(VK_NUMPAD5, "5");
3219 MATCH(VK_NUMPAD6, "6");
3220 MATCH(VK_NUMPAD7, "7");
3221 MATCH(VK_NUMPAD8, "8");
3222 MATCH(VK_NUMPAD9, "9");
3223
3224 MATCH(VK_MULTIPLY, "*");
3225 MATCH(VK_ADD, "+");
3226 MATCH(VK_SUBTRACT, "-");
3227 // VK_DECIMAL is generated by the . key on the keypad *when
3228 // NumLock is on* and *Shift is up* and the sequence is not
3229 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3230 // Windows Security screen to come up).
3231 case VK_DECIMAL:
3232 // U.S. English uses '.', Germany German uses ','.
3233 seqbuflen = _get_non_control_char(seqbuf, key_event,
3234 control_key_state);
3235 break;
3236
3237 MATCH_MODIFIER(VK_F1, SS3 "P");
3238 MATCH_MODIFIER(VK_F2, SS3 "Q");
3239 MATCH_MODIFIER(VK_F3, SS3 "R");
3240 MATCH_MODIFIER(VK_F4, SS3 "S");
3241 MATCH_MODIFIER(VK_F5, CSI "15~");
3242 MATCH_MODIFIER(VK_F6, CSI "17~");
3243 MATCH_MODIFIER(VK_F7, CSI "18~");
3244 MATCH_MODIFIER(VK_F8, CSI "19~");
3245 MATCH_MODIFIER(VK_F9, CSI "20~");
3246 MATCH_MODIFIER(VK_F10, CSI "21~");
3247 MATCH_MODIFIER(VK_F11, CSI "23~");
3248 MATCH_MODIFIER(VK_F12, CSI "24~");
3249
3250 MATCH_MODIFIER(VK_F13, CSI "25~");
3251 MATCH_MODIFIER(VK_F14, CSI "26~");
3252 MATCH_MODIFIER(VK_F15, CSI "28~");
3253 MATCH_MODIFIER(VK_F16, CSI "29~");
3254 MATCH_MODIFIER(VK_F17, CSI "31~");
3255 MATCH_MODIFIER(VK_F18, CSI "32~");
3256 MATCH_MODIFIER(VK_F19, CSI "33~");
3257 MATCH_MODIFIER(VK_F20, CSI "34~");
3258
3259 // MATCH_MODIFIER(VK_F21, ???);
3260 // MATCH_MODIFIER(VK_F22, ???);
3261 // MATCH_MODIFIER(VK_F23, ???);
3262 // MATCH_MODIFIER(VK_F24, ???);
3263 }
3264 }
3265
3266#undef MATCH
3267#undef MATCH_MODIFIER
3268#undef MATCH_KEYPAD
3269#undef MATCH_MODIFIER_KEYPAD
3270#undef ESC
3271#undef CSI
3272#undef SS3
3273
3274 const char* out;
3275 size_t outlen;
3276
3277 // Check for output in any of:
3278 // * seqstr is set (and strlen can be used to determine the length).
3279 // * seqbuf and seqbuflen are set
3280 // Fallback to ch from Windows.
3281 if (seqstr != NULL) {
3282 out = seqstr;
3283 outlen = strlen(seqstr);
3284 } else if (seqbuflen > 0) {
3285 out = seqbuf;
3286 outlen = seqbuflen;
3287 } else if (ch != '\0') {
3288 // Use whatever Windows told us it is.
3289 seqbuf[0] = ch;
3290 seqbuflen = 1;
3291 out = seqbuf;
3292 outlen = seqbuflen;
3293 } else {
3294 // No special handling for the virtual key code and Windows isn't
3295 // telling us a character code, then we don't know how to translate
3296 // the key press.
3297 //
3298 // Consume the input and 'continue' to cause us to get a new key
3299 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07003300 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08003301 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08003302 continue;
3303 }
3304
Spencer Low32762f42015-11-10 19:17:16 -08003305 // put output wRepeatCount times into g_console_input_buffer
3306 while (key_event->wRepeatCount-- > 0) {
3307 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08003308 }
3309
Spencer Low32762f42015-11-10 19:17:16 -08003310 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08003311 }
3312}
3313
3314static DWORD _old_console_mode; // previous GetConsoleMode() result
3315static HANDLE _console_handle; // when set, console mode should be restored
3316
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003317void stdin_raw_init() {
3318 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Low50184062015-03-01 15:06:21 -08003319
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003320 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3321 // calling the process Ctrl-C routine (configured by
3322 // SetConsoleCtrlHandler()).
3323 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3324 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3325 // flag also seems necessary to have proper line-ending processing.
3326 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3327 ENABLE_LINE_INPUT |
3328 ENABLE_ECHO_INPUT))) {
3329 // This really should not fail.
3330 D("stdin_raw_init: SetConsoleMode() failed: %s",
3331 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08003332 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003333
3334 // Once this is set, it means that stdin has been configured for
3335 // reading from and that the old console mode should be restored later.
3336 _console_handle = in;
3337
3338 // Note that we don't need to configure C Runtime line-ending
3339 // translation because _console_read() does not call the C Runtime to
3340 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08003341}
3342
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003343void stdin_raw_restore() {
3344 if (_console_handle != NULL) {
3345 const HANDLE in = _console_handle;
3346 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08003347
Elliott Hughesc15b17f2015-11-03 11:18:40 -08003348 if (!SetConsoleMode(in, _old_console_mode)) {
3349 // This really should not fail.
3350 D("stdin_raw_restore: SetConsoleMode() failed: %s",
3351 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08003352 }
3353 }
3354}
3355
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003356// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Low50184062015-03-01 15:06:21 -08003357int unix_read(int fd, void* buf, size_t len) {
3358 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3359 // If it is a request to read from stdin, and stdin_raw_init() has been
3360 // called, and it successfully configured the console, then read from
3361 // the console using Win32 console APIs and partially emulate a unix
3362 // terminal.
3363 return _console_read(_console_handle, buf, len);
3364 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07003365 // On older versions of Windows (definitely 7, definitely not 10),
3366 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07003367 // we need to limit the read size.
3368 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07003369 len = 4096;
3370 }
Spencer Low50184062015-03-01 15:06:21 -08003371 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003372 // can do LF/CR translation (which is overridable with _setmode()).
3373 // Undefine the macro that is set in sysdeps.h which bans calls to
3374 // plain read() in favor of unix_read() or adb_read().
3375#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003376#undef read
3377 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003378#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003379 }
3380}
Spencer Lowcf4ff642015-05-11 01:08:48 -07003381
3382/**************************************************************************/
3383/**************************************************************************/
3384/***** *****/
3385/***** Unicode support *****/
3386/***** *****/
3387/**************************************************************************/
3388/**************************************************************************/
3389
3390// This implements support for using files with Unicode filenames and for
3391// outputting Unicode text to a Win32 console window. This is inspired from
3392// http://utf8everywhere.org/.
3393//
3394// Background
3395// ----------
3396//
3397// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3398// filenames to APIs such as open(). This works because filenames are largely
3399// opaque 'cookies' (perhaps excluding path separators).
3400//
3401// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3402// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3403// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3404// CreateFile() API is really just a macro that adds the W/A based on whether
3405// the UNICODE preprocessor symbol is defined).
3406//
3407// Options
3408// -------
3409//
3410// Thus, to write a portable program, there are a few options:
3411//
3412// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3413// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3414// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3415// open() API.
3416//
3417// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3418// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3419// potentially touching a lot of code.
3420//
3421// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3422// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3423// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3424// or C Runtime API.
3425//
3426// The Choice
3427// ----------
3428//
Spencer Lowd21dc822015-11-12 15:20:15 -08003429// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
3430// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07003431// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08003432// args that are passed to main() at the beginning of program startup. We also use
3433// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07003434// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3435//
3436// Unicode console output
3437// ----------------------
3438//
3439// The way to output Unicode to a Win32 console window is to call
3440// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07003441// such as Lucida Console or Consolas, and in the case of East Asian languages
3442// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3443// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3444// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07003445//
3446// The problem is getting the C Runtime to make fprintf and related APIs call
3447// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3448// promising, but the various modes have issues:
3449//
3450// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3451// UTF-16 do not display properly.
3452// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3453// totally wrong.
3454// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3455// handler to be called (upon a later I/O call), aborting the process.
3456// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3457// to output nothing.
3458//
3459// So the only solution is to write our own adb_fprintf() that converts UTF-8
3460// to UTF-16 and then calls WriteConsoleW().
3461
3462
Spencer Lowcf4ff642015-05-11 01:08:48 -07003463// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3464// be passed to main().
3465NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3466 narrow_args = new char*[argc + 1];
3467
3468 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003469 std::string arg_narrow;
3470 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
3471 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
3472 }
3473 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003474 }
3475 narrow_args[argc] = nullptr; // terminate
3476}
3477
3478NarrowArgs::~NarrowArgs() {
3479 if (narrow_args != nullptr) {
3480 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3481 free(*argp);
3482 }
3483 delete[] narrow_args;
3484 narrow_args = nullptr;
3485 }
3486}
3487
3488int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003489 std::wstring path_wide;
3490 if (!android::base::UTF8ToWide(path, &path_wide)) {
3491 return -1;
3492 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003493 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003494 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003495 } else {
3496 int mode;
3497 va_list args;
3498 va_start(args, options);
3499 mode = va_arg(args, int);
3500 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08003501 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003502 }
3503}
3504
3505// Version of stat() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08003506int adb_stat(const char* path, struct adb_stat* s) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07003507#pragma push_macro("wstat")
3508// This definition of wstat seems to be missing from <sys/stat.h>.
3509#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3510#ifdef _USE_32BIT_TIME_T
3511#define wstat _wstat32i64
3512#else
3513#define wstat _wstat64
3514#endif
3515#else
3516// <sys/stat.h> has a function prototype for wstat() that should be available.
3517#endif
3518
Spencer Lowd21dc822015-11-12 15:20:15 -08003519 std::wstring path_wide;
3520 if (!android::base::UTF8ToWide(path, &path_wide)) {
3521 return -1;
3522 }
3523
3524 return wstat(path_wide.c_str(), s);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003525
3526#pragma pop_macro("wstat")
3527}
3528
3529// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08003530DIR* adb_opendir(const char* path) {
3531 std::wstring path_wide;
3532 if (!android::base::UTF8ToWide(path, &path_wide)) {
3533 return nullptr;
3534 }
3535
Spencer Lowcf4ff642015-05-11 01:08:48 -07003536 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3537 // the fields, but right now all the callers treat the structure as
3538 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08003539 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003540}
3541
3542// Version of readdir() that returns UTF-8 paths.
3543struct dirent* adb_readdir(DIR* dir) {
3544 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3545 struct _wdirent* const went = _wreaddir(wdir);
3546 if (went == nullptr) {
3547 return nullptr;
3548 }
Spencer Lowd21dc822015-11-12 15:20:15 -08003549
Spencer Lowcf4ff642015-05-11 01:08:48 -07003550 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08003551 std::string name_utf8;
3552 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
3553 return nullptr;
3554 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003555
3556 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3557 // space for UTF-16 wchar_t's) with UTF-8 char's.
3558 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3559
3560 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3561 // Name too big to fit in existing buffer.
3562 errno = ENOMEM;
3563 return nullptr;
3564 }
3565
3566 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3567 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3568 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3569 // bigger than the caller expects because they expect a dirent structure
3570 // which has a smaller d_name field. Ignore this since the caller should be
3571 // resilient.
3572
3573 // Rewrite the UTF-16 d_name field to UTF-8.
3574 strcpy(ent->d_name, name_utf8.c_str());
3575
3576 return ent;
3577}
3578
3579// Version of closedir() to go with our version of adb_opendir().
3580int adb_closedir(DIR* dir) {
3581 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3582}
3583
3584// Version of unlink() that takes a UTF-8 path.
3585int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003586 std::wstring wpath;
3587 if (!android::base::UTF8ToWide(path, &wpath)) {
3588 return -1;
3589 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07003590
3591 int rc = _wunlink(wpath.c_str());
3592
3593 if (rc == -1 && errno == EACCES) {
3594 /* unlink returns EACCES when the file is read-only, so we first */
3595 /* try to make it writable, then unlink again... */
3596 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3597 if (rc == 0)
3598 rc = _wunlink(wpath.c_str());
3599 }
3600 return rc;
3601}
3602
3603// Version of mkdir() that takes a UTF-8 path.
3604int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003605 std::wstring path_wide;
3606 if (!android::base::UTF8ToWide(path, &path_wide)) {
3607 return -1;
3608 }
3609
3610 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003611}
3612
3613// Version of utime() that takes a UTF-8 path.
3614int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003615 std::wstring path_wide;
3616 if (!android::base::UTF8ToWide(path, &path_wide)) {
3617 return -1;
3618 }
3619
Spencer Lowcf4ff642015-05-11 01:08:48 -07003620 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3621 "utimbuf and _utimbuf should be the same size because they both "
3622 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08003623 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003624}
3625
3626// Version of chmod() that takes a UTF-8 path.
3627int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08003628 std::wstring path_wide;
3629 if (!android::base::UTF8ToWide(path, &path_wide)) {
3630 return -1;
3631 }
3632
3633 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003634}
3635
Spencer Lowcf4ff642015-05-11 01:08:48 -07003636// Internal helper function to write UTF-8 bytes to a console. Returns -1
3637// on error.
3638static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3639 HANDLE console) {
Elliott Hughesc1fd4922015-11-11 18:02:29 +00003640 std::wstring output;
3641
3642 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors.
3643 // Data might not be UTF-8 if the user cat's random data, runs dmesg, etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07003644 // This could throw std::bad_alloc.
Elliott Hughesc1fd4922015-11-11 18:02:29 +00003645 (void)android::base::UTF8ToWide(buf, size, &output);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003646
3647 // Note that this does not do \n => \r\n translation because that
3648 // doesn't seem necessary for the Windows console. For the Windows
3649 // console \r moves to the beginning of the line and \n moves to a new
3650 // line.
3651
3652 // Flush any stream buffering so that our output is afterwards which
3653 // makes sense because our call is afterwards.
3654 (void)fflush(stream);
3655
3656 // Write UTF-16 to the console.
3657 DWORD written = 0;
3658 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3659 NULL)) {
3660 errno = EIO;
3661 return -1;
3662 }
3663
3664 // This is the number of UTF-16 chars written, which might be different
3665 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3666 // get this count correct.
3667 return written;
3668}
3669
3670// Function prototype because attributes cannot be placed on func definitions.
3671static int _console_vfprintf(const HANDLE console, FILE* stream,
3672 const char *format, va_list ap)
3673 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3674
3675// Internal function to format a UTF-8 string and write it to a Win32 console.
3676// Returns -1 on error.
3677static int _console_vfprintf(const HANDLE console, FILE* stream,
3678 const char *format, va_list ap) {
3679 std::string output_utf8;
3680
3681 // Format the string.
3682 // This could throw std::bad_alloc.
3683 android::base::StringAppendV(&output_utf8, format, ap);
3684
3685 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3686 stream, console);
3687}
3688
3689// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3690// Windows console.
3691int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3692 const HANDLE console = _get_console_handle(stream);
3693
3694 // If there is an associated Win32 console, write to it specially,
3695 // otherwise defer to the regular C Runtime, passing it UTF-8.
3696 if (console != NULL) {
3697 return _console_vfprintf(console, stream, format, ap);
3698 } else {
3699 // If vfprintf is a macro, undefine it, so we can call the real
3700 // C Runtime API.
3701#pragma push_macro("vfprintf")
3702#undef vfprintf
3703 return vfprintf(stream, format, ap);
3704#pragma pop_macro("vfprintf")
3705 }
3706}
3707
3708// Version of fprintf() that takes UTF-8 and can write Unicode to a
3709// Windows console.
3710int adb_fprintf(FILE *stream, const char *format, ...) {
3711 va_list ap;
3712 va_start(ap, format);
3713 const int result = adb_vfprintf(stream, format, ap);
3714 va_end(ap);
3715
3716 return result;
3717}
3718
3719// Version of printf() that takes UTF-8 and can write Unicode to a
3720// Windows console.
3721int adb_printf(const char *format, ...) {
3722 va_list ap;
3723 va_start(ap, format);
3724 const int result = adb_vfprintf(stdout, format, ap);
3725 va_end(ap);
3726
3727 return result;
3728}
3729
3730// Version of fputs() that takes UTF-8 and can write Unicode to a
3731// Windows console.
3732int adb_fputs(const char* buf, FILE* stream) {
3733 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3734 // which fputs (and hence adb_fputs) should return on error.
3735 return adb_fprintf(stream, "%s", buf);
3736}
3737
3738// Version of fputc() that takes UTF-8 and can write Unicode to a
3739// Windows console.
3740int adb_fputc(int ch, FILE* stream) {
3741 const int result = adb_fprintf(stream, "%c", ch);
3742 if (result <= 0) {
3743 // If there was an error, or if nothing was printed (which should be an
3744 // error), return an error, which fprintf signifies with EOF.
3745 return EOF;
3746 }
3747 // For success, fputc returns the char, cast to unsigned char, then to int.
3748 return static_cast<unsigned char>(ch);
3749}
3750
3751// Internal function to write UTF-8 to a Win32 console. Returns the number of
3752// items (of length size) written. On error, returns a short item count or 0.
3753static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3754 FILE* stream, HANDLE console) {
3755 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3756 // if we're passed only some of the bytes of a character (for example, from
3757 // the network socket for adb shell), we won't be able to convert the char
3758 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3759 // right.
3760 //
3761 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3762 //
3763 // For now we ignore this problem because the alternative is that we'd have
3764 // to parse UTF-8 and buffer things up (doable). At least this is better
3765 // than what we had before -- always incorrect multi-byte UTF-8 output.
3766 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3767 size * nmemb, stream, console);
3768 if (result == -1) {
3769 return 0;
3770 }
3771 return result / size;
3772}
3773
3774// Version of fwrite() that takes UTF-8 and can write Unicode to a
3775// Windows console.
3776size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3777 const HANDLE console = _get_console_handle(stream);
3778
3779 // If there is an associated Win32 console, write to it specially,
3780 // otherwise defer to the regular C Runtime, passing it UTF-8.
3781 if (console != NULL) {
3782 return _console_fwrite(ptr, size, nmemb, stream, console);
3783 } else {
3784 // If fwrite is a macro, undefine it, so we can call the real
3785 // C Runtime API.
3786#pragma push_macro("fwrite")
3787#undef fwrite
3788 return fwrite(ptr, size, nmemb, stream);
3789#pragma pop_macro("fwrite")
3790 }
3791}
3792
3793// Version of fopen() that takes a UTF-8 filename and can access a file with
3794// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08003795FILE* adb_fopen(const char* path, const char* mode) {
3796 std::wstring path_wide;
3797 if (!android::base::UTF8ToWide(path, &path_wide)) {
3798 return nullptr;
3799 }
3800
3801 std::wstring mode_wide;
3802 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
3803 return nullptr;
3804 }
3805
3806 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003807}
3808
Spencer Lowe6ae5732015-09-08 17:13:04 -07003809// Return a lowercase version of the argument. Uses C Runtime tolower() on
3810// each byte which is not UTF-8 aware, and theoretically uses the current C
3811// Runtime locale (which in practice is not changed, so this becomes a ASCII
3812// conversion).
3813static std::string ToLower(const std::string& anycase) {
3814 // copy string
3815 std::string str(anycase);
3816 // transform the copy
3817 std::transform(str.begin(), str.end(), str.begin(), tolower);
3818 return str;
3819}
3820
3821extern "C" int main(int argc, char** argv);
3822
3823// Link with -municode to cause this wmain() to be used as the program
3824// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3825// regular main() with UTF-8 args.
3826extern "C" int wmain(int argc, wchar_t **argv) {
3827 // Convert args from UTF-16 to UTF-8 and pass that to main().
3828 NarrowArgs narrow_args(argc, argv);
3829 return main(argc, narrow_args.data());
3830}
3831
Spencer Lowcf4ff642015-05-11 01:08:48 -07003832// Shadow UTF-8 environment variable name/value pairs that are created from
3833// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07003834// currently updated if putenv, setenv, unsetenv are called. Note that no
3835// thread synchronization is done, but we're called early enough in
3836// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08003837static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07003838
3839// Make sure that shadow UTF-8 environment variables are setup.
3840static void _ensure_env_setup() {
3841 // If some name/value pairs exist, then we've already done the setup below.
3842 if (g_environ_utf8.size() != 0) {
3843 return;
3844 }
3845
Spencer Lowe6ae5732015-09-08 17:13:04 -07003846 if (_wenviron == nullptr) {
3847 // If _wenviron is null, then -municode probably wasn't used. That
3848 // linker flag will cause the entry point to setup _wenviron. It will
3849 // also require an implementation of wmain() (which we provide above).
3850 fatal("_wenviron is not set, did you link with -municode?");
3851 }
3852
Spencer Lowcf4ff642015-05-11 01:08:48 -07003853 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3854 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3855 // to use the D() macro here because that tracing only works if the
3856 // ADB_TRACE environment variable is setup, but that env var can't be read
3857 // until this code completes.
3858 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3859 wchar_t* const equal = wcschr(*env, L'=');
3860 if (equal == nullptr) {
3861 // Malformed environment variable with no equal sign. Shouldn't
3862 // really happen, but we should be resilient to this.
3863 continue;
3864 }
3865
Spencer Lowd21dc822015-11-12 15:20:15 -08003866 // If we encounter an error converting UTF-16, don't error-out on account of a single env
3867 // var because the program might never even read this particular variable.
3868 std::string name_utf8;
3869 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
3870 continue;
3871 }
3872
Spencer Lowe6ae5732015-09-08 17:13:04 -07003873 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08003874 name_utf8 = ToLower(name_utf8);
3875
3876 std::string value_utf8;
3877 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
3878 continue;
3879 }
3880
3881 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07003882
Spencer Lowe6ae5732015-09-08 17:13:04 -07003883 // Don't overwrite a previus env var with the same name. In reality,
3884 // the system probably won't let two env vars with the same name exist
3885 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08003886 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07003887 }
3888}
3889
3890// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07003891// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07003892char* adb_getenv(const char* name) {
3893 _ensure_env_setup();
3894
Spencer Lowe6ae5732015-09-08 17:13:04 -07003895 // Case-insensitive search by searching for lowercase name in a map of
3896 // lowercase names.
3897 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07003898 if (it == g_environ_utf8.end()) {
3899 return nullptr;
3900 }
3901
3902 return it->second;
3903}
3904
3905// Version of getcwd() that returns the current working directory in UTF-8.
3906char* adb_getcwd(char* buf, int size) {
3907 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3908 if (wbuf == nullptr) {
3909 return nullptr;
3910 }
3911
Spencer Lowd21dc822015-11-12 15:20:15 -08003912 std::string buf_utf8;
3913 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07003914 free(wbuf);
3915 wbuf = nullptr;
3916
Spencer Lowd21dc822015-11-12 15:20:15 -08003917 if (!narrow_result) {
3918 return nullptr;
3919 }
3920
Spencer Lowcf4ff642015-05-11 01:08:48 -07003921 // If size was specified, make sure all the chars will fit.
3922 if (size != 0) {
3923 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3924 errno = ERANGE;
3925 return nullptr;
3926 }
3927 }
3928
3929 // If buf was not specified, allocate storage.
3930 if (buf == nullptr) {
3931 if (size == 0) {
3932 size = buf_utf8.length() + 1;
3933 }
3934 buf = reinterpret_cast<char*>(malloc(size));
3935 if (buf == nullptr) {
3936 return nullptr;
3937 }
3938 }
3939
3940 // Destination buffer was allocated with enough space, or we've already
3941 // checked an existing buffer size for enough space.
3942 strcpy(buf, buf_utf8.c_str());
3943
3944 return buf;
3945}