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