blob: db552a2da7078b3a8a7843417ea2ccfc0bd43445 [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define TRACE_TAG TRACE_SYSDEPS
18
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
Spencer Low753d4852015-07-30 23:07:55 -070028#include <memory>
29#include <string>
Spencer Low6815c072015-05-11 01:08:48 -070030#include <unordered_map>
Spencer Low753d4852015-07-30 23:07:55 -070031
Elliott Hughesfe447512015-07-24 11:35:40 -070032#include <cutils/sockets.h>
33
Spencer Low753d4852015-07-30 23:07:55 -070034#include <base/logging.h>
35#include <base/stringprintf.h>
36#include <base/strings.h>
37
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080038#include "adb.h"
39
40extern void fatal(const char *fmt, ...);
41
Elliott Hughes6a096932015-04-16 16:47:02 -070042/* forward declarations */
43
44typedef const struct FHClassRec_* FHClass;
45typedef struct FHRec_* FH;
46typedef struct EventHookRec_* EventHook;
47
48typedef struct FHClassRec_ {
49 void (*_fh_init)(FH);
50 int (*_fh_close)(FH);
51 int (*_fh_lseek)(FH, int, int);
52 int (*_fh_read)(FH, void*, int);
53 int (*_fh_write)(FH, const void*, int);
54 void (*_fh_hook)(FH, int, EventHook);
55} FHClassRec;
56
57static void _fh_file_init(FH);
58static int _fh_file_close(FH);
59static int _fh_file_lseek(FH, int, int);
60static int _fh_file_read(FH, void*, int);
61static int _fh_file_write(FH, const void*, int);
62static void _fh_file_hook(FH, int, EventHook);
63
64static const FHClassRec _fh_file_class = {
65 _fh_file_init,
66 _fh_file_close,
67 _fh_file_lseek,
68 _fh_file_read,
69 _fh_file_write,
70 _fh_file_hook
71};
72
73static void _fh_socket_init(FH);
74static int _fh_socket_close(FH);
75static int _fh_socket_lseek(FH, int, int);
76static int _fh_socket_read(FH, void*, int);
77static int _fh_socket_write(FH, const void*, int);
78static void _fh_socket_hook(FH, int, EventHook);
79
80static const FHClassRec _fh_socket_class = {
81 _fh_socket_init,
82 _fh_socket_close,
83 _fh_socket_lseek,
84 _fh_socket_read,
85 _fh_socket_write,
86 _fh_socket_hook
87};
88
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080089#define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
90
Spencer Low753d4852015-07-30 23:07:55 -070091std::string SystemErrorCodeToString(const DWORD error_code) {
92 const int kErrorMessageBufferSize = 256;
Spencer Lowcc467f12015-08-02 18:13:54 -070093 WCHAR msgbuf[kErrorMessageBufferSize];
Spencer Low753d4852015-07-30 23:07:55 -070094 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
Spencer Lowcc467f12015-08-02 18:13:54 -070095 DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf,
Spencer Low753d4852015-07-30 23:07:55 -070096 arraysize(msgbuf), nullptr);
97 if (len == 0) {
98 return android::base::StringPrintf(
99 "Error (%lu) while retrieving error. (%lu)", GetLastError(),
100 error_code);
101 }
102
Spencer Lowcc467f12015-08-02 18:13:54 -0700103 // Convert UTF-16 to UTF-8.
104 std::string msg(narrow(msgbuf));
Spencer Low753d4852015-07-30 23:07:55 -0700105 // Messages returned by the system end with line breaks.
106 msg = android::base::Trim(msg);
107 // There are many Windows error messages compared to POSIX, so include the
108 // numeric error code for easier, quicker, accurate identification. Use
109 // decimal instead of hex because there are decimal ranges like 10000-11999
110 // for Winsock.
111 android::base::StringAppendF(&msg, " (%lu)", error_code);
112 return msg;
113}
114
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800115/**************************************************************************/
116/**************************************************************************/
117/***** *****/
118/***** replaces libs/cutils/load_file.c *****/
119/***** *****/
120/**************************************************************************/
121/**************************************************************************/
122
123void *load_file(const char *fn, unsigned *_sz)
124{
125 HANDLE file;
126 char *data;
127 DWORD file_size;
128
Spencer Low6815c072015-05-11 01:08:48 -0700129 file = CreateFileW( widen(fn).c_str(),
130 GENERIC_READ,
131 FILE_SHARE_READ,
132 NULL,
133 OPEN_EXISTING,
134 0,
135 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800136
137 if (file == INVALID_HANDLE_VALUE)
138 return NULL;
139
140 file_size = GetFileSize( file, NULL );
141 data = NULL;
142
143 if (file_size > 0) {
144 data = (char*) malloc( file_size + 1 );
145 if (data == NULL) {
146 D("load_file: could not allocate %ld bytes\n", file_size );
147 file_size = 0;
148 } else {
149 DWORD out_bytes;
150
151 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
152 out_bytes != file_size )
153 {
154 D("load_file: could not read %ld bytes from '%s'\n", file_size, fn);
155 free(data);
156 data = NULL;
157 file_size = 0;
158 }
159 }
160 }
161 CloseHandle( file );
162
163 *_sz = (unsigned) file_size;
164 return data;
165}
166
167/**************************************************************************/
168/**************************************************************************/
169/***** *****/
170/***** common file descriptor handling *****/
171/***** *****/
172/**************************************************************************/
173/**************************************************************************/
174
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800175/* used to emulate unix-domain socket pairs */
176typedef struct SocketPairRec_* SocketPair;
177
178typedef struct FHRec_
179{
180 FHClass clazz;
181 int used;
182 int eof;
183 union {
184 HANDLE handle;
185 SOCKET socket;
186 SocketPair pair;
187 } u;
188
189 HANDLE event;
190 int mask;
191
192 char name[32];
193
194} FHRec;
195
196#define fh_handle u.handle
197#define fh_socket u.socket
198#define fh_pair u.pair
199
200#define WIN32_FH_BASE 100
201
202#define WIN32_MAX_FHS 128
203
204static adb_mutex_t _win32_lock;
205static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700206static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800207
208static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700209_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800210{
211 FH f;
212
213 fd -= WIN32_FH_BASE;
214
Spencer Lowb732a372015-07-24 15:38:19 -0700215 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Spencer Low3a2421b2015-05-22 20:09:06 -0700216 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
217 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800218 errno = EBADF;
219 return NULL;
220 }
221
222 f = &_win32_fhs[fd];
223
224 if (f->used == 0) {
Spencer Low3a2421b2015-05-22 20:09:06 -0700225 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
226 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800227 errno = EBADF;
228 return NULL;
229 }
230
231 return f;
232}
233
234
235static int
236_fh_to_int( FH f )
237{
238 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
239 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
240
241 return -1;
242}
243
244static FH
245_fh_alloc( FHClass clazz )
246{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800247 FH f = NULL;
248
249 adb_mutex_lock( &_win32_lock );
250
Spencer Lowb732a372015-07-24 15:38:19 -0700251 // Search entire array, starting from _win32_fh_next.
252 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
253 // Keep incrementing _win32_fh_next to avoid giving out an index that
254 // was recently closed, to try to avoid use-after-free.
255 const int index = _win32_fh_next++;
256 // Handle wrap-around of _win32_fh_next.
257 if (_win32_fh_next == WIN32_MAX_FHS) {
258 _win32_fh_next = 0;
259 }
260 if (_win32_fhs[index].clazz == NULL) {
261 f = &_win32_fhs[index];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800262 goto Exit;
263 }
264 }
265 D( "_fh_alloc: no more free file descriptors\n" );
Spencer Lowb732a372015-07-24 15:38:19 -0700266 errno = EMFILE; // Too many open files
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800267Exit:
268 if (f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700269 f->clazz = clazz;
270 f->used = 1;
271 f->eof = 0;
272 f->name[0] = '\0';
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800273 clazz->_fh_init(f);
274 }
275 adb_mutex_unlock( &_win32_lock );
276 return f;
277}
278
279
280static int
281_fh_close( FH f )
282{
Spencer Lowb732a372015-07-24 15:38:19 -0700283 // Use lock so that closing only happens once and so that _fh_alloc can't
284 // allocate a FH that we're in the middle of closing.
285 adb_mutex_lock(&_win32_lock);
286 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800287 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700288 f->name[0] = '\0';
289 f->eof = 0;
290 f->used = 0;
291 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800292 }
Spencer Lowb732a372015-07-24 15:38:19 -0700293 adb_mutex_unlock(&_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800294 return 0;
295}
296
Spencer Low753d4852015-07-30 23:07:55 -0700297// Deleter for unique_fh.
298class fh_deleter {
299 public:
300 void operator()(struct FHRec_* fh) {
301 // We're called from a destructor and destructors should not overwrite
302 // errno because callers may do:
303 // errno = EBLAH;
304 // return -1; // calls destructor, which should not overwrite errno
305 const int saved_errno = errno;
306 _fh_close(fh);
307 errno = saved_errno;
308 }
309};
310
311// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
312typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
313
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800314/**************************************************************************/
315/**************************************************************************/
316/***** *****/
317/***** file-based descriptor handling *****/
318/***** *****/
319/**************************************************************************/
320/**************************************************************************/
321
Elliott Hughes6a096932015-04-16 16:47:02 -0700322static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800323 f->fh_handle = INVALID_HANDLE_VALUE;
324}
325
Elliott Hughes6a096932015-04-16 16:47:02 -0700326static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800327 CloseHandle( f->fh_handle );
328 f->fh_handle = INVALID_HANDLE_VALUE;
329 return 0;
330}
331
Elliott Hughes6a096932015-04-16 16:47:02 -0700332static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800333 DWORD read_bytes;
334
335 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
336 D( "adb_read: could not read %d bytes from %s\n", len, f->name );
337 errno = EIO;
338 return -1;
339 } else if (read_bytes < (DWORD)len) {
340 f->eof = 1;
341 }
342 return (int)read_bytes;
343}
344
Elliott Hughes6a096932015-04-16 16:47:02 -0700345static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800346 DWORD wrote_bytes;
347
348 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
349 D( "adb_file_write: could not write %d bytes from %s\n", len, f->name );
350 errno = EIO;
351 return -1;
352 } else if (wrote_bytes < (DWORD)len) {
353 f->eof = 1;
354 }
355 return (int)wrote_bytes;
356}
357
Elliott Hughes6a096932015-04-16 16:47:02 -0700358static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800359 DWORD method;
360 DWORD result;
361
362 switch (origin)
363 {
364 case SEEK_SET: method = FILE_BEGIN; break;
365 case SEEK_CUR: method = FILE_CURRENT; break;
366 case SEEK_END: method = FILE_END; break;
367 default:
368 errno = EINVAL;
369 return -1;
370 }
371
372 result = SetFilePointer( f->fh_handle, pos, NULL, method );
373 if (result == INVALID_SET_FILE_POINTER) {
374 errno = EIO;
375 return -1;
376 } else {
377 f->eof = 0;
378 }
379 return (int)result;
380}
381
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800382
383/**************************************************************************/
384/**************************************************************************/
385/***** *****/
386/***** file-based descriptor handling *****/
387/***** *****/
388/**************************************************************************/
389/**************************************************************************/
390
391int adb_open(const char* path, int options)
392{
393 FH f;
394
395 DWORD desiredAccess = 0;
396 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
397
398 switch (options) {
399 case O_RDONLY:
400 desiredAccess = GENERIC_READ;
401 break;
402 case O_WRONLY:
403 desiredAccess = GENERIC_WRITE;
404 break;
405 case O_RDWR:
406 desiredAccess = GENERIC_READ | GENERIC_WRITE;
407 break;
408 default:
409 D("adb_open: invalid options (0x%0x)\n", options);
410 errno = EINVAL;
411 return -1;
412 }
413
414 f = _fh_alloc( &_fh_file_class );
415 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800416 return -1;
417 }
418
Spencer Low6815c072015-05-11 01:08:48 -0700419 f->fh_handle = CreateFileW( widen(path).c_str(), desiredAccess, shareMode,
420 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800421
422 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700423 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800424 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700425 D( "adb_open: could not open '%s': ", path );
426 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800427 case ERROR_FILE_NOT_FOUND:
428 D( "file not found\n" );
429 errno = ENOENT;
430 return -1;
431
432 case ERROR_PATH_NOT_FOUND:
433 D( "path not found\n" );
434 errno = ENOTDIR;
435 return -1;
436
437 default:
Spencer Low1711e012015-08-02 18:50:17 -0700438 D( "unknown error: %s\n",
439 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800440 errno = ENOENT;
441 return -1;
442 }
443 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800444
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800445 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
446 D( "adb_open: '%s' => fd %d\n", path, _fh_to_int(f) );
447 return _fh_to_int(f);
448}
449
450/* ignore mode on Win32 */
451int adb_creat(const char* path, int mode)
452{
453 FH f;
454
455 f = _fh_alloc( &_fh_file_class );
456 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800457 return -1;
458 }
459
Spencer Low6815c072015-05-11 01:08:48 -0700460 f->fh_handle = CreateFileW( widen(path).c_str(), GENERIC_WRITE,
461 FILE_SHARE_READ | FILE_SHARE_WRITE,
462 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
463 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800464
465 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700466 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800467 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700468 D( "adb_creat: could not open '%s': ", path );
469 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800470 case ERROR_FILE_NOT_FOUND:
471 D( "file not found\n" );
472 errno = ENOENT;
473 return -1;
474
475 case ERROR_PATH_NOT_FOUND:
476 D( "path not found\n" );
477 errno = ENOTDIR;
478 return -1;
479
480 default:
Spencer Low1711e012015-08-02 18:50:17 -0700481 D( "unknown error: %s\n",
482 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483 errno = ENOENT;
484 return -1;
485 }
486 }
487 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
488 D( "adb_creat: '%s' => fd %d\n", path, _fh_to_int(f) );
489 return _fh_to_int(f);
490}
491
492
493int adb_read(int fd, void* buf, int len)
494{
Spencer Low3a2421b2015-05-22 20:09:06 -0700495 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800496
497 if (f == NULL) {
498 return -1;
499 }
500
501 return f->clazz->_fh_read( f, buf, len );
502}
503
504
505int adb_write(int fd, const void* buf, int len)
506{
Spencer Low3a2421b2015-05-22 20:09:06 -0700507 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800508
509 if (f == NULL) {
510 return -1;
511 }
512
513 return f->clazz->_fh_write(f, buf, len);
514}
515
516
517int adb_lseek(int fd, int pos, int where)
518{
Spencer Low3a2421b2015-05-22 20:09:06 -0700519 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800520
521 if (!f) {
522 return -1;
523 }
524
525 return f->clazz->_fh_lseek(f, pos, where);
526}
527
528
529int adb_close(int fd)
530{
Spencer Low3a2421b2015-05-22 20:09:06 -0700531 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800532
533 if (!f) {
534 return -1;
535 }
536
537 D( "adb_close: %s\n", f->name);
538 _fh_close(f);
539 return 0;
540}
541
542/**************************************************************************/
543/**************************************************************************/
544/***** *****/
545/***** socket-based file descriptors *****/
546/***** *****/
547/**************************************************************************/
548/**************************************************************************/
549
Spencer Low31aafa62015-01-25 14:40:16 -0800550#undef setsockopt
551
Spencer Low753d4852015-07-30 23:07:55 -0700552static void _socket_set_errno( const DWORD err ) {
553 // The Windows C Runtime (MSVCRT.DLL) strerror() does not support a lot of
554 // POSIX and socket error codes, so this can only meaningfully map so much.
555 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800556 case 0: errno = 0; break;
557 case WSAEWOULDBLOCK: errno = EAGAIN; break;
558 case WSAEINTR: errno = EINTR; break;
Spencer Low753d4852015-07-30 23:07:55 -0700559 case WSAEFAULT: errno = EFAULT; break;
560 case WSAEINVAL: errno = EINVAL; break;
561 case WSAEMFILE: errno = EMFILE; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800562 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800563 errno = EINVAL;
Spencer Low753d4852015-07-30 23:07:55 -0700564 D( "_socket_set_errno: mapping Windows error code %lu to errno %d\n",
565 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800566 }
567}
568
Elliott Hughes6a096932015-04-16 16:47:02 -0700569static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800570 f->fh_socket = INVALID_SOCKET;
571 f->event = WSACreateEvent();
Spencer Low753d4852015-07-30 23:07:55 -0700572 if (f->event == WSA_INVALID_EVENT) {
573 D("WSACreateEvent failed: %s\n",
574 SystemErrorCodeToString(WSAGetLastError()).c_str());
575
576 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
577 // on failure, instead of NULL which is what Windows really returns on
578 // error. It might be better to change all the other code to look for
579 // NULL, but that is a much riskier change.
580 f->event = INVALID_HANDLE_VALUE;
581 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800582 f->mask = 0;
583}
584
Elliott Hughes6a096932015-04-16 16:47:02 -0700585static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700586 if (f->fh_socket != INVALID_SOCKET) {
587 /* gently tell any peer that we're closing the socket */
588 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
589 // If the socket is not connected, this returns an error. We want to
590 // minimize logging spam, so don't log these errors for now.
591#if 0
592 D("socket shutdown failed: %s\n",
593 SystemErrorCodeToString(WSAGetLastError()).c_str());
594#endif
595 }
596 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
597 D("closesocket failed: %s\n",
598 SystemErrorCodeToString(WSAGetLastError()).c_str());
599 }
600 f->fh_socket = INVALID_SOCKET;
601 }
602 if (f->event != NULL) {
603 if (!CloseHandle(f->event)) {
604 D("CloseHandle failed: %s\n",
605 SystemErrorCodeToString(GetLastError()).c_str());
606 }
607 f->event = NULL;
608 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800609 f->mask = 0;
610 return 0;
611}
612
Elliott Hughes6a096932015-04-16 16:47:02 -0700613static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800614 errno = EPIPE;
615 return -1;
616}
617
Elliott Hughes6a096932015-04-16 16:47:02 -0700618static int _fh_socket_read(FH f, void* buf, int len) {
619 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800620 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700621 const DWORD err = WSAGetLastError();
622 D("recv fd %d failed: %s\n", _fh_to_int(f),
623 SystemErrorCodeToString(err).c_str());
624 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800625 result = -1;
626 }
627 return result;
628}
629
Elliott Hughes6a096932015-04-16 16:47:02 -0700630static int _fh_socket_write(FH f, const void* buf, int len) {
631 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800632 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700633 const DWORD err = WSAGetLastError();
634 D("send fd %d failed: %s\n", _fh_to_int(f),
635 SystemErrorCodeToString(err).c_str());
636 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800637 result = -1;
638 }
639 return result;
640}
641
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800642/**************************************************************************/
643/**************************************************************************/
644/***** *****/
645/***** replacement for libs/cutils/socket_xxxx.c *****/
646/***** *****/
647/**************************************************************************/
648/**************************************************************************/
649
650#include <winsock2.h>
651
652static int _winsock_init;
653
654static void
655_cleanup_winsock( void )
656{
Spencer Low753d4852015-07-30 23:07:55 -0700657 // TODO: WSAStartup() might be called multiple times and this won't properly
658 // cleanup the right number of times. Plus, WSACleanup() probably doesn't
659 // make sense since it might interrupt other threads using Winsock (since
660 // our various threads are not explicitly cleanly shutdown at process exit).
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800661 WSACleanup();
662}
663
664static void
665_init_winsock( void )
666{
Spencer Low753d4852015-07-30 23:07:55 -0700667 // TODO: Multiple threads calling this may potentially cause multiple calls
668 // to WSAStartup() and multiple atexit() calls.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800669 if (!_winsock_init) {
670 WSADATA wsaData;
671 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
672 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700673 fatal( "adb: could not initialize Winsock: %s",
674 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800675 }
676 atexit( _cleanup_winsock );
677 _winsock_init = 1;
678 }
679}
680
Spencer Low753d4852015-07-30 23:07:55 -0700681int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800682 struct sockaddr_in addr;
683 SOCKET s;
684
Spencer Low753d4852015-07-30 23:07:55 -0700685 unique_fh f(_fh_alloc(&_fh_socket_class));
686 if (!f) {
687 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800688 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700689 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800690
691 if (!_winsock_init)
692 _init_winsock();
693
694 memset(&addr, 0, sizeof(addr));
695 addr.sin_family = AF_INET;
696 addr.sin_port = htons(port);
697 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
698
699 s = socket(AF_INET, type, 0);
700 if(s == INVALID_SOCKET) {
Spencer Low753d4852015-07-30 23:07:55 -0700701 *error = SystemErrorCodeToString(WSAGetLastError());
702 D("could not create socket: %s\n", error->c_str());
703 return -1;
704 }
705 f->fh_socket = s;
706
707 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
708 *error = SystemErrorCodeToString(WSAGetLastError());
709 D("could not connect to %s:%d: %s\n",
710 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800711 return -1;
712 }
713
Spencer Low753d4852015-07-30 23:07:55 -0700714 const int fd = _fh_to_int(f.get());
715 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
716 type != SOCK_STREAM ? "udp:" : "", port );
717 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
718 fd );
719 f.release();
720 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800721}
722
723#define LISTEN_BACKLOG 4
724
Spencer Low753d4852015-07-30 23:07:55 -0700725// interface_address is INADDR_LOOPBACK or INADDR_ANY.
726static int _network_server(int port, int type, u_long interface_address,
727 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800728 struct sockaddr_in addr;
729 SOCKET s;
730 int n;
731
Spencer Low753d4852015-07-30 23:07:55 -0700732 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800733 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700734 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800735 return -1;
736 }
737
738 if (!_winsock_init)
739 _init_winsock();
740
741 memset(&addr, 0, sizeof(addr));
742 addr.sin_family = AF_INET;
743 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700744 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800745
Spencer Low753d4852015-07-30 23:07:55 -0700746 // TODO: Consider using dual-stack socket that can simultaneously listen on
747 // IPv4 and IPv6.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800748 s = socket(AF_INET, type, 0);
Spencer Low753d4852015-07-30 23:07:55 -0700749 if (s == INVALID_SOCKET) {
750 *error = SystemErrorCodeToString(WSAGetLastError());
751 D("could not create socket: %s\n", error->c_str());
752 return -1;
753 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800754
755 f->fh_socket = s;
756
757 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700758 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
759 sizeof(n)) == SOCKET_ERROR) {
760 *error = SystemErrorCodeToString(WSAGetLastError());
761 D("setsockopt level %d optname %d failed: %s\n",
762 SOL_SOCKET, SO_EXCLUSIVEADDRUSE, error->c_str());
763 return -1;
764 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800765
Spencer Low753d4852015-07-30 23:07:55 -0700766 if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
767 *error = SystemErrorCodeToString(WSAGetLastError());
768 D("could not bind to %s:%d: %s\n",
769 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800770 return -1;
771 }
772 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700773 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
774 *error = SystemErrorCodeToString(WSAGetLastError());
775 D("could not listen on %s:%d: %s\n",
776 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800777 return -1;
778 }
779 }
Spencer Low753d4852015-07-30 23:07:55 -0700780 const int fd = _fh_to_int(f.get());
781 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
782 interface_address == INADDR_LOOPBACK ? "lo" : "any",
783 type != SOCK_STREAM ? "udp:" : "", port );
784 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
785 fd );
786 f.release();
787 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800788}
789
Spencer Low753d4852015-07-30 23:07:55 -0700790int network_loopback_server(int port, int type, std::string* error) {
791 return _network_server(port, type, INADDR_LOOPBACK, error);
792}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800793
Spencer Low753d4852015-07-30 23:07:55 -0700794int network_inaddr_any_server(int port, int type, std::string* error) {
795 return _network_server(port, type, INADDR_ANY, error);
796}
797
798int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
799 unique_fh f(_fh_alloc(&_fh_socket_class));
800 if (!f) {
801 *error = strerror(errno);
802 return -1;
803 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800804
Elliott Hughes43df1092015-07-23 17:12:58 -0700805 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800806
Spencer Low753d4852015-07-30 23:07:55 -0700807 struct addrinfo hints;
808 memset(&hints, 0, sizeof(hints));
809 hints.ai_family = AF_UNSPEC;
810 hints.ai_socktype = type;
811
812 char port_str[16];
813 snprintf(port_str, sizeof(port_str), "%d", port);
814
815 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700816
817#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
818 // TODO: When the Android SDK tools increases the Windows system
819 // requirements >= WinXP SP2, switch to GetAddrInfoW(widen(host).c_str()).
820#else
821 // Otherwise, keep using getaddrinfo(), or do runtime API detection
822 // with GetProcAddress("GetAddrInfoW").
823#endif
Spencer Low753d4852015-07-30 23:07:55 -0700824 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
825 *error = SystemErrorCodeToString(WSAGetLastError());
826 D("could not resolve host '%s' and port %s: %s\n", host.c_str(),
827 port_str, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800828 return -1;
829 }
Spencer Low753d4852015-07-30 23:07:55 -0700830 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
831 addrinfo(addrinfo_ptr, freeaddrinfo);
832 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800833
Spencer Low753d4852015-07-30 23:07:55 -0700834 // TODO: Try all the addresses if there's more than one? This just uses
835 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
836 // which tries all addresses, takes a timeout and more.
837 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
838 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800839 if(s == INVALID_SOCKET) {
Spencer Low753d4852015-07-30 23:07:55 -0700840 *error = SystemErrorCodeToString(WSAGetLastError());
841 D("could not create socket: %s\n", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800842 return -1;
843 }
844 f->fh_socket = s;
845
Spencer Low753d4852015-07-30 23:07:55 -0700846 // TODO: Implement timeouts for Windows. Seems like the default in theory
847 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
848 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
849 *error = SystemErrorCodeToString(WSAGetLastError());
850 D("could not connect to %s:%s:%s: %s\n",
851 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
852 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800853 return -1;
854 }
855
Spencer Low753d4852015-07-30 23:07:55 -0700856 const int fd = _fh_to_int(f.get());
857 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
858 type != SOCK_STREAM ? "udp:" : "", port );
859 D( "host '%s' port %d type %s => fd %d\n", host.c_str(), port,
860 type != SOCK_STREAM ? "udp" : "tcp", fd );
861 f.release();
862 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800863}
864
865#undef accept
866int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
867{
Spencer Low3a2421b2015-05-22 20:09:06 -0700868 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200869
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800870 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Spencer Low753d4852015-07-30 23:07:55 -0700871 D("adb_socket_accept: invalid fd %d\n", serverfd);
872 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800873 return -1;
874 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200875
Spencer Low753d4852015-07-30 23:07:55 -0700876 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800877 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700878 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
879 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800880 return -1;
881 }
882
883 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
884 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700885 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700886 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
887 " failed: " + SystemErrorCodeToString(err);
888 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800889 return -1;
890 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200891
Spencer Low753d4852015-07-30 23:07:55 -0700892 const int fd = _fh_to_int(fh.get());
893 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
894 D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, fd );
895 fh.release();
896 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800897}
898
899
Spencer Low31aafa62015-01-25 14:40:16 -0800900int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800901{
Spencer Low3a2421b2015-05-22 20:09:06 -0700902 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200903
Spencer Low31aafa62015-01-25 14:40:16 -0800904 if ( !fh || fh->clazz != &_fh_socket_class ) {
905 D("adb_setsockopt: invalid fd %d\n", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700906 errno = EBADF;
907 return -1;
908 }
909 int result = setsockopt( fh->fh_socket, level, optname,
910 reinterpret_cast<const char*>(optval), optlen );
911 if ( result == SOCKET_ERROR ) {
912 const DWORD err = WSAGetLastError();
913 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
914 "failed: %s\n", fd, level, optname,
915 SystemErrorCodeToString(err).c_str() );
916 _socket_set_errno( err );
917 result = -1;
918 }
919 return result;
920}
921
922
923int adb_shutdown(int fd)
924{
925 FH f = _fh_from_int(fd, __func__);
926
927 if (!f || f->clazz != &_fh_socket_class) {
928 D("adb_shutdown: invalid fd %d\n", fd);
929 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -0800930 return -1;
931 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800932
Spencer Low753d4852015-07-30 23:07:55 -0700933 D( "adb_shutdown: %s\n", f->name);
934 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
935 const DWORD err = WSAGetLastError();
936 D("socket shutdown fd %d failed: %s\n", fd,
937 SystemErrorCodeToString(err).c_str());
938 _socket_set_errno(err);
939 return -1;
940 }
941 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800942}
943
944/**************************************************************************/
945/**************************************************************************/
946/***** *****/
947/***** emulated socketpairs *****/
948/***** *****/
949/**************************************************************************/
950/**************************************************************************/
951
952/* we implement socketpairs directly in use space for the following reasons:
953 * - it avoids copying data from/to the Nt kernel
954 * - it allows us to implement fdevent hooks easily and cheaply, something
955 * that is not possible with standard Win32 pipes !!
956 *
957 * basically, we use two circular buffers, each one corresponding to a given
958 * direction.
959 *
960 * each buffer is implemented as two regions:
961 *
962 * region A which is (a_start,a_end)
963 * region B which is (0, b_end) with b_end <= a_start
964 *
965 * an empty buffer has: a_start = a_end = b_end = 0
966 *
967 * a_start is the pointer where we start reading data
968 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
969 * then you start writing at b_end
970 *
971 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
972 *
973 * there is room when b_end < a_start || a_end < BUFER_SIZE
974 *
975 * when reading, a_start is incremented, it a_start meets a_end, then
976 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
977 */
978
979#define BIP_BUFFER_SIZE 4096
980
981#if 0
982#include <stdio.h>
983# define BIPD(x) D x
984# define BIPDUMP bip_dump_hex
985
986static void bip_dump_hex( const unsigned char* ptr, size_t len )
987{
988 int nn, len2 = len;
989
990 if (len2 > 8) len2 = 8;
991
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800992 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800993 printf("%02x", ptr[nn]);
994 printf(" ");
995
996 for (nn = 0; nn < len2; nn++) {
997 int c = ptr[nn];
998 if (c < 32 || c > 127)
999 c = '.';
1000 printf("%c", c);
1001 }
1002 printf("\n");
1003 fflush(stdout);
1004}
1005
1006#else
1007# define BIPD(x) do {} while (0)
1008# define BIPDUMP(p,l) BIPD(p)
1009#endif
1010
1011typedef struct BipBufferRec_
1012{
1013 int a_start;
1014 int a_end;
1015 int b_end;
1016 int fdin;
1017 int fdout;
1018 int closed;
1019 int can_write; /* boolean */
1020 HANDLE evt_write; /* event signaled when one can write to a buffer */
1021 int can_read; /* boolean */
1022 HANDLE evt_read; /* event signaled when one can read from a buffer */
1023 CRITICAL_SECTION lock;
1024 unsigned char buff[ BIP_BUFFER_SIZE ];
1025
1026} BipBufferRec, *BipBuffer;
1027
1028static void
1029bip_buffer_init( BipBuffer buffer )
1030{
1031 D( "bit_buffer_init %p\n", buffer );
1032 buffer->a_start = 0;
1033 buffer->a_end = 0;
1034 buffer->b_end = 0;
1035 buffer->can_write = 1;
1036 buffer->can_read = 0;
1037 buffer->fdin = 0;
1038 buffer->fdout = 0;
1039 buffer->closed = 0;
1040 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1041 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1042 InitializeCriticalSection( &buffer->lock );
1043}
1044
1045static void
1046bip_buffer_close( BipBuffer bip )
1047{
1048 bip->closed = 1;
1049
1050 if (!bip->can_read) {
1051 SetEvent( bip->evt_read );
1052 }
1053 if (!bip->can_write) {
1054 SetEvent( bip->evt_write );
1055 }
1056}
1057
1058static void
1059bip_buffer_done( BipBuffer bip )
1060{
1061 BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
1062 CloseHandle( bip->evt_read );
1063 CloseHandle( bip->evt_write );
1064 DeleteCriticalSection( &bip->lock );
1065}
1066
1067static int
1068bip_buffer_write( BipBuffer bip, const void* src, int len )
1069{
1070 int avail, count = 0;
1071
1072 if (len <= 0)
1073 return 0;
1074
1075 BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1076 BIPDUMP( src, len );
1077
1078 EnterCriticalSection( &bip->lock );
1079
1080 while (!bip->can_write) {
1081 int ret;
1082 LeaveCriticalSection( &bip->lock );
1083
1084 if (bip->closed) {
1085 errno = EPIPE;
1086 return -1;
1087 }
1088 /* spinlocking here is probably unfair, but let's live with it */
1089 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1090 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
1091 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
1092 return 0;
1093 }
1094 if (bip->closed) {
1095 errno = EPIPE;
1096 return -1;
1097 }
1098 EnterCriticalSection( &bip->lock );
1099 }
1100
1101 BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1102
1103 avail = BIP_BUFFER_SIZE - bip->a_end;
1104 if (avail > 0)
1105 {
1106 /* we can append to region A */
1107 if (avail > len)
1108 avail = len;
1109
1110 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001111 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001112 count += avail;
1113 len -= avail;
1114
1115 bip->a_end += avail;
1116 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1117 bip->can_write = 0;
1118 ResetEvent( bip->evt_write );
1119 goto Exit;
1120 }
1121 }
1122
1123 if (len == 0)
1124 goto Exit;
1125
1126 avail = bip->a_start - bip->b_end;
1127 assert( avail > 0 ); /* since can_write is TRUE */
1128
1129 if (avail > len)
1130 avail = len;
1131
1132 memcpy( bip->buff + bip->b_end, src, avail );
1133 count += avail;
1134 bip->b_end += avail;
1135
1136 if (bip->b_end == bip->a_start) {
1137 bip->can_write = 0;
1138 ResetEvent( bip->evt_write );
1139 }
1140
1141Exit:
1142 assert( count > 0 );
1143
1144 if ( !bip->can_read ) {
1145 bip->can_read = 1;
1146 SetEvent( bip->evt_read );
1147 }
1148
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001149 BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001150 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1151 LeaveCriticalSection( &bip->lock );
1152
1153 return count;
1154 }
1155
1156static int
1157bip_buffer_read( BipBuffer bip, void* dst, int len )
1158{
1159 int avail, count = 0;
1160
1161 if (len <= 0)
1162 return 0;
1163
1164 BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1165
1166 EnterCriticalSection( &bip->lock );
1167 while ( !bip->can_read )
1168 {
1169#if 0
1170 LeaveCriticalSection( &bip->lock );
1171 errno = EAGAIN;
1172 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001173#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001174 int ret;
1175 LeaveCriticalSection( &bip->lock );
1176
1177 if (bip->closed) {
1178 errno = EPIPE;
1179 return -1;
1180 }
1181
1182 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1183 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
1184 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
1185 return 0;
1186 }
1187 if (bip->closed) {
1188 errno = EPIPE;
1189 return -1;
1190 }
1191 EnterCriticalSection( &bip->lock );
1192#endif
1193 }
1194
1195 BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1196
1197 avail = bip->a_end - bip->a_start;
1198 assert( avail > 0 ); /* since can_read is TRUE */
1199
1200 if (avail > len)
1201 avail = len;
1202
1203 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001204 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001205 count += avail;
1206 len -= avail;
1207
1208 bip->a_start += avail;
1209 if (bip->a_start < bip->a_end)
1210 goto Exit;
1211
1212 bip->a_start = 0;
1213 bip->a_end = bip->b_end;
1214 bip->b_end = 0;
1215
1216 avail = bip->a_end;
1217 if (avail > 0) {
1218 if (avail > len)
1219 avail = len;
1220 memcpy( dst, bip->buff, avail );
1221 count += avail;
1222 bip->a_start += avail;
1223
1224 if ( bip->a_start < bip->a_end )
1225 goto Exit;
1226
1227 bip->a_start = bip->a_end = 0;
1228 }
1229
1230 bip->can_read = 0;
1231 ResetEvent( bip->evt_read );
1232
1233Exit:
1234 assert( count > 0 );
1235
1236 if (!bip->can_write ) {
1237 bip->can_write = 1;
1238 SetEvent( bip->evt_write );
1239 }
1240
1241 BIPDUMP( (const unsigned char*)dst - count, count );
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001242 BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001243 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1244 LeaveCriticalSection( &bip->lock );
1245
1246 return count;
1247}
1248
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001249typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001250{
1251 BipBufferRec a2b_bip;
1252 BipBufferRec b2a_bip;
1253 FH a_fd;
1254 int used;
1255
1256} SocketPairRec;
1257
1258void _fh_socketpair_init( FH f )
1259{
1260 f->fh_pair = NULL;
1261}
1262
1263static int
1264_fh_socketpair_close( FH f )
1265{
1266 if ( f->fh_pair ) {
1267 SocketPair pair = f->fh_pair;
1268
1269 if ( f == pair->a_fd ) {
1270 pair->a_fd = NULL;
1271 }
1272
1273 bip_buffer_close( &pair->b2a_bip );
1274 bip_buffer_close( &pair->a2b_bip );
1275
1276 if ( --pair->used == 0 ) {
1277 bip_buffer_done( &pair->b2a_bip );
1278 bip_buffer_done( &pair->a2b_bip );
1279 free( pair );
1280 }
1281 f->fh_pair = NULL;
1282 }
1283 return 0;
1284}
1285
1286static int
1287_fh_socketpair_lseek( FH f, int pos, int origin )
1288{
1289 errno = ESPIPE;
1290 return -1;
1291}
1292
1293static int
1294_fh_socketpair_read( FH f, void* buf, int len )
1295{
1296 SocketPair pair = f->fh_pair;
1297 BipBuffer bip;
1298
1299 if (!pair)
1300 return -1;
1301
1302 if ( f == pair->a_fd )
1303 bip = &pair->b2a_bip;
1304 else
1305 bip = &pair->a2b_bip;
1306
1307 return bip_buffer_read( bip, buf, len );
1308}
1309
1310static int
1311_fh_socketpair_write( FH f, const void* buf, int len )
1312{
1313 SocketPair pair = f->fh_pair;
1314 BipBuffer bip;
1315
1316 if (!pair)
1317 return -1;
1318
1319 if ( f == pair->a_fd )
1320 bip = &pair->a2b_bip;
1321 else
1322 bip = &pair->b2a_bip;
1323
1324 return bip_buffer_write( bip, buf, len );
1325}
1326
1327
1328static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1329
1330static const FHClassRec _fh_socketpair_class =
1331{
1332 _fh_socketpair_init,
1333 _fh_socketpair_close,
1334 _fh_socketpair_lseek,
1335 _fh_socketpair_read,
1336 _fh_socketpair_write,
1337 _fh_socketpair_hook
1338};
1339
1340
Elliott Hughes6a096932015-04-16 16:47:02 -07001341int adb_socketpair(int sv[2]) {
1342 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001343
Spencer Low753d4852015-07-30 23:07:55 -07001344 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1345 if (!fa) {
1346 return -1;
1347 }
1348 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1349 if (!fb) {
1350 return -1;
1351 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001352
Elliott Hughes6a096932015-04-16 16:47:02 -07001353 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001354 if (pair == NULL) {
1355 D("adb_socketpair: not enough memory to allocate pipes\n" );
Spencer Low753d4852015-07-30 23:07:55 -07001356 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001357 }
1358
1359 bip_buffer_init( &pair->a2b_bip );
1360 bip_buffer_init( &pair->b2a_bip );
1361
1362 fa->fh_pair = pair;
1363 fb->fh_pair = pair;
1364 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001365 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001366
Spencer Low753d4852015-07-30 23:07:55 -07001367 sv[0] = _fh_to_int(fa.get());
1368 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001369
1370 pair->a2b_bip.fdin = sv[0];
1371 pair->a2b_bip.fdout = sv[1];
1372 pair->b2a_bip.fdin = sv[1];
1373 pair->b2a_bip.fdout = sv[0];
1374
1375 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1376 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
1377 D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001378 fa.release();
1379 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001380 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001381}
1382
1383/**************************************************************************/
1384/**************************************************************************/
1385/***** *****/
1386/***** fdevents emulation *****/
1387/***** *****/
1388/***** this is a very simple implementation, we rely on the fact *****/
1389/***** that ADB doesn't use FDE_ERROR. *****/
1390/***** *****/
1391/**************************************************************************/
1392/**************************************************************************/
1393
1394#define FATAL(x...) fatal(__FUNCTION__, x)
1395
1396#if DEBUG
1397static void dump_fde(fdevent *fde, const char *info)
1398{
1399 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1400 fde->state & FDE_READ ? 'R' : ' ',
1401 fde->state & FDE_WRITE ? 'W' : ' ',
1402 fde->state & FDE_ERROR ? 'E' : ' ',
1403 info);
1404}
1405#else
1406#define dump_fde(fde, info) do { } while(0)
1407#endif
1408
1409#define FDE_EVENTMASK 0x00ff
1410#define FDE_STATEMASK 0xff00
1411
1412#define FDE_ACTIVE 0x0100
1413#define FDE_PENDING 0x0200
1414#define FDE_CREATED 0x0400
1415
1416static void fdevent_plist_enqueue(fdevent *node);
1417static void fdevent_plist_remove(fdevent *node);
1418static fdevent *fdevent_plist_dequeue(void);
1419
1420static fdevent list_pending = {
1421 .next = &list_pending,
1422 .prev = &list_pending,
1423};
1424
1425static fdevent **fd_table = 0;
1426static int fd_table_max = 0;
1427
1428typedef struct EventLooperRec_* EventLooper;
1429
1430typedef struct EventHookRec_
1431{
1432 EventHook next;
1433 FH fh;
1434 HANDLE h;
1435 int wanted; /* wanted event flags */
1436 int ready; /* ready event flags */
1437 void* aux;
1438 void (*prepare)( EventHook hook );
1439 int (*start) ( EventHook hook );
1440 void (*stop) ( EventHook hook );
1441 int (*check) ( EventHook hook );
1442 int (*peek) ( EventHook hook );
1443} EventHookRec;
1444
1445static EventHook _free_hooks;
1446
1447static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001448event_hook_alloc(FH fh) {
1449 EventHook hook = _free_hooks;
1450 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001451 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001452 } else {
1453 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001454 if (hook == NULL)
1455 fatal( "could not allocate event hook\n" );
1456 }
1457 hook->next = NULL;
1458 hook->fh = fh;
1459 hook->wanted = 0;
1460 hook->ready = 0;
1461 hook->h = INVALID_HANDLE_VALUE;
1462 hook->aux = NULL;
1463
1464 hook->prepare = NULL;
1465 hook->start = NULL;
1466 hook->stop = NULL;
1467 hook->check = NULL;
1468 hook->peek = NULL;
1469
1470 return hook;
1471}
1472
1473static void
1474event_hook_free( EventHook hook )
1475{
1476 hook->fh = NULL;
1477 hook->wanted = 0;
1478 hook->ready = 0;
1479 hook->next = _free_hooks;
1480 _free_hooks = hook;
1481}
1482
1483
1484static void
1485event_hook_signal( EventHook hook )
1486{
1487 FH f = hook->fh;
1488 int fd = _fh_to_int(f);
1489 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1490
1491 if (fde != NULL && fde->fd == fd) {
1492 if ((fde->state & FDE_PENDING) == 0) {
1493 fde->state |= FDE_PENDING;
1494 fdevent_plist_enqueue( fde );
1495 }
1496 fde->events |= hook->wanted;
1497 }
1498}
1499
1500
1501#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1502
1503typedef struct EventLooperRec_
1504{
1505 EventHook hooks;
1506 HANDLE htab[ MAX_LOOPER_HANDLES ];
1507 int htab_count;
1508
1509} EventLooperRec;
1510
1511static EventHook*
1512event_looper_find_p( EventLooper looper, FH fh )
1513{
1514 EventHook *pnode = &looper->hooks;
1515 EventHook node = *pnode;
1516 for (;;) {
1517 if ( node == NULL || node->fh == fh )
1518 break;
1519 pnode = &node->next;
1520 node = *pnode;
1521 }
1522 return pnode;
1523}
1524
1525static void
1526event_looper_hook( EventLooper looper, int fd, int events )
1527{
Spencer Low3a2421b2015-05-22 20:09:06 -07001528 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001529 EventHook *pnode;
1530 EventHook node;
1531
1532 if (f == NULL) /* invalid arg */ {
1533 D("event_looper_hook: invalid fd=%d\n", fd);
1534 return;
1535 }
1536
1537 pnode = event_looper_find_p( looper, f );
1538 node = *pnode;
1539 if ( node == NULL ) {
1540 node = event_hook_alloc( f );
1541 node->next = *pnode;
1542 *pnode = node;
1543 }
1544
1545 if ( (node->wanted & events) != events ) {
1546 /* this should update start/stop/check/peek */
1547 D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
1548 fd, node->wanted, events);
1549 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1550 node->wanted |= events;
1551 } else {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001552 D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001553 events, fd, node->wanted);
1554 }
1555}
1556
1557static void
1558event_looper_unhook( EventLooper looper, int fd, int events )
1559{
Spencer Low3a2421b2015-05-22 20:09:06 -07001560 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001561 EventHook *pnode = event_looper_find_p( looper, fh );
1562 EventHook node = *pnode;
1563
1564 if (node != NULL) {
1565 int events2 = events & node->wanted;
1566 if ( events2 == 0 ) {
1567 D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
1568 return;
1569 }
1570 node->wanted &= ~events2;
1571 if (!node->wanted) {
1572 *pnode = node->next;
1573 event_hook_free( node );
1574 }
1575 }
1576}
1577
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001578/*
1579 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1580 * handles to wait on.
1581 *
1582 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1583 * instance, this may happen if there are more than 64 processes running on a
1584 * device, or there are multiple devices connected (including the emulator) with
1585 * the combined number of running processes greater than 64. In this case using
1586 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1587 * because of the API limitations (64 handles max). So, we need to provide a way
1588 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1589 * easiest (and "Microsoft recommended") way to do that would be dividing the
1590 * handle array into chunks with the chunk size less than 64, and fire up as many
1591 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1592 * handles, and will report back to the caller which handle has been set.
1593 * Here is the implementation of that algorithm.
1594 */
1595
1596/* Number of handles to wait on in each wating thread. */
1597#define WAIT_ALL_CHUNK_SIZE 63
1598
1599/* Descriptor for a wating thread */
1600typedef struct WaitForAllParam {
1601 /* A handle to an event to signal when waiting is over. This handle is shared
1602 * accross all the waiting threads, so each waiting thread knows when any
1603 * other thread has exited, so it can exit too. */
1604 HANDLE main_event;
1605 /* Upon exit from a waiting thread contains the index of the handle that has
1606 * been signaled. The index is an absolute index of the signaled handle in
1607 * the original array. This pointer is shared accross all the waiting threads
1608 * and it's not guaranteed (due to a race condition) that when all the
1609 * waiting threads exit, the value contained here would indicate the first
1610 * handle that was signaled. This is fine, because the caller cares only
1611 * about any handle being signaled. It doesn't care about the order, nor
1612 * about the whole list of handles that were signaled. */
1613 LONG volatile *signaled_index;
1614 /* Array of handles to wait on in a waiting thread. */
1615 HANDLE* handles;
1616 /* Number of handles in 'handles' array to wait on. */
1617 int handles_count;
1618 /* Index inside the main array of the first handle in the 'handles' array. */
1619 int first_handle_index;
1620 /* Waiting thread handle. */
1621 HANDLE thread;
1622} WaitForAllParam;
1623
1624/* Waiting thread routine. */
1625static unsigned __stdcall
1626_in_waiter_thread(void* arg)
1627{
1628 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1629 int res;
1630 WaitForAllParam* const param = (WaitForAllParam*)arg;
1631
1632 /* We have to wait on the main_event in order to be notified when any of the
1633 * sibling threads is exiting. */
1634 wait_on[0] = param->main_event;
1635 /* The rest of the handles go behind the main event handle. */
1636 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1637
1638 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1639 if (res > 0 && res < (param->handles_count + 1)) {
1640 /* One of the original handles got signaled. Save its absolute index into
1641 * the output variable. */
1642 InterlockedCompareExchange(param->signaled_index,
1643 res - 1L + param->first_handle_index, -1L);
1644 }
1645
1646 /* Notify the caller (and the siblings) that the wait is over. */
1647 SetEvent(param->main_event);
1648
1649 _endthreadex(0);
1650 return 0;
1651}
1652
1653/* WaitForMultipeObjects fixer routine.
1654 * Param:
1655 * handles Array of handles to wait on.
1656 * handles_count Number of handles in the array.
1657 * Return:
1658 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1659 * WAIT_FAILED on an error.
1660 */
1661static int
1662_wait_for_all(HANDLE* handles, int handles_count)
1663{
1664 WaitForAllParam* threads;
1665 HANDLE main_event;
1666 int chunks, chunk, remains;
1667
1668 /* This variable is going to be accessed by several threads at the same time,
1669 * this is bound to fail randomly when the core is run on multi-core machines.
1670 * To solve this, we need to do the following (1 _and_ 2):
1671 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1672 * out the reads/writes in this function unexpectedly.
1673 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1674 * all accesses inside a critical section. But we can also use
1675 * InterlockedCompareExchange() which always provide a full memory barrier
1676 * on Win32.
1677 */
1678 volatile LONG sig_index = -1;
1679
1680 /* Calculate number of chunks, and allocate thread param array. */
1681 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1682 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1683 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1684 sizeof(WaitForAllParam));
1685 if (threads == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001686 D("Unable to allocate thread array for %d handles.\n", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001687 return (int)WAIT_FAILED;
1688 }
1689
1690 /* Create main event to wait on for all waiting threads. This is a "manualy
1691 * reset" event that will remain set once it was set. */
1692 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1693 if (main_event == NULL) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001694 D("Unable to create main event. Error: %ld\n", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001695 free(threads);
1696 return (int)WAIT_FAILED;
1697 }
1698
1699 /*
1700 * Initialize waiting thread parameters.
1701 */
1702
1703 for (chunk = 0; chunk < chunks; chunk++) {
1704 threads[chunk].main_event = main_event;
1705 threads[chunk].signaled_index = &sig_index;
1706 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1707 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1708 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1709 }
1710 if (remains) {
1711 threads[chunk].main_event = main_event;
1712 threads[chunk].signaled_index = &sig_index;
1713 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1714 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1715 threads[chunk].handles_count = remains;
1716 chunks++;
1717 }
1718
1719 /* Start the waiting threads. */
1720 for (chunk = 0; chunk < chunks; chunk++) {
1721 /* Note that using adb_thread_create is not appropriate here, since we
1722 * need a handle to wait on for thread termination. */
1723 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1724 &threads[chunk], 0, NULL);
1725 if (threads[chunk].thread == NULL) {
1726 /* Unable to create a waiter thread. Collapse. */
Spencer Low5c761bd2015-07-21 02:06:26 -07001727 D("Unable to create a waiting thread %d of %d. errno=%d\n",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001728 chunk, chunks, errno);
1729 chunks = chunk;
1730 SetEvent(main_event);
1731 break;
1732 }
1733 }
1734
1735 /* Wait on any of the threads to get signaled. */
1736 WaitForSingleObject(main_event, INFINITE);
1737
1738 /* Wait on all the waiting threads to exit. */
1739 for (chunk = 0; chunk < chunks; chunk++) {
1740 WaitForSingleObject(threads[chunk].thread, INFINITE);
1741 CloseHandle(threads[chunk].thread);
1742 }
1743
1744 CloseHandle(main_event);
1745 free(threads);
1746
1747
1748 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1749 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1750}
1751
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001752static EventLooperRec win32_looper;
1753
1754static void fdevent_init(void)
1755{
1756 win32_looper.htab_count = 0;
1757 win32_looper.hooks = NULL;
1758}
1759
1760static void fdevent_connect(fdevent *fde)
1761{
1762 EventLooper looper = &win32_looper;
1763 int events = fde->state & FDE_EVENTMASK;
1764
1765 if (events != 0)
1766 event_looper_hook( looper, fde->fd, events );
1767}
1768
1769static void fdevent_disconnect(fdevent *fde)
1770{
1771 EventLooper looper = &win32_looper;
1772 int events = fde->state & FDE_EVENTMASK;
1773
1774 if (events != 0)
1775 event_looper_unhook( looper, fde->fd, events );
1776}
1777
1778static void fdevent_update(fdevent *fde, unsigned events)
1779{
1780 EventLooper looper = &win32_looper;
1781 unsigned events0 = fde->state & FDE_EVENTMASK;
1782
1783 if (events != events0) {
1784 int removes = events0 & ~events;
1785 int adds = events & ~events0;
1786 if (removes) {
1787 D("fdevent_update: remove %x from %d\n", removes, fde->fd);
1788 event_looper_unhook( looper, fde->fd, removes );
1789 }
1790 if (adds) {
1791 D("fdevent_update: add %x to %d\n", adds, fde->fd);
1792 event_looper_hook ( looper, fde->fd, adds );
1793 }
1794 }
1795}
1796
1797static void fdevent_process()
1798{
1799 EventLooper looper = &win32_looper;
1800 EventHook hook;
1801 int gotone = 0;
1802
1803 /* if we have at least one ready hook, execute it/them */
1804 for (hook = looper->hooks; hook; hook = hook->next) {
1805 hook->ready = 0;
1806 if (hook->prepare) {
1807 hook->prepare(hook);
1808 if (hook->ready != 0) {
1809 event_hook_signal( hook );
1810 gotone = 1;
1811 }
1812 }
1813 }
1814
1815 /* nothing's ready yet, so wait for something to happen */
1816 if (!gotone)
1817 {
1818 looper->htab_count = 0;
1819
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001820 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001821 {
1822 if (hook->start && !hook->start(hook)) {
1823 D( "fdevent_process: error when starting a hook\n" );
1824 return;
1825 }
1826 if (hook->h != INVALID_HANDLE_VALUE) {
1827 int nn;
1828
1829 for (nn = 0; nn < looper->htab_count; nn++)
1830 {
1831 if ( looper->htab[nn] == hook->h )
1832 goto DontAdd;
1833 }
1834 looper->htab[ looper->htab_count++ ] = hook->h;
1835 DontAdd:
1836 ;
1837 }
1838 }
1839
1840 if (looper->htab_count == 0) {
1841 D( "fdevent_process: nothing to wait for !!\n" );
1842 return;
1843 }
1844
1845 do
1846 {
1847 int wait_ret;
1848
1849 D( "adb_win32: waiting for %d events\n", looper->htab_count );
1850 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001851 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
1852 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1853 } else {
1854 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001855 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001856 if (wait_ret == (int)WAIT_FAILED) {
1857 D( "adb_win32: wait failed, error %ld\n", GetLastError() );
1858 } else {
1859 D( "adb_win32: got one (index %d)\n", wait_ret );
1860
1861 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1862 * like mouse movements. we need to filter these with the "check" function
1863 */
1864 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1865 {
1866 for (hook = looper->hooks; hook; hook = hook->next)
1867 {
1868 if ( looper->htab[wait_ret] == hook->h &&
1869 (!hook->check || hook->check(hook)) )
1870 {
1871 D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
1872 event_hook_signal( hook );
1873 gotone = 1;
1874 break;
1875 }
1876 }
1877 }
1878 }
1879 }
1880 while (!gotone);
1881
1882 for (hook = looper->hooks; hook; hook = hook->next) {
1883 if (hook->stop)
1884 hook->stop( hook );
1885 }
1886 }
1887
1888 for (hook = looper->hooks; hook; hook = hook->next) {
1889 if (hook->peek && hook->peek(hook))
1890 event_hook_signal( hook );
1891 }
1892}
1893
1894
1895static void fdevent_register(fdevent *fde)
1896{
1897 int fd = fde->fd - WIN32_FH_BASE;
1898
1899 if(fd < 0) {
1900 FATAL("bogus negative fd (%d)\n", fde->fd);
1901 }
1902
1903 if(fd >= fd_table_max) {
1904 int oldmax = fd_table_max;
1905 if(fde->fd > 32000) {
1906 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1907 }
1908 if(fd_table_max == 0) {
1909 fdevent_init();
1910 fd_table_max = 256;
1911 }
1912 while(fd_table_max <= fd) {
1913 fd_table_max *= 2;
1914 }
Elliott Hughes6a096932015-04-16 16:47:02 -07001915 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001916 if(fd_table == 0) {
1917 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1918 }
1919 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
1920 }
1921
1922 fd_table[fd] = fde;
1923}
1924
1925static void fdevent_unregister(fdevent *fde)
1926{
1927 int fd = fde->fd - WIN32_FH_BASE;
1928
1929 if((fd < 0) || (fd >= fd_table_max)) {
1930 FATAL("fd out of range (%d)\n", fde->fd);
1931 }
1932
1933 if(fd_table[fd] != fde) {
1934 FATAL("fd_table out of sync");
1935 }
1936
1937 fd_table[fd] = 0;
1938
1939 if(!(fde->state & FDE_DONT_CLOSE)) {
1940 dump_fde(fde, "close");
1941 adb_close(fde->fd);
1942 }
1943}
1944
1945static void fdevent_plist_enqueue(fdevent *node)
1946{
1947 fdevent *list = &list_pending;
1948
1949 node->next = list;
1950 node->prev = list->prev;
1951 node->prev->next = node;
1952 list->prev = node;
1953}
1954
1955static void fdevent_plist_remove(fdevent *node)
1956{
1957 node->prev->next = node->next;
1958 node->next->prev = node->prev;
1959 node->next = 0;
1960 node->prev = 0;
1961}
1962
1963static fdevent *fdevent_plist_dequeue(void)
1964{
1965 fdevent *list = &list_pending;
1966 fdevent *node = list->next;
1967
1968 if(node == list) return 0;
1969
1970 list->next = node->next;
1971 list->next->prev = list;
1972 node->next = 0;
1973 node->prev = 0;
1974
1975 return node;
1976}
1977
1978fdevent *fdevent_create(int fd, fd_func func, void *arg)
1979{
1980 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
1981 if(fde == 0) return 0;
1982 fdevent_install(fde, fd, func, arg);
1983 fde->state |= FDE_CREATED;
1984 return fde;
1985}
1986
1987void fdevent_destroy(fdevent *fde)
1988{
1989 if(fde == 0) return;
1990 if(!(fde->state & FDE_CREATED)) {
1991 FATAL("fde %p not created by fdevent_create()\n", fde);
1992 }
1993 fdevent_remove(fde);
1994}
1995
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001996void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001997{
1998 memset(fde, 0, sizeof(fdevent));
1999 fde->state = FDE_ACTIVE;
2000 fde->fd = fd;
2001 fde->func = func;
2002 fde->arg = arg;
2003
2004 fdevent_register(fde);
2005 dump_fde(fde, "connect");
2006 fdevent_connect(fde);
2007 fde->state |= FDE_ACTIVE;
2008}
2009
2010void fdevent_remove(fdevent *fde)
2011{
2012 if(fde->state & FDE_PENDING) {
2013 fdevent_plist_remove(fde);
2014 }
2015
2016 if(fde->state & FDE_ACTIVE) {
2017 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002018 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002019 fdevent_unregister(fde);
2020 }
2021
2022 fde->state = 0;
2023 fde->events = 0;
2024}
2025
2026
2027void fdevent_set(fdevent *fde, unsigned events)
2028{
2029 events &= FDE_EVENTMASK;
2030
2031 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2032
2033 if(fde->state & FDE_ACTIVE) {
2034 fdevent_update(fde, events);
2035 dump_fde(fde, "update");
2036 }
2037
2038 fde->state = (fde->state & FDE_STATEMASK) | events;
2039
2040 if(fde->state & FDE_PENDING) {
2041 /* if we're pending, make sure
2042 ** we don't signal an event that
2043 ** is no longer wanted.
2044 */
2045 fde->events &= (~events);
2046 if(fde->events == 0) {
2047 fdevent_plist_remove(fde);
2048 fde->state &= (~FDE_PENDING);
2049 }
2050 }
2051}
2052
2053void fdevent_add(fdevent *fde, unsigned events)
2054{
2055 fdevent_set(
2056 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2057}
2058
2059void fdevent_del(fdevent *fde, unsigned events)
2060{
2061 fdevent_set(
2062 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2063}
2064
2065void fdevent_loop()
2066{
2067 fdevent *fde;
2068
2069 for(;;) {
2070#if DEBUG
2071 fprintf(stderr,"--- ---- waiting for events\n");
2072#endif
2073 fdevent_process();
2074
2075 while((fde = fdevent_plist_dequeue())) {
2076 unsigned events = fde->events;
2077 fde->events = 0;
2078 fde->state &= (~FDE_PENDING);
2079 dump_fde(fde, "callback");
2080 fde->func(fde->fd, events, fde->arg);
2081 }
2082 }
2083}
2084
2085/** FILE EVENT HOOKS
2086 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002087
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002088static void _event_file_prepare( EventHook hook )
2089{
2090 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2091 /* we can always read/write */
2092 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2093 }
2094}
2095
2096static int _event_file_peek( EventHook hook )
2097{
2098 return (hook->wanted & (FDE_READ|FDE_WRITE));
2099}
2100
2101static void _fh_file_hook( FH f, int events, EventHook hook )
2102{
2103 hook->h = f->fh_handle;
2104 hook->prepare = _event_file_prepare;
2105 hook->peek = _event_file_peek;
2106}
2107
2108/** SOCKET EVENT HOOKS
2109 **/
2110
2111static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2112{
2113 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2114 if (hook->wanted & FDE_READ)
2115 hook->ready |= FDE_READ;
2116 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2117 hook->ready |= FDE_ERROR;
2118 }
2119 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2120 if (hook->wanted & FDE_WRITE)
2121 hook->ready |= FDE_WRITE;
2122 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2123 hook->ready |= FDE_ERROR;
2124 }
2125 if ( evts->lNetworkEvents & FD_OOB ) {
2126 if (hook->wanted & FDE_ERROR)
2127 hook->ready |= FDE_ERROR;
2128 }
2129}
2130
2131static void _event_socket_prepare( EventHook hook )
2132{
2133 WSANETWORKEVENTS evts;
2134
2135 /* look if some of the events we want already happened ? */
2136 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2137 _event_socket_verify( hook, &evts );
2138}
2139
2140static int _socket_wanted_to_flags( int wanted )
2141{
2142 int flags = 0;
2143 if (wanted & FDE_READ)
2144 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2145
2146 if (wanted & FDE_WRITE)
2147 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2148
2149 if (wanted & FDE_ERROR)
2150 flags |= FD_OOB;
2151
2152 return flags;
2153}
2154
2155static int _event_socket_start( EventHook hook )
2156{
2157 /* create an event which we're going to wait for */
2158 FH fh = hook->fh;
2159 long flags = _socket_wanted_to_flags( hook->wanted );
2160
2161 hook->h = fh->event;
2162 if (hook->h == INVALID_HANDLE_VALUE) {
2163 D( "_event_socket_start: no event for %s\n", fh->name );
2164 return 0;
2165 }
2166
2167 if ( flags != fh->mask ) {
2168 D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
2169 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
2170 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
2171 CloseHandle( hook->h );
2172 hook->h = INVALID_HANDLE_VALUE;
2173 exit(1);
2174 return 0;
2175 }
2176 fh->mask = flags;
2177 }
2178 return 1;
2179}
2180
2181static void _event_socket_stop( EventHook hook )
2182{
2183 hook->h = INVALID_HANDLE_VALUE;
2184}
2185
2186static int _event_socket_check( EventHook hook )
2187{
2188 int result = 0;
2189 FH fh = hook->fh;
2190 WSANETWORKEVENTS evts;
2191
2192 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2193 _event_socket_verify( hook, &evts );
2194 result = (hook->ready != 0);
2195 if (result) {
2196 ResetEvent( hook->h );
2197 }
2198 }
2199 D( "_event_socket_check %s returns %d\n", fh->name, result );
2200 return result;
2201}
2202
2203static int _event_socket_peek( EventHook hook )
2204{
2205 WSANETWORKEVENTS evts;
2206 FH fh = hook->fh;
2207
2208 /* look if some of the events we want already happened ? */
2209 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2210 _event_socket_verify( hook, &evts );
2211 if (hook->ready)
2212 ResetEvent( hook->h );
2213 }
2214
2215 return hook->ready != 0;
2216}
2217
2218
2219
2220static void _fh_socket_hook( FH f, int events, EventHook hook )
2221{
2222 hook->prepare = _event_socket_prepare;
2223 hook->start = _event_socket_start;
2224 hook->stop = _event_socket_stop;
2225 hook->check = _event_socket_check;
2226 hook->peek = _event_socket_peek;
2227
Spencer Low753d4852015-07-30 23:07:55 -07002228 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002229 _event_socket_start( hook );
2230}
2231
2232/** SOCKETPAIR EVENT HOOKS
2233 **/
2234
2235static void _event_socketpair_prepare( EventHook hook )
2236{
2237 FH fh = hook->fh;
2238 SocketPair pair = fh->fh_pair;
2239 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2240 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2241
2242 if (hook->wanted & FDE_READ && rbip->can_read)
2243 hook->ready |= FDE_READ;
2244
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002245 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002246 hook->ready |= FDE_WRITE;
2247 }
2248
2249 static int _event_socketpair_start( EventHook hook )
2250 {
2251 FH fh = hook->fh;
2252 SocketPair pair = fh->fh_pair;
2253 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2254 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2255
2256 if (hook->wanted == FDE_READ)
2257 hook->h = rbip->evt_read;
2258
2259 else if (hook->wanted == FDE_WRITE)
2260 hook->h = wbip->evt_write;
2261
2262 else {
2263 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
2264 return 0;
2265 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002266 D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002267 hook->fh->name, _fh_to_int(fh), hook->wanted);
2268 return 1;
2269}
2270
2271static int _event_socketpair_peek( EventHook hook )
2272{
2273 _event_socketpair_prepare( hook );
2274 return hook->ready != 0;
2275}
2276
2277static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2278{
2279 hook->prepare = _event_socketpair_prepare;
2280 hook->start = _event_socketpair_start;
2281 hook->peek = _event_socketpair_peek;
2282}
2283
2284
2285void
2286adb_sysdeps_init( void )
2287{
2288#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2289#include "mutex_list.h"
2290 InitializeCriticalSection( &_win32_lock );
2291}
2292
Spencer Lowbeb61982015-03-01 15:06:21 -08002293/**************************************************************************/
2294/**************************************************************************/
2295/***** *****/
2296/***** Console Window Terminal Emulation *****/
2297/***** *****/
2298/**************************************************************************/
2299/**************************************************************************/
2300
2301// This reads input from a Win32 console window and translates it into Unix
2302// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2303// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2304// is emulated instead of xterm because it is probably more popular than xterm:
2305// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2306// supports modern fonts, etc. It seems best to emulate the terminal that most
2307// Android developers use because they'll fix apps (the shell, etc.) to keep
2308// working with that terminal's emulation.
2309//
2310// The point of this emulation is not to be perfect or to solve all issues with
2311// console windows on Windows, but to be better than the original code which
2312// just called read() (which called ReadFile(), which called ReadConsoleA())
2313// which did not support Ctrl-C, tab completion, shell input line editing
2314// keys, server echo, and more.
2315//
2316// This implementation reconfigures the console with SetConsoleMode(), then
2317// calls ReadConsoleInput() to get raw input which it remaps to Unix
2318// terminal-style sequences which is returned via unix_read() which is used
2319// by the 'adb shell' command.
2320//
2321// Code organization:
2322//
2323// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2324// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2325// * _console_read() is the main code of the emulation.
2326
2327
2328// Read an input record from the console; one that should be processed.
2329static bool _get_interesting_input_record_uncached(const HANDLE console,
2330 INPUT_RECORD* const input_record) {
2331 for (;;) {
2332 DWORD read_count = 0;
2333 memset(input_record, 0, sizeof(*input_record));
2334 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2335 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
Spencer Low1711e012015-08-02 18:50:17 -07002336 "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002337 errno = EIO;
2338 return false;
2339 }
2340
2341 if (read_count == 0) { // should be impossible
2342 fatal("ReadConsoleInputA returned 0");
2343 }
2344
2345 if (read_count != 1) { // should be impossible
2346 fatal("ReadConsoleInputA did not return one input record");
2347 }
2348
2349 if ((input_record->EventType == KEY_EVENT) &&
2350 (input_record->Event.KeyEvent.bKeyDown)) {
2351 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2352 fatal("ReadConsoleInputA returned a key event with zero repeat"
2353 " count");
2354 }
2355
2356 // Got an interesting INPUT_RECORD, so return
2357 return true;
2358 }
2359 }
2360}
2361
2362// Cached input record (in case _console_read() is passed a buffer that doesn't
2363// have enough space to fit wRepeatCount number of key sequences). A non-zero
2364// wRepeatCount indicates that a record is cached.
2365static INPUT_RECORD _win32_input_record;
2366
2367// Get the next KEY_EVENT_RECORD that should be processed.
2368static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2369 // If nothing cached, read directly from the console until we get an
2370 // interesting record.
2371 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2372 if (!_get_interesting_input_record_uncached(console,
2373 &_win32_input_record)) {
2374 // There was an error, so make sure wRepeatCount is zero because
2375 // that signifies no cached input record.
2376 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2377 return NULL;
2378 }
2379 }
2380
2381 return &_win32_input_record.Event.KeyEvent;
2382}
2383
2384static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2385 return (control_key_state & SHIFT_PRESSED) != 0;
2386}
2387
2388static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2389 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2390}
2391
2392static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2393 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2394}
2395
2396static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2397 return (control_key_state & NUMLOCK_ON) != 0;
2398}
2399
2400static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2401 return (control_key_state & CAPSLOCK_ON) != 0;
2402}
2403
2404static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2405 return (control_key_state & ENHANCED_KEY) != 0;
2406}
2407
2408// Constants from MSDN for ToAscii().
2409static const BYTE TOASCII_KEY_OFF = 0x00;
2410static const BYTE TOASCII_KEY_DOWN = 0x80;
2411static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2412
2413// Given a key event, ignore a modifier key and return the character that was
2414// entered without the modifier. Writes to *ch and returns the number of bytes
2415// written.
2416static size_t _get_char_ignoring_modifier(char* const ch,
2417 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2418 const WORD modifier) {
2419 // If there is no character from Windows, try ignoring the specified
2420 // modifier and look for a character. Note that if AltGr is being used,
2421 // there will be a character from Windows.
2422 if (key_event->uChar.AsciiChar == '\0') {
2423 // Note that we read the control key state from the passed in argument
2424 // instead of from key_event since the argument has been normalized.
2425 if (((modifier == VK_SHIFT) &&
2426 _is_shift_pressed(control_key_state)) ||
2427 ((modifier == VK_CONTROL) &&
2428 _is_ctrl_pressed(control_key_state)) ||
2429 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2430
2431 BYTE key_state[256] = {0};
2432 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2433 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2434 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2435 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2436 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2437 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2438 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2439 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2440
2441 // cause this modifier to be ignored
2442 key_state[modifier] = TOASCII_KEY_OFF;
2443
2444 WORD translated = 0;
2445 if (ToAscii(key_event->wVirtualKeyCode,
2446 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2447 // Ignoring the modifier, we found a character.
2448 *ch = (CHAR)translated;
2449 return 1;
2450 }
2451 }
2452 }
2453
2454 // Just use whatever Windows told us originally.
2455 *ch = key_event->uChar.AsciiChar;
2456
2457 // If the character from Windows is NULL, return a size of zero.
2458 return (*ch == '\0') ? 0 : 1;
2459}
2460
2461// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2462// but taking into account the shift key. This is because for a sequence like
2463// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2464// we want to find the character ')'.
2465//
2466// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2467// because it is the default key-sequence to switch the input language.
2468// This is configurable in the Region and Language control panel.
2469static __inline__ size_t _get_non_control_char(char* const ch,
2470 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2471 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2472 VK_CONTROL);
2473}
2474
2475// Get without Alt.
2476static __inline__ size_t _get_non_alt_char(char* const ch,
2477 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2478 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2479 VK_MENU);
2480}
2481
2482// Ignore the control key, find the character from Windows, and apply any
2483// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2484// *pch and returns number of bytes written.
2485static size_t _get_control_character(char* const pch,
2486 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2487 const size_t len = _get_non_control_char(pch, key_event,
2488 control_key_state);
2489
2490 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2491 char ch = *pch;
2492 switch (ch) {
2493 case '2':
2494 case '@':
2495 case '`':
2496 ch = '\0';
2497 break;
2498 case '3':
2499 case '[':
2500 case '{':
2501 ch = '\x1b';
2502 break;
2503 case '4':
2504 case '\\':
2505 case '|':
2506 ch = '\x1c';
2507 break;
2508 case '5':
2509 case ']':
2510 case '}':
2511 ch = '\x1d';
2512 break;
2513 case '6':
2514 case '^':
2515 case '~':
2516 ch = '\x1e';
2517 break;
2518 case '7':
2519 case '-':
2520 case '_':
2521 ch = '\x1f';
2522 break;
2523 case '8':
2524 ch = '\x7f';
2525 break;
2526 case '/':
2527 if (!_is_alt_pressed(control_key_state)) {
2528 ch = '\x1f';
2529 }
2530 break;
2531 case '?':
2532 if (!_is_alt_pressed(control_key_state)) {
2533 ch = '\x7f';
2534 }
2535 break;
2536 }
2537 *pch = ch;
2538 }
2539
2540 return len;
2541}
2542
2543static DWORD _normalize_altgr_control_key_state(
2544 const KEY_EVENT_RECORD* const key_event) {
2545 DWORD control_key_state = key_event->dwControlKeyState;
2546
2547 // If we're in an AltGr situation where the AltGr key is down (depending on
2548 // the keyboard layout, that might be the physical right alt key which
2549 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2550 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2551 // a character (which indicates that there was an AltGr mapping), then act
2552 // as if alt and control are not really down for the purposes of modifiers.
2553 // This makes it so that if the user with, say, a German keyboard layout
2554 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2555 // output the key and we don't see the Alt and Ctrl keys.
2556 if (_is_ctrl_pressed(control_key_state) &&
2557 _is_alt_pressed(control_key_state)
2558 && (key_event->uChar.AsciiChar != '\0')) {
2559 // Try to remove as few bits as possible to improve our chances of
2560 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2561 // Left-Alt + Right-Ctrl + AltGr.
2562 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2563 // Remove Right-Alt.
2564 control_key_state &= ~RIGHT_ALT_PRESSED;
2565 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2566 // pressed, Left-Ctrl is almost always set, except if the user
2567 // presses Right-Ctrl, then AltGr (in that specific order) for
2568 // whatever reason. At any rate, make sure the bit is not set.
2569 control_key_state &= ~LEFT_CTRL_PRESSED;
2570 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2571 // Remove Left-Alt.
2572 control_key_state &= ~LEFT_ALT_PRESSED;
2573 // Whichever Ctrl key is down, remove it from the state. We only
2574 // remove one key, to improve our chances of detecting the
2575 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2576 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2577 // Remove Left-Ctrl.
2578 control_key_state &= ~LEFT_CTRL_PRESSED;
2579 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2580 // Remove Right-Ctrl.
2581 control_key_state &= ~RIGHT_CTRL_PRESSED;
2582 }
2583 }
2584
2585 // Note that this logic isn't 100% perfect because Windows doesn't
2586 // allow us to detect all combinations because a physical AltGr key
2587 // press shows up as two bits, plus some combinations are ambiguous
2588 // about what is actually physically pressed.
2589 }
2590
2591 return control_key_state;
2592}
2593
2594// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2595// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2596// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2597// appropriately.
2598static DWORD _normalize_keypad_control_key_state(const WORD vk,
2599 const DWORD control_key_state) {
2600 if (!_is_numlock_on(control_key_state)) {
2601 return control_key_state;
2602 }
2603 if (!_is_enhanced_key(control_key_state)) {
2604 switch (vk) {
2605 case VK_INSERT: // 0
2606 case VK_DELETE: // .
2607 case VK_END: // 1
2608 case VK_DOWN: // 2
2609 case VK_NEXT: // 3
2610 case VK_LEFT: // 4
2611 case VK_CLEAR: // 5
2612 case VK_RIGHT: // 6
2613 case VK_HOME: // 7
2614 case VK_UP: // 8
2615 case VK_PRIOR: // 9
2616 return control_key_state | SHIFT_PRESSED;
2617 }
2618 }
2619
2620 return control_key_state;
2621}
2622
2623static const char* _get_keypad_sequence(const DWORD control_key_state,
2624 const char* const normal, const char* const shifted) {
2625 if (_is_shift_pressed(control_key_state)) {
2626 // Shift is pressed and NumLock is off
2627 return shifted;
2628 } else {
2629 // Shift is not pressed and NumLock is off, or,
2630 // Shift is pressed and NumLock is on, in which case we want the
2631 // NumLock and Shift to neutralize each other, thus, we want the normal
2632 // sequence.
2633 return normal;
2634 }
2635 // If Shift is not pressed and NumLock is on, a different virtual key code
2636 // is returned by Windows, which can be taken care of by a different case
2637 // statement in _console_read().
2638}
2639
2640// Write sequence to buf and return the number of bytes written.
2641static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2642 DWORD control_key_state, const char* const normal) {
2643 // Copy the base sequence into buf.
2644 const size_t len = strlen(normal);
2645 memcpy(buf, normal, len);
2646
2647 int code = 0;
2648
2649 control_key_state = _normalize_keypad_control_key_state(vk,
2650 control_key_state);
2651
2652 if (_is_shift_pressed(control_key_state)) {
2653 code |= 0x1;
2654 }
2655 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2656 code |= 0x2;
2657 }
2658 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2659 code |= 0x4;
2660 }
2661 // If some modifier was held down, then we need to insert the modifier code
2662 if (code != 0) {
2663 if (len == 0) {
2664 // Should be impossible because caller should pass a string of
2665 // non-zero length.
2666 return 0;
2667 }
2668 size_t index = len - 1;
2669 const char lastChar = buf[index];
2670 if (lastChar != '~') {
2671 buf[index++] = '1';
2672 }
2673 buf[index++] = ';'; // modifier separator
2674 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2675 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2676 buf[index++] = '1' + code;
2677 buf[index++] = lastChar; // move ~ (or other last char) to the end
2678 return index;
2679 }
2680 return len;
2681}
2682
2683// Write sequence to buf and return the number of bytes written.
2684static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2685 const DWORD control_key_state, const char* const normal,
2686 const char shifted) {
2687 if (_is_shift_pressed(control_key_state)) {
2688 // Shift is pressed and NumLock is off
2689 if (shifted != '\0') {
2690 buf[0] = shifted;
2691 return sizeof(buf[0]);
2692 } else {
2693 return 0;
2694 }
2695 } else {
2696 // Shift is not pressed and NumLock is off, or,
2697 // Shift is pressed and NumLock is on, in which case we want the
2698 // NumLock and Shift to neutralize each other, thus, we want the normal
2699 // sequence.
2700 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2701 }
2702 // If Shift is not pressed and NumLock is on, a different virtual key code
2703 // is returned by Windows, which can be taken care of by a different case
2704 // statement in _console_read().
2705}
2706
2707// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2708// Standard German. Figure this out at runtime so we know what to output for
2709// Shift-VK_DELETE.
2710static char _get_decimal_char() {
2711 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2712}
2713
2714// Prefix the len bytes in buf with the escape character, and then return the
2715// new buffer length.
2716size_t _escape_prefix(char* const buf, const size_t len) {
2717 // If nothing to prefix, don't do anything. We might be called with
2718 // len == 0, if alt was held down with a dead key which produced nothing.
2719 if (len == 0) {
2720 return 0;
2721 }
2722
2723 memmove(&buf[1], buf, len);
2724 buf[0] = '\x1b';
2725 return len + 1;
2726}
2727
2728// Writes to buffer buf (of length len), returning number of bytes written or
2729// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2730// (as far as I can tell).
2731static int _console_read(const HANDLE console, void* buf, size_t len) {
2732 for (;;) {
2733 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2734 if (key_event == NULL) {
2735 return -1;
2736 }
2737
2738 const WORD vk = key_event->wVirtualKeyCode;
2739 const CHAR ch = key_event->uChar.AsciiChar;
2740 const DWORD control_key_state = _normalize_altgr_control_key_state(
2741 key_event);
2742
2743 // The following emulation code should write the output sequence to
2744 // either seqstr or to seqbuf and seqbuflen.
2745 const char* seqstr = NULL; // NULL terminated C-string
2746 // Enough space for max sequence string below, plus modifiers and/or
2747 // escape prefix.
2748 char seqbuf[16];
2749 size_t seqbuflen = 0; // Space used in seqbuf.
2750
2751#define MATCH(vk, normal) \
2752 case (vk): \
2753 { \
2754 seqstr = (normal); \
2755 } \
2756 break;
2757
2758 // Modifier keys should affect the output sequence.
2759#define MATCH_MODIFIER(vk, normal) \
2760 case (vk): \
2761 { \
2762 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2763 control_key_state, (normal)); \
2764 } \
2765 break;
2766
2767 // The shift key should affect the output sequence.
2768#define MATCH_KEYPAD(vk, normal, shifted) \
2769 case (vk): \
2770 { \
2771 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2772 (shifted)); \
2773 } \
2774 break;
2775
2776 // The shift key and other modifier keys should affect the output
2777 // sequence.
2778#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2779 case (vk): \
2780 { \
2781 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2782 control_key_state, (normal), (shifted)); \
2783 } \
2784 break;
2785
2786#define ESC "\x1b"
2787#define CSI ESC "["
2788#define SS3 ESC "O"
2789
2790 // Only support normal mode, not application mode.
2791
2792 // Enhanced keys:
2793 // * 6-pack: insert, delete, home, end, page up, page down
2794 // * cursor keys: up, down, right, left
2795 // * keypad: divide, enter
2796 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2797 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2798 if (_is_enhanced_key(control_key_state)) {
2799 switch (vk) {
2800 case VK_RETURN: // Enter key on keypad
2801 if (_is_ctrl_pressed(control_key_state)) {
2802 seqstr = "\n";
2803 } else {
2804 seqstr = "\r";
2805 }
2806 break;
2807
2808 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2809 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2810
2811 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2812 // will be fixed soon to match xterm which sends CSI "F" and
2813 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2814 MATCH(VK_END, CSI "F");
2815 MATCH(VK_HOME, CSI "H");
2816
2817 MATCH_MODIFIER(VK_LEFT, CSI "D");
2818 MATCH_MODIFIER(VK_UP, CSI "A");
2819 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2820 MATCH_MODIFIER(VK_DOWN, CSI "B");
2821
2822 MATCH_MODIFIER(VK_INSERT, CSI "2~");
2823 MATCH_MODIFIER(VK_DELETE, CSI "3~");
2824
2825 MATCH(VK_DIVIDE, "/");
2826 }
2827 } else { // Non-enhanced keys:
2828 switch (vk) {
2829 case VK_BACK: // backspace
2830 if (_is_alt_pressed(control_key_state)) {
2831 seqstr = ESC "\x7f";
2832 } else {
2833 seqstr = "\x7f";
2834 }
2835 break;
2836
2837 case VK_TAB:
2838 if (_is_shift_pressed(control_key_state)) {
2839 seqstr = CSI "Z";
2840 } else {
2841 seqstr = "\t";
2842 }
2843 break;
2844
2845 // Number 5 key in keypad when NumLock is off, or if NumLock is
2846 // on and Shift is down.
2847 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2848
2849 case VK_RETURN: // Enter key on main keyboard
2850 if (_is_alt_pressed(control_key_state)) {
2851 seqstr = ESC "\n";
2852 } else if (_is_ctrl_pressed(control_key_state)) {
2853 seqstr = "\n";
2854 } else {
2855 seqstr = "\r";
2856 }
2857 break;
2858
2859 // VK_ESCAPE: Don't do any special handling. The OS uses many
2860 // of the sequences with Escape and many of the remaining
2861 // sequences don't produce bKeyDown messages, only !bKeyDown
2862 // for whatever reason.
2863
2864 case VK_SPACE:
2865 if (_is_alt_pressed(control_key_state)) {
2866 seqstr = ESC " ";
2867 } else if (_is_ctrl_pressed(control_key_state)) {
2868 seqbuf[0] = '\0'; // NULL char
2869 seqbuflen = 1;
2870 } else {
2871 seqstr = " ";
2872 }
2873 break;
2874
2875 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2876 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
2877
2878 MATCH_KEYPAD(VK_END, CSI "4~", "1");
2879 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2880
2881 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
2882 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
2883 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2884 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
2885
2886 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2887 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2888 _get_decimal_char());
2889
2890 case 0x30: // 0
2891 case 0x31: // 1
2892 case 0x39: // 9
2893 case VK_OEM_1: // ;:
2894 case VK_OEM_PLUS: // =+
2895 case VK_OEM_COMMA: // ,<
2896 case VK_OEM_PERIOD: // .>
2897 case VK_OEM_7: // '"
2898 case VK_OEM_102: // depends on keyboard, could be <> or \|
2899 case VK_OEM_2: // /?
2900 case VK_OEM_3: // `~
2901 case VK_OEM_4: // [{
2902 case VK_OEM_5: // \|
2903 case VK_OEM_6: // ]}
2904 {
2905 seqbuflen = _get_control_character(seqbuf, key_event,
2906 control_key_state);
2907
2908 if (_is_alt_pressed(control_key_state)) {
2909 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2910 }
2911 }
2912 break;
2913
2914 case 0x32: // 2
2915 case 0x36: // 6
2916 case VK_OEM_MINUS: // -_
2917 {
2918 seqbuflen = _get_control_character(seqbuf, key_event,
2919 control_key_state);
2920
2921 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2922 // prefix with escape.
2923 if (_is_alt_pressed(control_key_state) &&
2924 !(_is_ctrl_pressed(control_key_state) &&
2925 !_is_shift_pressed(control_key_state))) {
2926 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2927 }
2928 }
2929 break;
2930
2931 case 0x33: // 3
2932 case 0x34: // 4
2933 case 0x35: // 5
2934 case 0x37: // 7
2935 case 0x38: // 8
2936 {
2937 seqbuflen = _get_control_character(seqbuf, key_event,
2938 control_key_state);
2939
2940 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2941 // prefix with escape.
2942 if (_is_alt_pressed(control_key_state) &&
2943 !(_is_ctrl_pressed(control_key_state) &&
2944 !_is_shift_pressed(control_key_state))) {
2945 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2946 }
2947 }
2948 break;
2949
2950 case 0x41: // a
2951 case 0x42: // b
2952 case 0x43: // c
2953 case 0x44: // d
2954 case 0x45: // e
2955 case 0x46: // f
2956 case 0x47: // g
2957 case 0x48: // h
2958 case 0x49: // i
2959 case 0x4a: // j
2960 case 0x4b: // k
2961 case 0x4c: // l
2962 case 0x4d: // m
2963 case 0x4e: // n
2964 case 0x4f: // o
2965 case 0x50: // p
2966 case 0x51: // q
2967 case 0x52: // r
2968 case 0x53: // s
2969 case 0x54: // t
2970 case 0x55: // u
2971 case 0x56: // v
2972 case 0x57: // w
2973 case 0x58: // x
2974 case 0x59: // y
2975 case 0x5a: // z
2976 {
2977 seqbuflen = _get_non_alt_char(seqbuf, key_event,
2978 control_key_state);
2979
2980 // If Alt is pressed, then prefix with escape.
2981 if (_is_alt_pressed(control_key_state)) {
2982 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2983 }
2984 }
2985 break;
2986
2987 // These virtual key codes are generated by the keys on the
2988 // keypad *when NumLock is on* and *Shift is up*.
2989 MATCH(VK_NUMPAD0, "0");
2990 MATCH(VK_NUMPAD1, "1");
2991 MATCH(VK_NUMPAD2, "2");
2992 MATCH(VK_NUMPAD3, "3");
2993 MATCH(VK_NUMPAD4, "4");
2994 MATCH(VK_NUMPAD5, "5");
2995 MATCH(VK_NUMPAD6, "6");
2996 MATCH(VK_NUMPAD7, "7");
2997 MATCH(VK_NUMPAD8, "8");
2998 MATCH(VK_NUMPAD9, "9");
2999
3000 MATCH(VK_MULTIPLY, "*");
3001 MATCH(VK_ADD, "+");
3002 MATCH(VK_SUBTRACT, "-");
3003 // VK_DECIMAL is generated by the . key on the keypad *when
3004 // NumLock is on* and *Shift is up* and the sequence is not
3005 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3006 // Windows Security screen to come up).
3007 case VK_DECIMAL:
3008 // U.S. English uses '.', Germany German uses ','.
3009 seqbuflen = _get_non_control_char(seqbuf, key_event,
3010 control_key_state);
3011 break;
3012
3013 MATCH_MODIFIER(VK_F1, SS3 "P");
3014 MATCH_MODIFIER(VK_F2, SS3 "Q");
3015 MATCH_MODIFIER(VK_F3, SS3 "R");
3016 MATCH_MODIFIER(VK_F4, SS3 "S");
3017 MATCH_MODIFIER(VK_F5, CSI "15~");
3018 MATCH_MODIFIER(VK_F6, CSI "17~");
3019 MATCH_MODIFIER(VK_F7, CSI "18~");
3020 MATCH_MODIFIER(VK_F8, CSI "19~");
3021 MATCH_MODIFIER(VK_F9, CSI "20~");
3022 MATCH_MODIFIER(VK_F10, CSI "21~");
3023 MATCH_MODIFIER(VK_F11, CSI "23~");
3024 MATCH_MODIFIER(VK_F12, CSI "24~");
3025
3026 MATCH_MODIFIER(VK_F13, CSI "25~");
3027 MATCH_MODIFIER(VK_F14, CSI "26~");
3028 MATCH_MODIFIER(VK_F15, CSI "28~");
3029 MATCH_MODIFIER(VK_F16, CSI "29~");
3030 MATCH_MODIFIER(VK_F17, CSI "31~");
3031 MATCH_MODIFIER(VK_F18, CSI "32~");
3032 MATCH_MODIFIER(VK_F19, CSI "33~");
3033 MATCH_MODIFIER(VK_F20, CSI "34~");
3034
3035 // MATCH_MODIFIER(VK_F21, ???);
3036 // MATCH_MODIFIER(VK_F22, ???);
3037 // MATCH_MODIFIER(VK_F23, ???);
3038 // MATCH_MODIFIER(VK_F24, ???);
3039 }
3040 }
3041
3042#undef MATCH
3043#undef MATCH_MODIFIER
3044#undef MATCH_KEYPAD
3045#undef MATCH_MODIFIER_KEYPAD
3046#undef ESC
3047#undef CSI
3048#undef SS3
3049
3050 const char* out;
3051 size_t outlen;
3052
3053 // Check for output in any of:
3054 // * seqstr is set (and strlen can be used to determine the length).
3055 // * seqbuf and seqbuflen are set
3056 // Fallback to ch from Windows.
3057 if (seqstr != NULL) {
3058 out = seqstr;
3059 outlen = strlen(seqstr);
3060 } else if (seqbuflen > 0) {
3061 out = seqbuf;
3062 outlen = seqbuflen;
3063 } else if (ch != '\0') {
3064 // Use whatever Windows told us it is.
3065 seqbuf[0] = ch;
3066 seqbuflen = 1;
3067 out = seqbuf;
3068 outlen = seqbuflen;
3069 } else {
3070 // No special handling for the virtual key code and Windows isn't
3071 // telling us a character code, then we don't know how to translate
3072 // the key press.
3073 //
3074 // Consume the input and 'continue' to cause us to get a new key
3075 // event.
3076 D("_console_read: unknown virtual key code: %d, enhanced: %s\n",
3077 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3078 key_event->wRepeatCount = 0;
3079 continue;
3080 }
3081
3082 int bytesRead = 0;
3083
3084 // put output wRepeatCount times into buf/len
3085 while (key_event->wRepeatCount > 0) {
3086 if (len >= outlen) {
3087 // Write to buf/len
3088 memcpy(buf, out, outlen);
3089 buf = (void*)((char*)buf + outlen);
3090 len -= outlen;
3091 bytesRead += outlen;
3092
3093 // consume the input
3094 --key_event->wRepeatCount;
3095 } else {
3096 // Not enough space, so just leave it in _win32_input_record
3097 // for a subsequent retrieval.
3098 if (bytesRead == 0) {
3099 // We didn't write anything because there wasn't enough
3100 // space to even write one sequence. This should never
3101 // happen if the caller uses sensible buffer sizes
3102 // (i.e. >= maximum sequence length which is probably a
3103 // few bytes long).
3104 D("_console_read: no buffer space to write one sequence; "
3105 "buffer: %ld, sequence: %ld\n", (long)len,
3106 (long)outlen);
3107 errno = ENOMEM;
3108 return -1;
3109 } else {
3110 // Stop trying to write to buf/len, just return whatever
3111 // we wrote so far.
3112 break;
3113 }
3114 }
3115 }
3116
3117 return bytesRead;
3118 }
3119}
3120
3121static DWORD _old_console_mode; // previous GetConsoleMode() result
3122static HANDLE _console_handle; // when set, console mode should be restored
3123
3124void stdin_raw_init(const int fd) {
3125 if (STDIN_FILENO == fd) {
3126 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3127 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3128 return;
3129 }
3130
3131 if (GetFileType(in) != FILE_TYPE_CHAR) {
3132 // stdin might be a file or pipe.
3133 return;
3134 }
3135
3136 if (!GetConsoleMode(in, &_old_console_mode)) {
3137 // If GetConsoleMode() fails, stdin is probably is not a console.
3138 return;
3139 }
3140
3141 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3142 // calling the process Ctrl-C routine (configured by
3143 // SetConsoleCtrlHandler()).
3144 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3145 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3146 // flag also seems necessary to have proper line-ending processing.
3147 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3148 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3149 // This really should not fail.
Spencer Low1711e012015-08-02 18:50:17 -07003150 D("stdin_raw_init: SetConsoleMode() failed: %s\n",
3151 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003152 }
3153
3154 // Once this is set, it means that stdin has been configured for
3155 // reading from and that the old console mode should be restored later.
3156 _console_handle = in;
3157
3158 // Note that we don't need to configure C Runtime line-ending
3159 // translation because _console_read() does not call the C Runtime to
3160 // read from the console.
3161 }
3162}
3163
3164void stdin_raw_restore(const int fd) {
3165 if (STDIN_FILENO == fd) {
3166 if (_console_handle != NULL) {
3167 const HANDLE in = _console_handle;
3168 _console_handle = NULL; // clear state
3169
3170 if (!SetConsoleMode(in, _old_console_mode)) {
3171 // This really should not fail.
Spencer Low1711e012015-08-02 18:50:17 -07003172 D("stdin_raw_restore: SetConsoleMode() failed: %s\n",
3173 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003174 }
3175 }
3176 }
3177}
3178
Spencer Low3a2421b2015-05-22 20:09:06 -07003179// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003180int unix_read(int fd, void* buf, size_t len) {
3181 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3182 // If it is a request to read from stdin, and stdin_raw_init() has been
3183 // called, and it successfully configured the console, then read from
3184 // the console using Win32 console APIs and partially emulate a unix
3185 // terminal.
3186 return _console_read(_console_handle, buf, len);
3187 } else {
3188 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003189 // can do LF/CR translation (which is overridable with _setmode()).
3190 // Undefine the macro that is set in sysdeps.h which bans calls to
3191 // plain read() in favor of unix_read() or adb_read().
3192#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003193#undef read
3194 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003195#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003196 }
3197}
Spencer Low6815c072015-05-11 01:08:48 -07003198
3199/**************************************************************************/
3200/**************************************************************************/
3201/***** *****/
3202/***** Unicode support *****/
3203/***** *****/
3204/**************************************************************************/
3205/**************************************************************************/
3206
3207// This implements support for using files with Unicode filenames and for
3208// outputting Unicode text to a Win32 console window. This is inspired from
3209// http://utf8everywhere.org/.
3210//
3211// Background
3212// ----------
3213//
3214// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3215// filenames to APIs such as open(). This works because filenames are largely
3216// opaque 'cookies' (perhaps excluding path separators).
3217//
3218// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3219// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3220// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3221// CreateFile() API is really just a macro that adds the W/A based on whether
3222// the UNICODE preprocessor symbol is defined).
3223//
3224// Options
3225// -------
3226//
3227// Thus, to write a portable program, there are a few options:
3228//
3229// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3230// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3231// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3232// open() API.
3233//
3234// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3235// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3236// potentially touching a lot of code.
3237//
3238// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3239// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3240// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3241// or C Runtime API.
3242//
3243// The Choice
3244// ----------
3245//
3246// The code below chooses option 3, the UTF-8 everywhere strategy. It
3247// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3248// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3249// args that are passed to main() at the beginning of program startup. We also
3250// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3251// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3252//
3253// Unicode console output
3254// ----------------------
3255//
3256// The way to output Unicode to a Win32 console window is to call
3257// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003258// such as Lucida Console or Consolas, and in the case of East Asian languages
3259// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3260// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3261// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003262//
3263// The problem is getting the C Runtime to make fprintf and related APIs call
3264// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3265// promising, but the various modes have issues:
3266//
3267// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3268// UTF-16 do not display properly.
3269// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3270// totally wrong.
3271// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3272// handler to be called (upon a later I/O call), aborting the process.
3273// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3274// to output nothing.
3275//
3276// So the only solution is to write our own adb_fprintf() that converts UTF-8
3277// to UTF-16 and then calls WriteConsoleW().
3278
3279
3280// Function prototype because attributes cannot be placed on func definitions.
3281static void _widen_fatal(const char *fmt, ...)
3282 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3283
3284// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3285// called from those functions.
3286static void _widen_fatal(const char *fmt, ...) {
3287 va_list ap;
3288 va_start(ap, fmt);
3289 // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3290 // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3291 // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3292 // By directly calling real C Runtime APIs that don't properly output
3293 // Unicode, but will be able to get a comprehendible message out. To do
3294 // this, make sure we don't call (v)fprintf macros by undefining them.
3295#pragma push_macro("fprintf")
3296#pragma push_macro("vfprintf")
3297#undef fprintf
3298#undef vfprintf
3299 fprintf(stderr, "error: ");
3300 vfprintf(stderr, fmt, ap);
3301 fprintf(stderr, "\n");
3302#pragma pop_macro("vfprintf")
3303#pragma pop_macro("fprintf")
3304 va_end(ap);
3305 exit(-1);
3306}
3307
3308// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3309// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3310
3311// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3312// string. Any other size specifies the number of chars to convert, excluding
3313// any NULL terminator (if you're passing an explicit size, you probably don't
3314// have a NULL terminated string in the first place).
3315std::wstring widen(const char* utf8, const int size) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003316 // Note: Do not call SystemErrorCodeToString() from widen() because
3317 // SystemErrorCodeToString() calls narrow() which may call fatal() which
3318 // calls adb_vfprintf() which calls widen(), potentially causing infinite
3319 // recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003320 const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3321 NULL, 0);
3322 if (chars_to_convert <= 0) {
3323 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3324 _widen_fatal("MultiByteToWideChar failed counting: %d, "
3325 "GetLastError: %lu", chars_to_convert, GetLastError());
3326 }
3327
3328 std::wstring utf16;
3329 size_t chars_to_allocate = chars_to_convert;
3330 if (size == -1) {
3331 // chars_to_convert includes a NULL terminator, so subtract space
3332 // for that because resize() includes that itself.
3333 --chars_to_allocate;
3334 }
3335 utf16.resize(chars_to_allocate);
3336
3337 // This uses &string[0] to get write-access to the entire string buffer
3338 // which may be assuming that the chars are all contiguous, but it seems
3339 // to work and saves us the hassle of using a temporary
3340 // std::vector<wchar_t>.
3341 const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3342 chars_to_convert);
3343 if (result != chars_to_convert) {
3344 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3345 _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3346 "GetLastError: %lu", result, GetLastError());
3347 }
3348
3349 // If a size was passed in (size != -1), then the string is NULL terminated
3350 // by a NULL char that was written by std::string::resize(). If size == -1,
3351 // then MultiByteToWideChar() read a NULL terminator from the original
3352 // string and converted it to a NULL UTF-16 char in the output.
3353
3354 return utf16;
3355}
3356
3357// Convert a NULL terminated string from UTF-8 to UTF-16.
3358std::wstring widen(const char* utf8) {
3359 // Pass -1 to let widen() determine the string length.
3360 return widen(utf8, -1);
3361}
3362
3363// Convert from UTF-8 to UTF-16.
3364std::wstring widen(const std::string& utf8) {
3365 return widen(utf8.c_str(), utf8.length());
3366}
3367
3368// Convert from UTF-16 to UTF-8.
3369std::string narrow(const std::wstring& utf16) {
3370 return narrow(utf16.c_str());
3371}
3372
3373// Convert from UTF-16 to UTF-8.
3374std::string narrow(const wchar_t* utf16) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003375 // Note: Do not call SystemErrorCodeToString() from narrow() because
Elliott Hughes1ba53092015-08-03 16:26:13 -07003376 // SystemErrorCodeToString() calls narrow() and we don't want potential
Spencer Lowcc467f12015-08-02 18:13:54 -07003377 // infinite recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003378 const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3379 0, NULL, NULL);
3380 if (chars_required <= 0) {
3381 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003382 fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003383 chars_required, GetLastError());
3384 }
3385
3386 std::string utf8;
3387 // Subtract space for the NULL terminator because resize() includes
3388 // that itself. Note that this could potentially throw a std::bad_alloc
3389 // exception.
3390 utf8.resize(chars_required - 1);
3391
3392 // This uses &string[0] to get write-access to the entire string buffer
3393 // which may be assuming that the chars are all contiguous, but it seems
3394 // to work and saves us the hassle of using a temporary
3395 // std::vector<char>.
3396 const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3397 chars_required, NULL, NULL);
3398 if (result != chars_required) {
3399 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003400 fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003401 result, GetLastError());
3402 }
3403
3404 return utf8;
3405}
3406
3407// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3408// be passed to main().
3409NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3410 narrow_args = new char*[argc + 1];
3411
3412 for (int i = 0; i < argc; ++i) {
3413 narrow_args[i] = strdup(narrow(argv[i]).c_str());
3414 }
3415 narrow_args[argc] = nullptr; // terminate
3416}
3417
3418NarrowArgs::~NarrowArgs() {
3419 if (narrow_args != nullptr) {
3420 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3421 free(*argp);
3422 }
3423 delete[] narrow_args;
3424 narrow_args = nullptr;
3425 }
3426}
3427
3428int unix_open(const char* path, int options, ...) {
3429 if ((options & O_CREAT) == 0) {
3430 return _wopen(widen(path).c_str(), options);
3431 } else {
3432 int mode;
3433 va_list args;
3434 va_start(args, options);
3435 mode = va_arg(args, int);
3436 va_end(args);
3437 return _wopen(widen(path).c_str(), options, mode);
3438 }
3439}
3440
3441// Version of stat() that takes a UTF-8 path.
3442int adb_stat(const char* f, struct adb_stat* s) {
3443#pragma push_macro("wstat")
3444// This definition of wstat seems to be missing from <sys/stat.h>.
3445#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3446#ifdef _USE_32BIT_TIME_T
3447#define wstat _wstat32i64
3448#else
3449#define wstat _wstat64
3450#endif
3451#else
3452// <sys/stat.h> has a function prototype for wstat() that should be available.
3453#endif
3454
3455 return wstat(widen(f).c_str(), s);
3456
3457#pragma pop_macro("wstat")
3458}
3459
3460// Version of opendir() that takes a UTF-8 path.
3461DIR* adb_opendir(const char* name) {
3462 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3463 // the fields, but right now all the callers treat the structure as
3464 // opaque.
3465 return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3466}
3467
3468// Version of readdir() that returns UTF-8 paths.
3469struct dirent* adb_readdir(DIR* dir) {
3470 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3471 struct _wdirent* const went = _wreaddir(wdir);
3472 if (went == nullptr) {
3473 return nullptr;
3474 }
3475 // Convert from UTF-16 to UTF-8.
3476 const std::string name_utf8(narrow(went->d_name));
3477
3478 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3479 // space for UTF-16 wchar_t's) with UTF-8 char's.
3480 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3481
3482 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3483 // Name too big to fit in existing buffer.
3484 errno = ENOMEM;
3485 return nullptr;
3486 }
3487
3488 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3489 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3490 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3491 // bigger than the caller expects because they expect a dirent structure
3492 // which has a smaller d_name field. Ignore this since the caller should be
3493 // resilient.
3494
3495 // Rewrite the UTF-16 d_name field to UTF-8.
3496 strcpy(ent->d_name, name_utf8.c_str());
3497
3498 return ent;
3499}
3500
3501// Version of closedir() to go with our version of adb_opendir().
3502int adb_closedir(DIR* dir) {
3503 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3504}
3505
3506// Version of unlink() that takes a UTF-8 path.
3507int adb_unlink(const char* path) {
3508 const std::wstring wpath(widen(path));
3509
3510 int rc = _wunlink(wpath.c_str());
3511
3512 if (rc == -1 && errno == EACCES) {
3513 /* unlink returns EACCES when the file is read-only, so we first */
3514 /* try to make it writable, then unlink again... */
3515 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3516 if (rc == 0)
3517 rc = _wunlink(wpath.c_str());
3518 }
3519 return rc;
3520}
3521
3522// Version of mkdir() that takes a UTF-8 path.
3523int adb_mkdir(const std::string& path, int mode) {
3524 return _wmkdir(widen(path.c_str()).c_str());
3525}
3526
3527// Version of utime() that takes a UTF-8 path.
3528int adb_utime(const char* path, struct utimbuf* u) {
3529 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3530 "utimbuf and _utimbuf should be the same size because they both "
3531 "contain the same types, namely time_t");
3532 return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3533}
3534
3535// Version of chmod() that takes a UTF-8 path.
3536int adb_chmod(const char* path, int mode) {
3537 return _wchmod(widen(path).c_str(), mode);
3538}
3539
3540// Internal function to get a Win32 console HANDLE from a C Runtime FILE*.
3541static HANDLE _get_console_handle(FILE* const stream) {
3542 // Get a C Runtime file descriptor number from the FILE* structure.
3543 const int fd = fileno(stream);
3544 if (fd < 0) {
3545 return NULL;
3546 }
3547
3548 // If it is not a "character device", it is probably a file and not a
3549 // console. Do this check early because it is probably cheap. Still do more
3550 // checks after this since there are devices that pass this test, but are
3551 // not a console, such as NUL, the Windows /dev/null equivalent (I think).
3552 if (!isatty(fd)) {
3553 return NULL;
3554 }
3555
3556 // Given a C Runtime file descriptor number, get the underlying OS
3557 // file handle.
3558 const intptr_t osfh = _get_osfhandle(fd);
3559 if (osfh == -1) {
3560 return NULL;
3561 }
3562
3563 const HANDLE h = reinterpret_cast<const HANDLE>(osfh);
3564
3565 DWORD old_mode = 0;
3566 if (!GetConsoleMode(h, &old_mode)) {
3567 return NULL;
3568 }
3569
3570 // If GetConsoleMode() was successful, assume this is a console.
3571 return h;
3572}
3573
3574// Internal helper function to write UTF-8 bytes to a console. Returns -1
3575// on error.
3576static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3577 HANDLE console) {
3578 // Convert from UTF-8 to UTF-16.
3579 // This could throw std::bad_alloc.
3580 const std::wstring output(widen(buf, size));
3581
3582 // Note that this does not do \n => \r\n translation because that
3583 // doesn't seem necessary for the Windows console. For the Windows
3584 // console \r moves to the beginning of the line and \n moves to a new
3585 // line.
3586
3587 // Flush any stream buffering so that our output is afterwards which
3588 // makes sense because our call is afterwards.
3589 (void)fflush(stream);
3590
3591 // Write UTF-16 to the console.
3592 DWORD written = 0;
3593 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3594 NULL)) {
3595 errno = EIO;
3596 return -1;
3597 }
3598
3599 // This is the number of UTF-16 chars written, which might be different
3600 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3601 // get this count correct.
3602 return written;
3603}
3604
3605// Function prototype because attributes cannot be placed on func definitions.
3606static int _console_vfprintf(const HANDLE console, FILE* stream,
3607 const char *format, va_list ap)
3608 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3609
3610// Internal function to format a UTF-8 string and write it to a Win32 console.
3611// Returns -1 on error.
3612static int _console_vfprintf(const HANDLE console, FILE* stream,
3613 const char *format, va_list ap) {
3614 std::string output_utf8;
3615
3616 // Format the string.
3617 // This could throw std::bad_alloc.
3618 android::base::StringAppendV(&output_utf8, format, ap);
3619
3620 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3621 stream, console);
3622}
3623
3624// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3625// Windows console.
3626int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3627 const HANDLE console = _get_console_handle(stream);
3628
3629 // If there is an associated Win32 console, write to it specially,
3630 // otherwise defer to the regular C Runtime, passing it UTF-8.
3631 if (console != NULL) {
3632 return _console_vfprintf(console, stream, format, ap);
3633 } else {
3634 // If vfprintf is a macro, undefine it, so we can call the real
3635 // C Runtime API.
3636#pragma push_macro("vfprintf")
3637#undef vfprintf
3638 return vfprintf(stream, format, ap);
3639#pragma pop_macro("vfprintf")
3640 }
3641}
3642
3643// Version of fprintf() that takes UTF-8 and can write Unicode to a
3644// Windows console.
3645int adb_fprintf(FILE *stream, const char *format, ...) {
3646 va_list ap;
3647 va_start(ap, format);
3648 const int result = adb_vfprintf(stream, format, ap);
3649 va_end(ap);
3650
3651 return result;
3652}
3653
3654// Version of printf() that takes UTF-8 and can write Unicode to a
3655// Windows console.
3656int adb_printf(const char *format, ...) {
3657 va_list ap;
3658 va_start(ap, format);
3659 const int result = adb_vfprintf(stdout, format, ap);
3660 va_end(ap);
3661
3662 return result;
3663}
3664
3665// Version of fputs() that takes UTF-8 and can write Unicode to a
3666// Windows console.
3667int adb_fputs(const char* buf, FILE* stream) {
3668 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3669 // which fputs (and hence adb_fputs) should return on error.
3670 return adb_fprintf(stream, "%s", buf);
3671}
3672
3673// Version of fputc() that takes UTF-8 and can write Unicode to a
3674// Windows console.
3675int adb_fputc(int ch, FILE* stream) {
3676 const int result = adb_fprintf(stream, "%c", ch);
3677 if (result <= 0) {
3678 // If there was an error, or if nothing was printed (which should be an
3679 // error), return an error, which fprintf signifies with EOF.
3680 return EOF;
3681 }
3682 // For success, fputc returns the char, cast to unsigned char, then to int.
3683 return static_cast<unsigned char>(ch);
3684}
3685
3686// Internal function to write UTF-8 to a Win32 console. Returns the number of
3687// items (of length size) written. On error, returns a short item count or 0.
3688static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3689 FILE* stream, HANDLE console) {
3690 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3691 // if we're passed only some of the bytes of a character (for example, from
3692 // the network socket for adb shell), we won't be able to convert the char
3693 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3694 // right.
3695 //
3696 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3697 //
3698 // For now we ignore this problem because the alternative is that we'd have
3699 // to parse UTF-8 and buffer things up (doable). At least this is better
3700 // than what we had before -- always incorrect multi-byte UTF-8 output.
3701 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3702 size * nmemb, stream, console);
3703 if (result == -1) {
3704 return 0;
3705 }
3706 return result / size;
3707}
3708
3709// Version of fwrite() that takes UTF-8 and can write Unicode to a
3710// Windows console.
3711size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3712 const HANDLE console = _get_console_handle(stream);
3713
3714 // If there is an associated Win32 console, write to it specially,
3715 // otherwise defer to the regular C Runtime, passing it UTF-8.
3716 if (console != NULL) {
3717 return _console_fwrite(ptr, size, nmemb, stream, console);
3718 } else {
3719 // If fwrite is a macro, undefine it, so we can call the real
3720 // C Runtime API.
3721#pragma push_macro("fwrite")
3722#undef fwrite
3723 return fwrite(ptr, size, nmemb, stream);
3724#pragma pop_macro("fwrite")
3725 }
3726}
3727
3728// Version of fopen() that takes a UTF-8 filename and can access a file with
3729// a Unicode filename.
3730FILE* adb_fopen(const char* f, const char* m) {
3731 return _wfopen(widen(f).c_str(), widen(m).c_str());
3732}
3733
3734// Shadow UTF-8 environment variable name/value pairs that are created from
3735// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003736// currently updated if putenv, setenv, unsetenv are called. Note that no
3737// thread synchronization is done, but we're called early enough in
3738// single-threaded startup that things work ok.
Spencer Low6815c072015-05-11 01:08:48 -07003739static std::unordered_map<std::string, char*> g_environ_utf8;
3740
3741// Make sure that shadow UTF-8 environment variables are setup.
3742static void _ensure_env_setup() {
3743 // If some name/value pairs exist, then we've already done the setup below.
3744 if (g_environ_utf8.size() != 0) {
3745 return;
3746 }
3747
3748 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3749 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3750 // to use the D() macro here because that tracing only works if the
3751 // ADB_TRACE environment variable is setup, but that env var can't be read
3752 // until this code completes.
3753 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3754 wchar_t* const equal = wcschr(*env, L'=');
3755 if (equal == nullptr) {
3756 // Malformed environment variable with no equal sign. Shouldn't
3757 // really happen, but we should be resilient to this.
3758 continue;
3759 }
3760
3761 const std::string name_utf8(narrow(std::wstring(*env, equal - *env)));
3762 char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3763
3764 // Overwrite any duplicate name, but there shouldn't be a dup in the
3765 // first place.
3766 g_environ_utf8[name_utf8] = value_utf8;
3767 }
3768}
3769
3770// Version of getenv() that takes a UTF-8 environment variable name and
3771// retrieves a UTF-8 value.
3772char* adb_getenv(const char* name) {
3773 _ensure_env_setup();
3774
Spencer Lowcc467f12015-08-02 18:13:54 -07003775 const auto it = g_environ_utf8.find(std::string(name));
Spencer Low6815c072015-05-11 01:08:48 -07003776 if (it == g_environ_utf8.end()) {
3777 return nullptr;
3778 }
3779
3780 return it->second;
3781}
3782
3783// Version of getcwd() that returns the current working directory in UTF-8.
3784char* adb_getcwd(char* buf, int size) {
3785 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3786 if (wbuf == nullptr) {
3787 return nullptr;
3788 }
3789
3790 const std::string buf_utf8(narrow(wbuf));
3791 free(wbuf);
3792 wbuf = nullptr;
3793
3794 // If size was specified, make sure all the chars will fit.
3795 if (size != 0) {
3796 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3797 errno = ERANGE;
3798 return nullptr;
3799 }
3800 }
3801
3802 // If buf was not specified, allocate storage.
3803 if (buf == nullptr) {
3804 if (size == 0) {
3805 size = buf_utf8.length() + 1;
3806 }
3807 buf = reinterpret_cast<char*>(malloc(size));
3808 if (buf == nullptr) {
3809 return nullptr;
3810 }
3811 }
3812
3813 // Destination buffer was allocated with enough space, or we've already
3814 // checked an existing buffer size for enough space.
3815 strcpy(buf, buf_utf8.c_str());
3816
3817 return buf;
3818}