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