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