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