blob: d2e6cdb3fdd9c35f8663f028a753f9e798ae1f4e [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albertdb6fe642015-03-19 15:21:08 -070018
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
Spencer Low50740f52015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low753d4852015-07-30 23:07:55 -070029#include <memory>
30#include <string>
Spencer Low6815c072015-05-11 01:08:48 -070031#include <unordered_map>
Spencer Low753d4852015-07-30 23:07:55 -070032
Elliott Hughesfe447512015-07-24 11:35:40 -070033#include <cutils/sockets.h>
34
Spencer Low753d4852015-07-30 23:07:55 -070035#include <base/logging.h>
36#include <base/stringprintf.h>
37#include <base/strings.h>
38
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080039#include "adb.h"
40
41extern void fatal(const char *fmt, ...);
42
Elliott Hughes6a096932015-04-16 16:47:02 -070043/* forward declarations */
44
45typedef const struct FHClassRec_* FHClass;
46typedef struct FHRec_* FH;
47typedef struct EventHookRec_* EventHook;
48
49typedef struct FHClassRec_ {
50 void (*_fh_init)(FH);
51 int (*_fh_close)(FH);
52 int (*_fh_lseek)(FH, int, int);
53 int (*_fh_read)(FH, void*, int);
54 int (*_fh_write)(FH, const void*, int);
55 void (*_fh_hook)(FH, int, EventHook);
56} FHClassRec;
57
58static void _fh_file_init(FH);
59static int _fh_file_close(FH);
60static int _fh_file_lseek(FH, int, int);
61static int _fh_file_read(FH, void*, int);
62static int _fh_file_write(FH, const void*, int);
63static void _fh_file_hook(FH, int, EventHook);
64
65static const FHClassRec _fh_file_class = {
66 _fh_file_init,
67 _fh_file_close,
68 _fh_file_lseek,
69 _fh_file_read,
70 _fh_file_write,
71 _fh_file_hook
72};
73
74static void _fh_socket_init(FH);
75static int _fh_socket_close(FH);
76static int _fh_socket_lseek(FH, int, int);
77static int _fh_socket_read(FH, void*, int);
78static int _fh_socket_write(FH, const void*, int);
79static void _fh_socket_hook(FH, int, EventHook);
80
81static const FHClassRec _fh_socket_class = {
82 _fh_socket_init,
83 _fh_socket_close,
84 _fh_socket_lseek,
85 _fh_socket_read,
86 _fh_socket_write,
87 _fh_socket_hook
88};
89
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080090#define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
91
Spencer Low753d4852015-07-30 23:07:55 -070092std::string SystemErrorCodeToString(const DWORD error_code) {
93 const int kErrorMessageBufferSize = 256;
Spencer Lowcc467f12015-08-02 18:13:54 -070094 WCHAR msgbuf[kErrorMessageBufferSize];
Spencer Low753d4852015-07-30 23:07:55 -070095 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
Spencer Lowcc467f12015-08-02 18:13:54 -070096 DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf,
Spencer Low753d4852015-07-30 23:07:55 -070097 arraysize(msgbuf), nullptr);
98 if (len == 0) {
99 return android::base::StringPrintf(
100 "Error (%lu) while retrieving error. (%lu)", GetLastError(),
101 error_code);
102 }
103
Spencer Lowcc467f12015-08-02 18:13:54 -0700104 // Convert UTF-16 to UTF-8.
105 std::string msg(narrow(msgbuf));
Spencer Low753d4852015-07-30 23:07:55 -0700106 // Messages returned by the system end with line breaks.
107 msg = android::base::Trim(msg);
108 // There are many Windows error messages compared to POSIX, so include the
109 // numeric error code for easier, quicker, accurate identification. Use
110 // decimal instead of hex because there are decimal ranges like 10000-11999
111 // for Winsock.
112 android::base::StringAppendF(&msg, " (%lu)", error_code);
113 return msg;
114}
115
Spencer Low2bbb3a92015-08-26 18:46:09 -0700116void handle_deleter::operator()(HANDLE h) {
117 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
118 // implying that NULL is a valid handle, but this is probably impossible.
119 // Other APIs like CreateEvent() are documented to return NULL on error,
120 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
121 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
122 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
123 // only need to check for INVALID_HANDLE_VALUE.
124 if (h != INVALID_HANDLE_VALUE) {
125 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700126 D("CloseHandle(%p) failed: %s", h,
Spencer Low2bbb3a92015-08-26 18:46:09 -0700127 SystemErrorCodeToString(GetLastError()).c_str());
128 }
129 }
130}
131
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800132/**************************************************************************/
133/**************************************************************************/
134/***** *****/
135/***** replaces libs/cutils/load_file.c *****/
136/***** *****/
137/**************************************************************************/
138/**************************************************************************/
139
140void *load_file(const char *fn, unsigned *_sz)
141{
142 HANDLE file;
143 char *data;
144 DWORD file_size;
145
Spencer Low6815c072015-05-11 01:08:48 -0700146 file = CreateFileW( widen(fn).c_str(),
147 GENERIC_READ,
148 FILE_SHARE_READ,
149 NULL,
150 OPEN_EXISTING,
151 0,
152 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800153
154 if (file == INVALID_HANDLE_VALUE)
155 return NULL;
156
157 file_size = GetFileSize( file, NULL );
158 data = NULL;
159
160 if (file_size > 0) {
161 data = (char*) malloc( file_size + 1 );
162 if (data == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -0700163 D("load_file: could not allocate %ld bytes", file_size );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800164 file_size = 0;
165 } else {
166 DWORD out_bytes;
167
168 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
169 out_bytes != file_size )
170 {
Yabin Cui815ad882015-09-02 17:44:28 -0700171 D("load_file: could not read %ld bytes from '%s'", file_size, fn);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800172 free(data);
173 data = NULL;
174 file_size = 0;
175 }
176 }
177 }
178 CloseHandle( file );
179
180 *_sz = (unsigned) file_size;
181 return data;
182}
183
184/**************************************************************************/
185/**************************************************************************/
186/***** *****/
187/***** common file descriptor handling *****/
188/***** *****/
189/**************************************************************************/
190/**************************************************************************/
191
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800192/* used to emulate unix-domain socket pairs */
193typedef struct SocketPairRec_* SocketPair;
194
195typedef struct FHRec_
196{
197 FHClass clazz;
198 int used;
199 int eof;
200 union {
201 HANDLE handle;
202 SOCKET socket;
203 SocketPair pair;
204 } u;
205
206 HANDLE event;
207 int mask;
208
209 char name[32];
210
211} FHRec;
212
213#define fh_handle u.handle
214#define fh_socket u.socket
215#define fh_pair u.pair
216
217#define WIN32_FH_BASE 100
218
219#define WIN32_MAX_FHS 128
220
221static adb_mutex_t _win32_lock;
222static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700223static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800224
225static FH
Spencer Low3a2421b2015-05-22 20:09:06 -0700226_fh_from_int( int fd, const char* func )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800227{
228 FH f;
229
230 fd -= WIN32_FH_BASE;
231
Spencer Lowb732a372015-07-24 15:38:19 -0700232 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui815ad882015-09-02 17:44:28 -0700233 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700234 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800235 errno = EBADF;
236 return NULL;
237 }
238
239 f = &_win32_fhs[fd];
240
241 if (f->used == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700242 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low3a2421b2015-05-22 20:09:06 -0700243 func );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800244 errno = EBADF;
245 return NULL;
246 }
247
248 return f;
249}
250
251
252static int
253_fh_to_int( FH f )
254{
255 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
256 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
257
258 return -1;
259}
260
261static FH
262_fh_alloc( FHClass clazz )
263{
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800264 FH f = NULL;
265
266 adb_mutex_lock( &_win32_lock );
267
Spencer Lowb732a372015-07-24 15:38:19 -0700268 // Search entire array, starting from _win32_fh_next.
269 for (int nn = 0; nn < WIN32_MAX_FHS; nn++) {
270 // Keep incrementing _win32_fh_next to avoid giving out an index that
271 // was recently closed, to try to avoid use-after-free.
272 const int index = _win32_fh_next++;
273 // Handle wrap-around of _win32_fh_next.
274 if (_win32_fh_next == WIN32_MAX_FHS) {
275 _win32_fh_next = 0;
276 }
277 if (_win32_fhs[index].clazz == NULL) {
278 f = &_win32_fhs[index];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800279 goto Exit;
280 }
281 }
Yabin Cui815ad882015-09-02 17:44:28 -0700282 D( "_fh_alloc: no more free file descriptors" );
Spencer Lowb732a372015-07-24 15:38:19 -0700283 errno = EMFILE; // Too many open files
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800284Exit:
285 if (f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700286 f->clazz = clazz;
287 f->used = 1;
288 f->eof = 0;
289 f->name[0] = '\0';
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800290 clazz->_fh_init(f);
291 }
292 adb_mutex_unlock( &_win32_lock );
293 return f;
294}
295
296
297static int
298_fh_close( FH f )
299{
Spencer Lowb732a372015-07-24 15:38:19 -0700300 // Use lock so that closing only happens once and so that _fh_alloc can't
301 // allocate a FH that we're in the middle of closing.
302 adb_mutex_lock(&_win32_lock);
303 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800304 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700305 f->name[0] = '\0';
306 f->eof = 0;
307 f->used = 0;
308 f->clazz = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800309 }
Spencer Lowb732a372015-07-24 15:38:19 -0700310 adb_mutex_unlock(&_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800311 return 0;
312}
313
Spencer Low753d4852015-07-30 23:07:55 -0700314// Deleter for unique_fh.
315class fh_deleter {
316 public:
317 void operator()(struct FHRec_* fh) {
318 // We're called from a destructor and destructors should not overwrite
319 // errno because callers may do:
320 // errno = EBLAH;
321 // return -1; // calls destructor, which should not overwrite errno
322 const int saved_errno = errno;
323 _fh_close(fh);
324 errno = saved_errno;
325 }
326};
327
328// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
329typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
330
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800331/**************************************************************************/
332/**************************************************************************/
333/***** *****/
334/***** file-based descriptor handling *****/
335/***** *****/
336/**************************************************************************/
337/**************************************************************************/
338
Elliott Hughes6a096932015-04-16 16:47:02 -0700339static void _fh_file_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800340 f->fh_handle = INVALID_HANDLE_VALUE;
341}
342
Elliott Hughes6a096932015-04-16 16:47:02 -0700343static int _fh_file_close( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800344 CloseHandle( f->fh_handle );
345 f->fh_handle = INVALID_HANDLE_VALUE;
346 return 0;
347}
348
Elliott Hughes6a096932015-04-16 16:47:02 -0700349static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800350 DWORD read_bytes;
351
352 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700353 D( "adb_read: could not read %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800354 errno = EIO;
355 return -1;
356 } else if (read_bytes < (DWORD)len) {
357 f->eof = 1;
358 }
359 return (int)read_bytes;
360}
361
Elliott Hughes6a096932015-04-16 16:47:02 -0700362static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800363 DWORD wrote_bytes;
364
365 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700366 D( "adb_file_write: could not write %d bytes from %s", len, f->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800367 errno = EIO;
368 return -1;
369 } else if (wrote_bytes < (DWORD)len) {
370 f->eof = 1;
371 }
372 return (int)wrote_bytes;
373}
374
Elliott Hughes6a096932015-04-16 16:47:02 -0700375static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800376 DWORD method;
377 DWORD result;
378
379 switch (origin)
380 {
381 case SEEK_SET: method = FILE_BEGIN; break;
382 case SEEK_CUR: method = FILE_CURRENT; break;
383 case SEEK_END: method = FILE_END; break;
384 default:
385 errno = EINVAL;
386 return -1;
387 }
388
389 result = SetFilePointer( f->fh_handle, pos, NULL, method );
390 if (result == INVALID_SET_FILE_POINTER) {
391 errno = EIO;
392 return -1;
393 } else {
394 f->eof = 0;
395 }
396 return (int)result;
397}
398
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800399
400/**************************************************************************/
401/**************************************************************************/
402/***** *****/
403/***** file-based descriptor handling *****/
404/***** *****/
405/**************************************************************************/
406/**************************************************************************/
407
408int adb_open(const char* path, int options)
409{
410 FH f;
411
412 DWORD desiredAccess = 0;
413 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
414
415 switch (options) {
416 case O_RDONLY:
417 desiredAccess = GENERIC_READ;
418 break;
419 case O_WRONLY:
420 desiredAccess = GENERIC_WRITE;
421 break;
422 case O_RDWR:
423 desiredAccess = GENERIC_READ | GENERIC_WRITE;
424 break;
425 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700426 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800427 errno = EINVAL;
428 return -1;
429 }
430
431 f = _fh_alloc( &_fh_file_class );
432 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800433 return -1;
434 }
435
Spencer Low6815c072015-05-11 01:08:48 -0700436 f->fh_handle = CreateFileW( widen(path).c_str(), desiredAccess, shareMode,
437 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800438
439 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700440 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800441 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700442 D( "adb_open: could not open '%s': ", path );
443 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800444 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700445 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800446 errno = ENOENT;
447 return -1;
448
449 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700450 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800451 errno = ENOTDIR;
452 return -1;
453
454 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700455 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700456 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800457 errno = ENOENT;
458 return -1;
459 }
460 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800461
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800462 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700463 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800464 return _fh_to_int(f);
465}
466
467/* ignore mode on Win32 */
468int adb_creat(const char* path, int mode)
469{
470 FH f;
471
472 f = _fh_alloc( &_fh_file_class );
473 if ( !f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800474 return -1;
475 }
476
Spencer Low6815c072015-05-11 01:08:48 -0700477 f->fh_handle = CreateFileW( widen(path).c_str(), GENERIC_WRITE,
478 FILE_SHARE_READ | FILE_SHARE_WRITE,
479 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
480 NULL );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800481
482 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700483 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800484 _fh_close(f);
Spencer Low5c761bd2015-07-21 02:06:26 -0700485 D( "adb_creat: could not open '%s': ", path );
486 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800487 case ERROR_FILE_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700488 D( "file not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800489 errno = ENOENT;
490 return -1;
491
492 case ERROR_PATH_NOT_FOUND:
Yabin Cui815ad882015-09-02 17:44:28 -0700493 D( "path not found" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800494 errno = ENOTDIR;
495 return -1;
496
497 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700498 D( "unknown error: %s",
Spencer Low1711e012015-08-02 18:50:17 -0700499 SystemErrorCodeToString( err ).c_str() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800500 errno = ENOENT;
501 return -1;
502 }
503 }
504 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui815ad882015-09-02 17:44:28 -0700505 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800506 return _fh_to_int(f);
507}
508
509
510int adb_read(int fd, void* buf, int len)
511{
Spencer Low3a2421b2015-05-22 20:09:06 -0700512 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800513
514 if (f == NULL) {
515 return -1;
516 }
517
518 return f->clazz->_fh_read( f, buf, len );
519}
520
521
522int adb_write(int fd, const void* buf, int len)
523{
Spencer Low3a2421b2015-05-22 20:09:06 -0700524 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800525
526 if (f == NULL) {
527 return -1;
528 }
529
530 return f->clazz->_fh_write(f, buf, len);
531}
532
533
534int adb_lseek(int fd, int pos, int where)
535{
Spencer Low3a2421b2015-05-22 20:09:06 -0700536 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800537
538 if (!f) {
539 return -1;
540 }
541
542 return f->clazz->_fh_lseek(f, pos, where);
543}
544
545
546int adb_close(int fd)
547{
Spencer Low3a2421b2015-05-22 20:09:06 -0700548 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800549
550 if (!f) {
551 return -1;
552 }
553
Yabin Cui815ad882015-09-02 17:44:28 -0700554 D( "adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800555 _fh_close(f);
556 return 0;
557}
558
Spencer Low028e1592015-10-18 16:45:09 -0700559// Overrides strerror() to handle error codes not supported by the Windows C
560// Runtime (MSVCRT.DLL).
561char* adb_strerror(int err) {
562 // sysdeps.h defines strerror to adb_strerror, but in this function, we
563 // want to call the real C Runtime strerror().
564#pragma push_macro("strerror")
565#undef strerror
566 const int saved_err = errno; // Save because we overwrite it later.
567
568 // Lookup the string for an unknown error.
569 char* errmsg = strerror(-1);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700570 const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg;
Spencer Low028e1592015-10-18 16:45:09 -0700571
572 // Lookup the string for this error to see if the C Runtime has it.
573 errmsg = strerror(err);
Elliott Hughes6c73bfc2015-10-27 13:40:35 -0700574 if (errmsg != nullptr && unknown_error != errmsg) {
Spencer Low028e1592015-10-18 16:45:09 -0700575 // The CRT returned an error message and it is different than the error
576 // message for an unknown error, so it is probably valid, so use it.
577 } else {
578 // Check if we have a string for this error code.
579 const char* custom_msg = nullptr;
580 switch (err) {
581#pragma push_macro("ERR")
582#undef ERR
583#define ERR(errnum, desc) case errnum: custom_msg = desc; break
584 // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h.
585 // Note that these cannot be longer than 94 characters because we
586 // pass this to _strerror() which has that requirement.
587 ERR(ECONNRESET, "Connection reset by peer");
588 ERR(EHOSTUNREACH, "No route to host");
589 ERR(ENETDOWN, "Network is down");
590 ERR(ENETRESET, "Network dropped connection because of reset");
591 ERR(ENOBUFS, "No buffer space available");
592 ERR(ENOPROTOOPT, "Protocol not available");
593 ERR(ENOTCONN, "Transport endpoint is not connected");
594 ERR(ENOTSOCK, "Socket operation on non-socket");
595 ERR(EOPNOTSUPP, "Operation not supported on transport endpoint");
596#pragma pop_macro("ERR")
597 }
598
599 if (custom_msg != nullptr) {
600 // Use _strerror() to write our string into the writable per-thread
601 // buffer used by strerror()/_strerror(). _strerror() appends the
602 // msg for the current value of errno, so set errno to a consistent
603 // value for every call so that our code-path is always the same.
604 errno = 0;
605 errmsg = _strerror(custom_msg);
606 const size_t custom_msg_len = strlen(custom_msg);
607 // Just in case _strerror() returned a read-only string, check if
608 // the returned string starts with our custom message because that
609 // implies that the string is not read-only.
610 if ((errmsg != nullptr) &&
611 !strncmp(custom_msg, errmsg, custom_msg_len)) {
612 // _strerror() puts other text after our custom message, so
613 // remove that by terminating after our message.
614 errmsg[custom_msg_len] = '\0';
615 } else {
616 // For some reason nullptr was returned or a pointer to a
617 // read-only string was returned, so fallback to whatever
618 // strerror() can muster (probably "Unknown error" or some
619 // generic CRT error string).
620 errmsg = strerror(err);
621 }
622 } else {
623 // We don't have a custom message, so use whatever strerror(err)
624 // returned earlier.
625 }
626 }
627
628 errno = saved_err; // restore
629
630 return errmsg;
631#pragma pop_macro("strerror")
632}
633
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800634/**************************************************************************/
635/**************************************************************************/
636/***** *****/
637/***** socket-based file descriptors *****/
638/***** *****/
639/**************************************************************************/
640/**************************************************************************/
641
Spencer Low31aafa62015-01-25 14:40:16 -0800642#undef setsockopt
643
Spencer Low753d4852015-07-30 23:07:55 -0700644static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700645 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
646 // lot of POSIX and socket error codes, some of the resulting error codes
647 // are mapped to strings by adb_strerror() above.
Spencer Low753d4852015-07-30 23:07:55 -0700648 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800649 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700650 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
651 // case WSAEINTR: errno = EINTR; break;
652 case WSAEFAULT: errno = EFAULT; break;
653 case WSAEINVAL: errno = EINVAL; break;
654 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700655 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
656 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
657 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800658 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700659 case WSAENOTSOCK: errno = ENOTSOCK; break;
660 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
661 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
662 case WSAENETDOWN: errno = ENETDOWN; break;
663 case WSAENETRESET: errno = ENETRESET; break;
664 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
665 // to use EPIPE for these situations and there are some callers that look
666 // for EPIPE.
667 case WSAECONNABORTED: errno = EPIPE; break;
668 case WSAECONNRESET: errno = ECONNRESET; break;
669 case WSAENOBUFS: errno = ENOBUFS; break;
670 case WSAENOTCONN: errno = ENOTCONN; break;
671 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
672 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
673 // considerations: Reportedly send() can return zero on timeout, and POSIX
674 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
675 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
676 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800677 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800678 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700679 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700680 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800681 }
682}
683
Elliott Hughes6a096932015-04-16 16:47:02 -0700684static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800685 f->fh_socket = INVALID_SOCKET;
686 f->event = WSACreateEvent();
Spencer Low753d4852015-07-30 23:07:55 -0700687 if (f->event == WSA_INVALID_EVENT) {
Yabin Cui815ad882015-09-02 17:44:28 -0700688 D("WSACreateEvent failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700689 SystemErrorCodeToString(WSAGetLastError()).c_str());
690
691 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
692 // on failure, instead of NULL which is what Windows really returns on
693 // error. It might be better to change all the other code to look for
694 // NULL, but that is a much riskier change.
695 f->event = INVALID_HANDLE_VALUE;
696 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800697 f->mask = 0;
698}
699
Elliott Hughes6a096932015-04-16 16:47:02 -0700700static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700701 if (f->fh_socket != INVALID_SOCKET) {
702 /* gently tell any peer that we're closing the socket */
703 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
704 // If the socket is not connected, this returns an error. We want to
705 // minimize logging spam, so don't log these errors for now.
706#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700707 D("socket shutdown failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700708 SystemErrorCodeToString(WSAGetLastError()).c_str());
709#endif
710 }
711 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Yabin Cui815ad882015-09-02 17:44:28 -0700712 D("closesocket failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700713 SystemErrorCodeToString(WSAGetLastError()).c_str());
714 }
715 f->fh_socket = INVALID_SOCKET;
716 }
717 if (f->event != NULL) {
718 if (!CloseHandle(f->event)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700719 D("CloseHandle failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700720 SystemErrorCodeToString(GetLastError()).c_str());
721 }
722 f->event = NULL;
723 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800724 f->mask = 0;
725 return 0;
726}
727
Elliott Hughes6a096932015-04-16 16:47:02 -0700728static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800729 errno = EPIPE;
730 return -1;
731}
732
Elliott Hughes6a096932015-04-16 16:47:02 -0700733static int _fh_socket_read(FH f, void* buf, int len) {
734 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800735 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700736 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700737 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
738 // that to reduce spam and confusion.
739 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700740 D("recv fd %d failed: %s", _fh_to_int(f),
Spencer Low32625852015-08-11 16:45:32 -0700741 SystemErrorCodeToString(err).c_str());
742 }
Spencer Low753d4852015-07-30 23:07:55 -0700743 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800744 result = -1;
745 }
746 return result;
747}
748
Elliott Hughes6a096932015-04-16 16:47:02 -0700749static int _fh_socket_write(FH f, const void* buf, int len) {
750 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800751 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700752 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700753 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
754 // that to reduce spam and confusion.
755 if (err != WSAEWOULDBLOCK) {
756 D("send fd %d failed: %s", _fh_to_int(f),
757 SystemErrorCodeToString(err).c_str());
758 }
Spencer Low753d4852015-07-30 23:07:55 -0700759 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800760 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700761 } else {
762 // According to https://code.google.com/p/chromium/issues/detail?id=27870
763 // Winsock Layered Service Providers may cause this.
764 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
765 << f->name << ", but " << result
766 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800767 }
768 return result;
769}
770
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800771/**************************************************************************/
772/**************************************************************************/
773/***** *****/
774/***** replacement for libs/cutils/socket_xxxx.c *****/
775/***** *****/
776/**************************************************************************/
777/**************************************************************************/
778
779#include <winsock2.h>
780
781static int _winsock_init;
782
783static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800784_init_winsock( void )
785{
Spencer Low753d4852015-07-30 23:07:55 -0700786 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700787 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800788 if (!_winsock_init) {
789 WSADATA wsaData;
790 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
791 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700792 fatal( "adb: could not initialize Winsock: %s",
793 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800794 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800795 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700796
797 // Note that we do not call atexit() to register WSACleanup to be called
798 // at normal process termination because:
799 // 1) When exit() is called, there are still threads actively using
800 // Winsock because we don't cleanly shutdown all threads, so it
801 // doesn't make sense to call WSACleanup() and may cause problems
802 // with those threads.
803 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
804 // calls WSACleanup() which tries to unload a DLL, which tries to
805 // grab the LoaderLock. This conflicts with the device_poll_thread
806 // which holds the LoaderLock because AdbWinApi.dll calls
807 // setupapi.dll which tries to load wintrust.dll which tries to load
808 // crypt32.dll which calls atexit() which tries to acquire the C
809 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800810 }
811}
812
Spencer Lowc7c45612015-09-29 15:05:29 -0700813// Map a socket type to an explicit socket protocol instead of using the socket
814// protocol of 0. Explicit socket protocols are used by most apps and we should
815// do the same to reduce the chance of exercising uncommon code-paths that might
816// have problems or that might load different Winsock service providers that
817// have problems.
818static int GetSocketProtocolFromSocketType(int type) {
819 switch (type) {
820 case SOCK_STREAM:
821 return IPPROTO_TCP;
822 case SOCK_DGRAM:
823 return IPPROTO_UDP;
824 default:
825 LOG(FATAL) << "Unknown socket type: " << type;
826 return 0;
827 }
828}
829
Spencer Low753d4852015-07-30 23:07:55 -0700830int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800831 struct sockaddr_in addr;
832 SOCKET s;
833
Spencer Low753d4852015-07-30 23:07:55 -0700834 unique_fh f(_fh_alloc(&_fh_socket_class));
835 if (!f) {
836 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800837 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700838 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800839
840 if (!_winsock_init)
841 _init_winsock();
842
843 memset(&addr, 0, sizeof(addr));
844 addr.sin_family = AF_INET;
845 addr.sin_port = htons(port);
846 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
847
Spencer Lowc7c45612015-09-29 15:05:29 -0700848 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800849 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700850 *error = android::base::StringPrintf("cannot create socket: %s",
851 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700852 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700853 return -1;
854 }
855 f->fh_socket = s;
856
857 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700858 // Save err just in case inet_ntoa() or ntohs() changes the last error.
859 const DWORD err = WSAGetLastError();
860 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
861 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
862 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700863 D("could not connect to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700864 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800865 return -1;
866 }
867
Spencer Low753d4852015-07-30 23:07:55 -0700868 const int fd = _fh_to_int(f.get());
869 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
870 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700871 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700872 fd );
873 f.release();
874 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800875}
876
877#define LISTEN_BACKLOG 4
878
Spencer Low753d4852015-07-30 23:07:55 -0700879// interface_address is INADDR_LOOPBACK or INADDR_ANY.
880static int _network_server(int port, int type, u_long interface_address,
881 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800882 struct sockaddr_in addr;
883 SOCKET s;
884 int n;
885
Spencer Low753d4852015-07-30 23:07:55 -0700886 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800887 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700888 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800889 return -1;
890 }
891
892 if (!_winsock_init)
893 _init_winsock();
894
895 memset(&addr, 0, sizeof(addr));
896 addr.sin_family = AF_INET;
897 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700898 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800899
Spencer Low753d4852015-07-30 23:07:55 -0700900 // TODO: Consider using dual-stack socket that can simultaneously listen on
901 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700902 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700903 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700904 *error = android::base::StringPrintf("cannot create socket: %s",
905 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700906 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700907 return -1;
908 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800909
910 f->fh_socket = s;
911
Spencer Low32625852015-08-11 16:45:32 -0700912 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
913 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800914 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700915 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
916 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700917 *error = android::base::StringPrintf(
918 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
919 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700920 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700921 return -1;
922 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800923
Spencer Low32625852015-08-11 16:45:32 -0700924 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
925 // Save err just in case inet_ntoa() or ntohs() changes the last error.
926 const DWORD err = WSAGetLastError();
927 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
928 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
929 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700930 D("could not bind to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700931 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800932 return -1;
933 }
934 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700935 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700936 *error = android::base::StringPrintf("cannot listen on socket: %s",
937 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700938 D("could not listen on %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700939 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800940 return -1;
941 }
942 }
Spencer Low753d4852015-07-30 23:07:55 -0700943 const int fd = _fh_to_int(f.get());
944 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
945 interface_address == INADDR_LOOPBACK ? "lo" : "any",
946 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700947 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700948 fd );
949 f.release();
950 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800951}
952
Spencer Low753d4852015-07-30 23:07:55 -0700953int network_loopback_server(int port, int type, std::string* error) {
954 return _network_server(port, type, INADDR_LOOPBACK, error);
955}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800956
Spencer Low753d4852015-07-30 23:07:55 -0700957int network_inaddr_any_server(int port, int type, std::string* error) {
958 return _network_server(port, type, INADDR_ANY, error);
959}
960
961int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
962 unique_fh f(_fh_alloc(&_fh_socket_class));
963 if (!f) {
964 *error = strerror(errno);
965 return -1;
966 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800967
Elliott Hughes43df1092015-07-23 17:12:58 -0700968 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800969
Spencer Low753d4852015-07-30 23:07:55 -0700970 struct addrinfo hints;
971 memset(&hints, 0, sizeof(hints));
972 hints.ai_family = AF_UNSPEC;
973 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700974 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700975
976 char port_str[16];
977 snprintf(port_str, sizeof(port_str), "%d", port);
978
979 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700980
981#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
982 // TODO: When the Android SDK tools increases the Windows system
983 // requirements >= WinXP SP2, switch to GetAddrInfoW(widen(host).c_str()).
984#else
985 // Otherwise, keep using getaddrinfo(), or do runtime API detection
986 // with GetProcAddress("GetAddrInfoW").
987#endif
Spencer Low753d4852015-07-30 23:07:55 -0700988 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -0700989 *error = android::base::StringPrintf(
990 "cannot resolve host '%s' and port %s: %s", host.c_str(),
991 port_str, SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700992 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800993 return -1;
994 }
Spencer Low753d4852015-07-30 23:07:55 -0700995 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
996 addrinfo(addrinfo_ptr, freeaddrinfo);
997 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800998
Spencer Low753d4852015-07-30 23:07:55 -0700999 // TODO: Try all the addresses if there's more than one? This just uses
1000 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
1001 // which tries all addresses, takes a timeout and more.
1002 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
1003 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001004 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -07001005 *error = android::base::StringPrintf("cannot create socket: %s",
1006 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001007 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001008 return -1;
1009 }
1010 f->fh_socket = s;
1011
Spencer Low753d4852015-07-30 23:07:55 -07001012 // TODO: Implement timeouts for Windows. Seems like the default in theory
1013 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
1014 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -07001015 // TODO: Use WSAAddressToString or inet_ntop on address.
1016 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
1017 host.c_str(), port_str,
1018 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -07001019 D("could not connect to %s:%s:%s: %s",
Spencer Low753d4852015-07-30 23:07:55 -07001020 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
1021 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001022 return -1;
1023 }
1024
Spencer Low753d4852015-07-30 23:07:55 -07001025 const int fd = _fh_to_int(f.get());
1026 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
1027 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -07001028 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low753d4852015-07-30 23:07:55 -07001029 type != SOCK_STREAM ? "udp" : "tcp", fd );
1030 f.release();
1031 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001032}
1033
1034#undef accept
1035int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
1036{
Spencer Low3a2421b2015-05-22 20:09:06 -07001037 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001038
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001039 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001040 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -07001041 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001042 return -1;
1043 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001044
Spencer Low753d4852015-07-30 23:07:55 -07001045 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001046 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -07001047 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1048 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001049 return -1;
1050 }
1051
1052 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1053 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001054 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -07001055 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
1056 " failed: " + SystemErrorCodeToString(err);
1057 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001058 return -1;
1059 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001060
Spencer Low753d4852015-07-30 23:07:55 -07001061 const int fd = _fh_to_int(fh.get());
1062 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -07001063 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -07001064 fh.release();
1065 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001066}
1067
1068
Spencer Low31aafa62015-01-25 14:40:16 -08001069int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001070{
Spencer Low3a2421b2015-05-22 20:09:06 -07001071 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001072
Spencer Low31aafa62015-01-25 14:40:16 -08001073 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001074 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001075 errno = EBADF;
1076 return -1;
1077 }
Spencer Lowc7c45612015-09-29 15:05:29 -07001078
1079 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1080 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1081 // auto-tuning.
1082
Spencer Low753d4852015-07-30 23:07:55 -07001083 int result = setsockopt( fh->fh_socket, level, optname,
1084 reinterpret_cast<const char*>(optval), optlen );
1085 if ( result == SOCKET_ERROR ) {
1086 const DWORD err = WSAGetLastError();
1087 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
1088 "failed: %s\n", fd, level, optname,
1089 SystemErrorCodeToString(err).c_str() );
1090 _socket_set_errno( err );
1091 result = -1;
1092 }
1093 return result;
1094}
1095
1096
1097int adb_shutdown(int fd)
1098{
1099 FH f = _fh_from_int(fd, __func__);
1100
1101 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001102 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001103 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001104 return -1;
1105 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001106
Yabin Cui815ad882015-09-02 17:44:28 -07001107 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001108 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1109 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001110 D("socket shutdown fd %d failed: %s", fd,
Spencer Low753d4852015-07-30 23:07:55 -07001111 SystemErrorCodeToString(err).c_str());
1112 _socket_set_errno(err);
1113 return -1;
1114 }
1115 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001116}
1117
1118/**************************************************************************/
1119/**************************************************************************/
1120/***** *****/
1121/***** emulated socketpairs *****/
1122/***** *****/
1123/**************************************************************************/
1124/**************************************************************************/
1125
1126/* we implement socketpairs directly in use space for the following reasons:
1127 * - it avoids copying data from/to the Nt kernel
1128 * - it allows us to implement fdevent hooks easily and cheaply, something
1129 * that is not possible with standard Win32 pipes !!
1130 *
1131 * basically, we use two circular buffers, each one corresponding to a given
1132 * direction.
1133 *
1134 * each buffer is implemented as two regions:
1135 *
1136 * region A which is (a_start,a_end)
1137 * region B which is (0, b_end) with b_end <= a_start
1138 *
1139 * an empty buffer has: a_start = a_end = b_end = 0
1140 *
1141 * a_start is the pointer where we start reading data
1142 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
1143 * then you start writing at b_end
1144 *
1145 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
1146 *
1147 * there is room when b_end < a_start || a_end < BUFER_SIZE
1148 *
1149 * when reading, a_start is incremented, it a_start meets a_end, then
1150 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1151 */
1152
1153#define BIP_BUFFER_SIZE 4096
1154
1155#if 0
1156#include <stdio.h>
1157# define BIPD(x) D x
1158# define BIPDUMP bip_dump_hex
1159
1160static void bip_dump_hex( const unsigned char* ptr, size_t len )
1161{
1162 int nn, len2 = len;
1163
1164 if (len2 > 8) len2 = 8;
1165
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001166 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001167 printf("%02x", ptr[nn]);
1168 printf(" ");
1169
1170 for (nn = 0; nn < len2; nn++) {
1171 int c = ptr[nn];
1172 if (c < 32 || c > 127)
1173 c = '.';
1174 printf("%c", c);
1175 }
1176 printf("\n");
1177 fflush(stdout);
1178}
1179
1180#else
1181# define BIPD(x) do {} while (0)
1182# define BIPDUMP(p,l) BIPD(p)
1183#endif
1184
1185typedef struct BipBufferRec_
1186{
1187 int a_start;
1188 int a_end;
1189 int b_end;
1190 int fdin;
1191 int fdout;
1192 int closed;
1193 int can_write; /* boolean */
1194 HANDLE evt_write; /* event signaled when one can write to a buffer */
1195 int can_read; /* boolean */
1196 HANDLE evt_read; /* event signaled when one can read from a buffer */
1197 CRITICAL_SECTION lock;
1198 unsigned char buff[ BIP_BUFFER_SIZE ];
1199
1200} BipBufferRec, *BipBuffer;
1201
1202static void
1203bip_buffer_init( BipBuffer buffer )
1204{
Yabin Cui815ad882015-09-02 17:44:28 -07001205 D( "bit_buffer_init %p", buffer );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001206 buffer->a_start = 0;
1207 buffer->a_end = 0;
1208 buffer->b_end = 0;
1209 buffer->can_write = 1;
1210 buffer->can_read = 0;
1211 buffer->fdin = 0;
1212 buffer->fdout = 0;
1213 buffer->closed = 0;
1214 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1215 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1216 InitializeCriticalSection( &buffer->lock );
1217}
1218
1219static void
1220bip_buffer_close( BipBuffer bip )
1221{
1222 bip->closed = 1;
1223
1224 if (!bip->can_read) {
1225 SetEvent( bip->evt_read );
1226 }
1227 if (!bip->can_write) {
1228 SetEvent( bip->evt_write );
1229 }
1230}
1231
1232static void
1233bip_buffer_done( BipBuffer bip )
1234{
Yabin Cui815ad882015-09-02 17:44:28 -07001235 BIPD(( "bip_buffer_done: %d->%d", bip->fdin, bip->fdout ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001236 CloseHandle( bip->evt_read );
1237 CloseHandle( bip->evt_write );
1238 DeleteCriticalSection( &bip->lock );
1239}
1240
1241static int
1242bip_buffer_write( BipBuffer bip, const void* src, int len )
1243{
1244 int avail, count = 0;
1245
1246 if (len <= 0)
1247 return 0;
1248
Yabin Cui815ad882015-09-02 17:44:28 -07001249 BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001250 BIPDUMP( src, len );
1251
David Pursell7616ae12015-09-11 16:06:59 -07001252 if (bip->closed) {
1253 errno = EPIPE;
1254 return -1;
1255 }
1256
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001257 EnterCriticalSection( &bip->lock );
1258
1259 while (!bip->can_write) {
1260 int ret;
1261 LeaveCriticalSection( &bip->lock );
1262
1263 if (bip->closed) {
1264 errno = EPIPE;
1265 return -1;
1266 }
1267 /* spinlocking here is probably unfair, but let's live with it */
1268 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1269 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
Yabin Cui815ad882015-09-02 17:44:28 -07001270 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001271 return 0;
1272 }
1273 if (bip->closed) {
1274 errno = EPIPE;
1275 return -1;
1276 }
1277 EnterCriticalSection( &bip->lock );
1278 }
1279
Yabin Cui815ad882015-09-02 17:44:28 -07001280 BIPD(( "bip_buffer_write: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001281
1282 avail = BIP_BUFFER_SIZE - bip->a_end;
1283 if (avail > 0)
1284 {
1285 /* we can append to region A */
1286 if (avail > len)
1287 avail = len;
1288
1289 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001290 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001291 count += avail;
1292 len -= avail;
1293
1294 bip->a_end += avail;
1295 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1296 bip->can_write = 0;
1297 ResetEvent( bip->evt_write );
1298 goto Exit;
1299 }
1300 }
1301
1302 if (len == 0)
1303 goto Exit;
1304
1305 avail = bip->a_start - bip->b_end;
1306 assert( avail > 0 ); /* since can_write is TRUE */
1307
1308 if (avail > len)
1309 avail = len;
1310
1311 memcpy( bip->buff + bip->b_end, src, avail );
1312 count += avail;
1313 bip->b_end += avail;
1314
1315 if (bip->b_end == bip->a_start) {
1316 bip->can_write = 0;
1317 ResetEvent( bip->evt_write );
1318 }
1319
1320Exit:
1321 assert( count > 0 );
1322
1323 if ( !bip->can_read ) {
1324 bip->can_read = 1;
1325 SetEvent( bip->evt_read );
1326 }
1327
Yabin Cui815ad882015-09-02 17:44:28 -07001328 BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001329 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1330 LeaveCriticalSection( &bip->lock );
1331
1332 return count;
1333 }
1334
1335static int
1336bip_buffer_read( BipBuffer bip, void* dst, int len )
1337{
1338 int avail, count = 0;
1339
1340 if (len <= 0)
1341 return 0;
1342
Yabin Cui815ad882015-09-02 17:44:28 -07001343 BIPD(( "bip_buffer_read: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001344
1345 EnterCriticalSection( &bip->lock );
1346 while ( !bip->can_read )
1347 {
1348#if 0
1349 LeaveCriticalSection( &bip->lock );
1350 errno = EAGAIN;
1351 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001352#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001353 int ret;
1354 LeaveCriticalSection( &bip->lock );
1355
1356 if (bip->closed) {
1357 errno = EPIPE;
1358 return -1;
1359 }
1360
1361 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1362 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
Yabin Cui815ad882015-09-02 17:44:28 -07001363 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001364 return 0;
1365 }
1366 if (bip->closed) {
1367 errno = EPIPE;
1368 return -1;
1369 }
1370 EnterCriticalSection( &bip->lock );
1371#endif
1372 }
1373
Yabin Cui815ad882015-09-02 17:44:28 -07001374 BIPD(( "bip_buffer_read: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001375
1376 avail = bip->a_end - bip->a_start;
1377 assert( avail > 0 ); /* since can_read is TRUE */
1378
1379 if (avail > len)
1380 avail = len;
1381
1382 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001383 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001384 count += avail;
1385 len -= avail;
1386
1387 bip->a_start += avail;
1388 if (bip->a_start < bip->a_end)
1389 goto Exit;
1390
1391 bip->a_start = 0;
1392 bip->a_end = bip->b_end;
1393 bip->b_end = 0;
1394
1395 avail = bip->a_end;
1396 if (avail > 0) {
1397 if (avail > len)
1398 avail = len;
1399 memcpy( dst, bip->buff, avail );
1400 count += avail;
1401 bip->a_start += avail;
1402
1403 if ( bip->a_start < bip->a_end )
1404 goto Exit;
1405
1406 bip->a_start = bip->a_end = 0;
1407 }
1408
1409 bip->can_read = 0;
1410 ResetEvent( bip->evt_read );
1411
1412Exit:
1413 assert( count > 0 );
1414
1415 if (!bip->can_write ) {
1416 bip->can_write = 1;
1417 SetEvent( bip->evt_write );
1418 }
1419
1420 BIPDUMP( (const unsigned char*)dst - count, count );
Yabin Cui815ad882015-09-02 17:44:28 -07001421 BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001422 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1423 LeaveCriticalSection( &bip->lock );
1424
1425 return count;
1426}
1427
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001428typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001429{
1430 BipBufferRec a2b_bip;
1431 BipBufferRec b2a_bip;
1432 FH a_fd;
1433 int used;
1434
1435} SocketPairRec;
1436
1437void _fh_socketpair_init( FH f )
1438{
1439 f->fh_pair = NULL;
1440}
1441
1442static int
1443_fh_socketpair_close( FH f )
1444{
1445 if ( f->fh_pair ) {
1446 SocketPair pair = f->fh_pair;
1447
1448 if ( f == pair->a_fd ) {
1449 pair->a_fd = NULL;
1450 }
1451
1452 bip_buffer_close( &pair->b2a_bip );
1453 bip_buffer_close( &pair->a2b_bip );
1454
1455 if ( --pair->used == 0 ) {
1456 bip_buffer_done( &pair->b2a_bip );
1457 bip_buffer_done( &pair->a2b_bip );
1458 free( pair );
1459 }
1460 f->fh_pair = NULL;
1461 }
1462 return 0;
1463}
1464
1465static int
1466_fh_socketpair_lseek( FH f, int pos, int origin )
1467{
1468 errno = ESPIPE;
1469 return -1;
1470}
1471
1472static int
1473_fh_socketpair_read( FH f, void* buf, int len )
1474{
1475 SocketPair pair = f->fh_pair;
1476 BipBuffer bip;
1477
1478 if (!pair)
1479 return -1;
1480
1481 if ( f == pair->a_fd )
1482 bip = &pair->b2a_bip;
1483 else
1484 bip = &pair->a2b_bip;
1485
1486 return bip_buffer_read( bip, buf, len );
1487}
1488
1489static int
1490_fh_socketpair_write( FH f, const void* buf, int len )
1491{
1492 SocketPair pair = f->fh_pair;
1493 BipBuffer bip;
1494
1495 if (!pair)
1496 return -1;
1497
1498 if ( f == pair->a_fd )
1499 bip = &pair->a2b_bip;
1500 else
1501 bip = &pair->b2a_bip;
1502
1503 return bip_buffer_write( bip, buf, len );
1504}
1505
1506
1507static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1508
1509static const FHClassRec _fh_socketpair_class =
1510{
1511 _fh_socketpair_init,
1512 _fh_socketpair_close,
1513 _fh_socketpair_lseek,
1514 _fh_socketpair_read,
1515 _fh_socketpair_write,
1516 _fh_socketpair_hook
1517};
1518
1519
Elliott Hughes6a096932015-04-16 16:47:02 -07001520int adb_socketpair(int sv[2]) {
1521 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001522
Spencer Low753d4852015-07-30 23:07:55 -07001523 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1524 if (!fa) {
1525 return -1;
1526 }
1527 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1528 if (!fb) {
1529 return -1;
1530 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001531
Elliott Hughes6a096932015-04-16 16:47:02 -07001532 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001533 if (pair == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001534 D("adb_socketpair: not enough memory to allocate pipes" );
Spencer Low753d4852015-07-30 23:07:55 -07001535 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001536 }
1537
1538 bip_buffer_init( &pair->a2b_bip );
1539 bip_buffer_init( &pair->b2a_bip );
1540
1541 fa->fh_pair = pair;
1542 fb->fh_pair = pair;
1543 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001544 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001545
Spencer Low753d4852015-07-30 23:07:55 -07001546 sv[0] = _fh_to_int(fa.get());
1547 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001548
1549 pair->a2b_bip.fdin = sv[0];
1550 pair->a2b_bip.fdout = sv[1];
1551 pair->b2a_bip.fdin = sv[1];
1552 pair->b2a_bip.fdout = sv[0];
1553
1554 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1555 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
Yabin Cui815ad882015-09-02 17:44:28 -07001556 D( "adb_socketpair: returns (%d, %d)", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001557 fa.release();
1558 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001559 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001560}
1561
1562/**************************************************************************/
1563/**************************************************************************/
1564/***** *****/
1565/***** fdevents emulation *****/
1566/***** *****/
1567/***** this is a very simple implementation, we rely on the fact *****/
1568/***** that ADB doesn't use FDE_ERROR. *****/
1569/***** *****/
1570/**************************************************************************/
1571/**************************************************************************/
1572
1573#define FATAL(x...) fatal(__FUNCTION__, x)
1574
1575#if DEBUG
1576static void dump_fde(fdevent *fde, const char *info)
1577{
1578 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1579 fde->state & FDE_READ ? 'R' : ' ',
1580 fde->state & FDE_WRITE ? 'W' : ' ',
1581 fde->state & FDE_ERROR ? 'E' : ' ',
1582 info);
1583}
1584#else
1585#define dump_fde(fde, info) do { } while(0)
1586#endif
1587
1588#define FDE_EVENTMASK 0x00ff
1589#define FDE_STATEMASK 0xff00
1590
1591#define FDE_ACTIVE 0x0100
1592#define FDE_PENDING 0x0200
1593#define FDE_CREATED 0x0400
1594
1595static void fdevent_plist_enqueue(fdevent *node);
1596static void fdevent_plist_remove(fdevent *node);
1597static fdevent *fdevent_plist_dequeue(void);
1598
1599static fdevent list_pending = {
1600 .next = &list_pending,
1601 .prev = &list_pending,
1602};
1603
1604static fdevent **fd_table = 0;
1605static int fd_table_max = 0;
1606
1607typedef struct EventLooperRec_* EventLooper;
1608
1609typedef struct EventHookRec_
1610{
1611 EventHook next;
1612 FH fh;
1613 HANDLE h;
1614 int wanted; /* wanted event flags */
1615 int ready; /* ready event flags */
1616 void* aux;
1617 void (*prepare)( EventHook hook );
1618 int (*start) ( EventHook hook );
1619 void (*stop) ( EventHook hook );
1620 int (*check) ( EventHook hook );
1621 int (*peek) ( EventHook hook );
1622} EventHookRec;
1623
1624static EventHook _free_hooks;
1625
1626static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001627event_hook_alloc(FH fh) {
1628 EventHook hook = _free_hooks;
1629 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001630 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001631 } else {
1632 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001633 if (hook == NULL)
1634 fatal( "could not allocate event hook\n" );
1635 }
1636 hook->next = NULL;
1637 hook->fh = fh;
1638 hook->wanted = 0;
1639 hook->ready = 0;
1640 hook->h = INVALID_HANDLE_VALUE;
1641 hook->aux = NULL;
1642
1643 hook->prepare = NULL;
1644 hook->start = NULL;
1645 hook->stop = NULL;
1646 hook->check = NULL;
1647 hook->peek = NULL;
1648
1649 return hook;
1650}
1651
1652static void
1653event_hook_free( EventHook hook )
1654{
1655 hook->fh = NULL;
1656 hook->wanted = 0;
1657 hook->ready = 0;
1658 hook->next = _free_hooks;
1659 _free_hooks = hook;
1660}
1661
1662
1663static void
1664event_hook_signal( EventHook hook )
1665{
1666 FH f = hook->fh;
1667 int fd = _fh_to_int(f);
1668 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1669
1670 if (fde != NULL && fde->fd == fd) {
1671 if ((fde->state & FDE_PENDING) == 0) {
1672 fde->state |= FDE_PENDING;
1673 fdevent_plist_enqueue( fde );
1674 }
1675 fde->events |= hook->wanted;
1676 }
1677}
1678
1679
1680#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1681
1682typedef struct EventLooperRec_
1683{
1684 EventHook hooks;
1685 HANDLE htab[ MAX_LOOPER_HANDLES ];
1686 int htab_count;
1687
1688} EventLooperRec;
1689
1690static EventHook*
1691event_looper_find_p( EventLooper looper, FH fh )
1692{
1693 EventHook *pnode = &looper->hooks;
1694 EventHook node = *pnode;
1695 for (;;) {
1696 if ( node == NULL || node->fh == fh )
1697 break;
1698 pnode = &node->next;
1699 node = *pnode;
1700 }
1701 return pnode;
1702}
1703
1704static void
1705event_looper_hook( EventLooper looper, int fd, int events )
1706{
Spencer Low3a2421b2015-05-22 20:09:06 -07001707 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001708 EventHook *pnode;
1709 EventHook node;
1710
1711 if (f == NULL) /* invalid arg */ {
Yabin Cui815ad882015-09-02 17:44:28 -07001712 D("event_looper_hook: invalid fd=%d", fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001713 return;
1714 }
1715
1716 pnode = event_looper_find_p( looper, f );
1717 node = *pnode;
1718 if ( node == NULL ) {
1719 node = event_hook_alloc( f );
1720 node->next = *pnode;
1721 *pnode = node;
1722 }
1723
1724 if ( (node->wanted & events) != events ) {
1725 /* this should update start/stop/check/peek */
Yabin Cui815ad882015-09-02 17:44:28 -07001726 D("event_looper_hook: call hook for %d (new=%x, old=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001727 fd, node->wanted, events);
1728 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1729 node->wanted |= events;
1730 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07001731 D("event_looper_hook: ignoring events %x for %d wanted=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001732 events, fd, node->wanted);
1733 }
1734}
1735
1736static void
1737event_looper_unhook( EventLooper looper, int fd, int events )
1738{
Spencer Low3a2421b2015-05-22 20:09:06 -07001739 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001740 EventHook *pnode = event_looper_find_p( looper, fh );
1741 EventHook node = *pnode;
1742
1743 if (node != NULL) {
1744 int events2 = events & node->wanted;
1745 if ( events2 == 0 ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001746 D( "event_looper_unhook: events %x not registered for fd %d", events, fd );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001747 return;
1748 }
1749 node->wanted &= ~events2;
1750 if (!node->wanted) {
1751 *pnode = node->next;
1752 event_hook_free( node );
1753 }
1754 }
1755}
1756
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001757/*
1758 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1759 * handles to wait on.
1760 *
1761 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1762 * instance, this may happen if there are more than 64 processes running on a
1763 * device, or there are multiple devices connected (including the emulator) with
1764 * the combined number of running processes greater than 64. In this case using
1765 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1766 * because of the API limitations (64 handles max). So, we need to provide a way
1767 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1768 * easiest (and "Microsoft recommended") way to do that would be dividing the
1769 * handle array into chunks with the chunk size less than 64, and fire up as many
1770 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1771 * handles, and will report back to the caller which handle has been set.
1772 * Here is the implementation of that algorithm.
1773 */
1774
1775/* Number of handles to wait on in each wating thread. */
1776#define WAIT_ALL_CHUNK_SIZE 63
1777
1778/* Descriptor for a wating thread */
1779typedef struct WaitForAllParam {
1780 /* A handle to an event to signal when waiting is over. This handle is shared
1781 * accross all the waiting threads, so each waiting thread knows when any
1782 * other thread has exited, so it can exit too. */
1783 HANDLE main_event;
1784 /* Upon exit from a waiting thread contains the index of the handle that has
1785 * been signaled. The index is an absolute index of the signaled handle in
1786 * the original array. This pointer is shared accross all the waiting threads
1787 * and it's not guaranteed (due to a race condition) that when all the
1788 * waiting threads exit, the value contained here would indicate the first
1789 * handle that was signaled. This is fine, because the caller cares only
1790 * about any handle being signaled. It doesn't care about the order, nor
1791 * about the whole list of handles that were signaled. */
1792 LONG volatile *signaled_index;
1793 /* Array of handles to wait on in a waiting thread. */
1794 HANDLE* handles;
1795 /* Number of handles in 'handles' array to wait on. */
1796 int handles_count;
1797 /* Index inside the main array of the first handle in the 'handles' array. */
1798 int first_handle_index;
1799 /* Waiting thread handle. */
1800 HANDLE thread;
1801} WaitForAllParam;
1802
1803/* Waiting thread routine. */
1804static unsigned __stdcall
1805_in_waiter_thread(void* arg)
1806{
1807 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1808 int res;
1809 WaitForAllParam* const param = (WaitForAllParam*)arg;
1810
1811 /* We have to wait on the main_event in order to be notified when any of the
1812 * sibling threads is exiting. */
1813 wait_on[0] = param->main_event;
1814 /* The rest of the handles go behind the main event handle. */
1815 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1816
1817 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1818 if (res > 0 && res < (param->handles_count + 1)) {
1819 /* One of the original handles got signaled. Save its absolute index into
1820 * the output variable. */
1821 InterlockedCompareExchange(param->signaled_index,
1822 res - 1L + param->first_handle_index, -1L);
1823 }
1824
1825 /* Notify the caller (and the siblings) that the wait is over. */
1826 SetEvent(param->main_event);
1827
1828 _endthreadex(0);
1829 return 0;
1830}
1831
1832/* WaitForMultipeObjects fixer routine.
1833 * Param:
1834 * handles Array of handles to wait on.
1835 * handles_count Number of handles in the array.
1836 * Return:
1837 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1838 * WAIT_FAILED on an error.
1839 */
1840static int
1841_wait_for_all(HANDLE* handles, int handles_count)
1842{
1843 WaitForAllParam* threads;
1844 HANDLE main_event;
1845 int chunks, chunk, remains;
1846
1847 /* This variable is going to be accessed by several threads at the same time,
1848 * this is bound to fail randomly when the core is run on multi-core machines.
1849 * To solve this, we need to do the following (1 _and_ 2):
1850 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1851 * out the reads/writes in this function unexpectedly.
1852 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1853 * all accesses inside a critical section. But we can also use
1854 * InterlockedCompareExchange() which always provide a full memory barrier
1855 * on Win32.
1856 */
1857 volatile LONG sig_index = -1;
1858
1859 /* Calculate number of chunks, and allocate thread param array. */
1860 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1861 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1862 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1863 sizeof(WaitForAllParam));
1864 if (threads == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001865 D("Unable to allocate thread array for %d handles.", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001866 return (int)WAIT_FAILED;
1867 }
1868
1869 /* Create main event to wait on for all waiting threads. This is a "manualy
1870 * reset" event that will remain set once it was set. */
1871 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1872 if (main_event == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001873 D("Unable to create main event. Error: %ld", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001874 free(threads);
1875 return (int)WAIT_FAILED;
1876 }
1877
1878 /*
1879 * Initialize waiting thread parameters.
1880 */
1881
1882 for (chunk = 0; chunk < chunks; chunk++) {
1883 threads[chunk].main_event = main_event;
1884 threads[chunk].signaled_index = &sig_index;
1885 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1886 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1887 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1888 }
1889 if (remains) {
1890 threads[chunk].main_event = main_event;
1891 threads[chunk].signaled_index = &sig_index;
1892 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1893 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1894 threads[chunk].handles_count = remains;
1895 chunks++;
1896 }
1897
1898 /* Start the waiting threads. */
1899 for (chunk = 0; chunk < chunks; chunk++) {
1900 /* Note that using adb_thread_create is not appropriate here, since we
1901 * need a handle to wait on for thread termination. */
1902 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1903 &threads[chunk], 0, NULL);
1904 if (threads[chunk].thread == NULL) {
1905 /* Unable to create a waiter thread. Collapse. */
Yabin Cui815ad882015-09-02 17:44:28 -07001906 D("Unable to create a waiting thread %d of %d. errno=%d",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001907 chunk, chunks, errno);
1908 chunks = chunk;
1909 SetEvent(main_event);
1910 break;
1911 }
1912 }
1913
1914 /* Wait on any of the threads to get signaled. */
1915 WaitForSingleObject(main_event, INFINITE);
1916
1917 /* Wait on all the waiting threads to exit. */
1918 for (chunk = 0; chunk < chunks; chunk++) {
1919 WaitForSingleObject(threads[chunk].thread, INFINITE);
1920 CloseHandle(threads[chunk].thread);
1921 }
1922
1923 CloseHandle(main_event);
1924 free(threads);
1925
1926
1927 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1928 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1929}
1930
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001931static EventLooperRec win32_looper;
1932
1933static void fdevent_init(void)
1934{
1935 win32_looper.htab_count = 0;
1936 win32_looper.hooks = NULL;
1937}
1938
1939static void fdevent_connect(fdevent *fde)
1940{
1941 EventLooper looper = &win32_looper;
1942 int events = fde->state & FDE_EVENTMASK;
1943
1944 if (events != 0)
1945 event_looper_hook( looper, fde->fd, events );
1946}
1947
1948static void fdevent_disconnect(fdevent *fde)
1949{
1950 EventLooper looper = &win32_looper;
1951 int events = fde->state & FDE_EVENTMASK;
1952
1953 if (events != 0)
1954 event_looper_unhook( looper, fde->fd, events );
1955}
1956
1957static void fdevent_update(fdevent *fde, unsigned events)
1958{
1959 EventLooper looper = &win32_looper;
1960 unsigned events0 = fde->state & FDE_EVENTMASK;
1961
1962 if (events != events0) {
1963 int removes = events0 & ~events;
1964 int adds = events & ~events0;
1965 if (removes) {
Yabin Cui815ad882015-09-02 17:44:28 -07001966 D("fdevent_update: remove %x from %d", removes, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001967 event_looper_unhook( looper, fde->fd, removes );
1968 }
1969 if (adds) {
Yabin Cui815ad882015-09-02 17:44:28 -07001970 D("fdevent_update: add %x to %d", adds, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001971 event_looper_hook ( looper, fde->fd, adds );
1972 }
1973 }
1974}
1975
1976static void fdevent_process()
1977{
1978 EventLooper looper = &win32_looper;
1979 EventHook hook;
1980 int gotone = 0;
1981
1982 /* if we have at least one ready hook, execute it/them */
1983 for (hook = looper->hooks; hook; hook = hook->next) {
1984 hook->ready = 0;
1985 if (hook->prepare) {
1986 hook->prepare(hook);
1987 if (hook->ready != 0) {
1988 event_hook_signal( hook );
1989 gotone = 1;
1990 }
1991 }
1992 }
1993
1994 /* nothing's ready yet, so wait for something to happen */
1995 if (!gotone)
1996 {
1997 looper->htab_count = 0;
1998
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001999 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002000 {
2001 if (hook->start && !hook->start(hook)) {
Yabin Cui815ad882015-09-02 17:44:28 -07002002 D( "fdevent_process: error when starting a hook" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002003 return;
2004 }
2005 if (hook->h != INVALID_HANDLE_VALUE) {
2006 int nn;
2007
2008 for (nn = 0; nn < looper->htab_count; nn++)
2009 {
2010 if ( looper->htab[nn] == hook->h )
2011 goto DontAdd;
2012 }
2013 looper->htab[ looper->htab_count++ ] = hook->h;
2014 DontAdd:
2015 ;
2016 }
2017 }
2018
2019 if (looper->htab_count == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -07002020 D( "fdevent_process: nothing to wait for !!" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002021 return;
2022 }
2023
2024 do
2025 {
2026 int wait_ret;
2027
Yabin Cui815ad882015-09-02 17:44:28 -07002028 D( "adb_win32: waiting for %d events", looper->htab_count );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002029 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Yabin Cui815ad882015-09-02 17:44:28 -07002030 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.", looper->htab_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002031 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
2032 } else {
2033 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002034 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002035 if (wait_ret == (int)WAIT_FAILED) {
Yabin Cui815ad882015-09-02 17:44:28 -07002036 D( "adb_win32: wait failed, error %ld", GetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002037 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07002038 D( "adb_win32: got one (index %d)", wait_ret );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002039
2040 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
2041 * like mouse movements. we need to filter these with the "check" function
2042 */
2043 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
2044 {
2045 for (hook = looper->hooks; hook; hook = hook->next)
2046 {
2047 if ( looper->htab[wait_ret] == hook->h &&
2048 (!hook->check || hook->check(hook)) )
2049 {
Yabin Cui815ad882015-09-02 17:44:28 -07002050 D( "adb_win32: signaling %s for %x", hook->fh->name, hook->ready );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002051 event_hook_signal( hook );
2052 gotone = 1;
2053 break;
2054 }
2055 }
2056 }
2057 }
2058 }
2059 while (!gotone);
2060
2061 for (hook = looper->hooks; hook; hook = hook->next) {
2062 if (hook->stop)
2063 hook->stop( hook );
2064 }
2065 }
2066
2067 for (hook = looper->hooks; hook; hook = hook->next) {
2068 if (hook->peek && hook->peek(hook))
2069 event_hook_signal( hook );
2070 }
2071}
2072
2073
2074static void fdevent_register(fdevent *fde)
2075{
2076 int fd = fde->fd - WIN32_FH_BASE;
2077
2078 if(fd < 0) {
2079 FATAL("bogus negative fd (%d)\n", fde->fd);
2080 }
2081
2082 if(fd >= fd_table_max) {
2083 int oldmax = fd_table_max;
2084 if(fde->fd > 32000) {
2085 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
2086 }
2087 if(fd_table_max == 0) {
2088 fdevent_init();
2089 fd_table_max = 256;
2090 }
2091 while(fd_table_max <= fd) {
2092 fd_table_max *= 2;
2093 }
Elliott Hughes6a096932015-04-16 16:47:02 -07002094 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002095 if(fd_table == 0) {
2096 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
2097 }
2098 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
2099 }
2100
2101 fd_table[fd] = fde;
2102}
2103
2104static void fdevent_unregister(fdevent *fde)
2105{
2106 int fd = fde->fd - WIN32_FH_BASE;
2107
2108 if((fd < 0) || (fd >= fd_table_max)) {
2109 FATAL("fd out of range (%d)\n", fde->fd);
2110 }
2111
2112 if(fd_table[fd] != fde) {
2113 FATAL("fd_table out of sync");
2114 }
2115
2116 fd_table[fd] = 0;
2117
2118 if(!(fde->state & FDE_DONT_CLOSE)) {
2119 dump_fde(fde, "close");
2120 adb_close(fde->fd);
2121 }
2122}
2123
2124static void fdevent_plist_enqueue(fdevent *node)
2125{
2126 fdevent *list = &list_pending;
2127
2128 node->next = list;
2129 node->prev = list->prev;
2130 node->prev->next = node;
2131 list->prev = node;
2132}
2133
2134static void fdevent_plist_remove(fdevent *node)
2135{
2136 node->prev->next = node->next;
2137 node->next->prev = node->prev;
2138 node->next = 0;
2139 node->prev = 0;
2140}
2141
2142static fdevent *fdevent_plist_dequeue(void)
2143{
2144 fdevent *list = &list_pending;
2145 fdevent *node = list->next;
2146
2147 if(node == list) return 0;
2148
2149 list->next = node->next;
2150 list->next->prev = list;
2151 node->next = 0;
2152 node->prev = 0;
2153
2154 return node;
2155}
2156
2157fdevent *fdevent_create(int fd, fd_func func, void *arg)
2158{
2159 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2160 if(fde == 0) return 0;
2161 fdevent_install(fde, fd, func, arg);
2162 fde->state |= FDE_CREATED;
2163 return fde;
2164}
2165
2166void fdevent_destroy(fdevent *fde)
2167{
2168 if(fde == 0) return;
2169 if(!(fde->state & FDE_CREATED)) {
2170 FATAL("fde %p not created by fdevent_create()\n", fde);
2171 }
2172 fdevent_remove(fde);
2173}
2174
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002175void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002176{
2177 memset(fde, 0, sizeof(fdevent));
2178 fde->state = FDE_ACTIVE;
2179 fde->fd = fd;
2180 fde->func = func;
2181 fde->arg = arg;
2182
2183 fdevent_register(fde);
2184 dump_fde(fde, "connect");
2185 fdevent_connect(fde);
2186 fde->state |= FDE_ACTIVE;
2187}
2188
2189void fdevent_remove(fdevent *fde)
2190{
2191 if(fde->state & FDE_PENDING) {
2192 fdevent_plist_remove(fde);
2193 }
2194
2195 if(fde->state & FDE_ACTIVE) {
2196 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002197 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002198 fdevent_unregister(fde);
2199 }
2200
2201 fde->state = 0;
2202 fde->events = 0;
2203}
2204
2205
2206void fdevent_set(fdevent *fde, unsigned events)
2207{
2208 events &= FDE_EVENTMASK;
2209
2210 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2211
2212 if(fde->state & FDE_ACTIVE) {
2213 fdevent_update(fde, events);
2214 dump_fde(fde, "update");
2215 }
2216
2217 fde->state = (fde->state & FDE_STATEMASK) | events;
2218
2219 if(fde->state & FDE_PENDING) {
2220 /* if we're pending, make sure
2221 ** we don't signal an event that
2222 ** is no longer wanted.
2223 */
2224 fde->events &= (~events);
2225 if(fde->events == 0) {
2226 fdevent_plist_remove(fde);
2227 fde->state &= (~FDE_PENDING);
2228 }
2229 }
2230}
2231
2232void fdevent_add(fdevent *fde, unsigned events)
2233{
2234 fdevent_set(
2235 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2236}
2237
2238void fdevent_del(fdevent *fde, unsigned events)
2239{
2240 fdevent_set(
2241 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2242}
2243
2244void fdevent_loop()
2245{
2246 fdevent *fde;
2247
2248 for(;;) {
2249#if DEBUG
2250 fprintf(stderr,"--- ---- waiting for events\n");
2251#endif
2252 fdevent_process();
2253
2254 while((fde = fdevent_plist_dequeue())) {
2255 unsigned events = fde->events;
2256 fde->events = 0;
2257 fde->state &= (~FDE_PENDING);
2258 dump_fde(fde, "callback");
2259 fde->func(fde->fd, events, fde->arg);
2260 }
2261 }
2262}
2263
2264/** FILE EVENT HOOKS
2265 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002266
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002267static void _event_file_prepare( EventHook hook )
2268{
2269 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2270 /* we can always read/write */
2271 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2272 }
2273}
2274
2275static int _event_file_peek( EventHook hook )
2276{
2277 return (hook->wanted & (FDE_READ|FDE_WRITE));
2278}
2279
2280static void _fh_file_hook( FH f, int events, EventHook hook )
2281{
2282 hook->h = f->fh_handle;
2283 hook->prepare = _event_file_prepare;
2284 hook->peek = _event_file_peek;
2285}
2286
2287/** SOCKET EVENT HOOKS
2288 **/
2289
2290static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2291{
2292 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2293 if (hook->wanted & FDE_READ)
2294 hook->ready |= FDE_READ;
2295 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2296 hook->ready |= FDE_ERROR;
2297 }
2298 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2299 if (hook->wanted & FDE_WRITE)
2300 hook->ready |= FDE_WRITE;
2301 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2302 hook->ready |= FDE_ERROR;
2303 }
2304 if ( evts->lNetworkEvents & FD_OOB ) {
2305 if (hook->wanted & FDE_ERROR)
2306 hook->ready |= FDE_ERROR;
2307 }
2308}
2309
2310static void _event_socket_prepare( EventHook hook )
2311{
2312 WSANETWORKEVENTS evts;
2313
2314 /* look if some of the events we want already happened ? */
2315 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2316 _event_socket_verify( hook, &evts );
2317}
2318
2319static int _socket_wanted_to_flags( int wanted )
2320{
2321 int flags = 0;
2322 if (wanted & FDE_READ)
2323 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2324
2325 if (wanted & FDE_WRITE)
2326 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2327
2328 if (wanted & FDE_ERROR)
2329 flags |= FD_OOB;
2330
2331 return flags;
2332}
2333
2334static int _event_socket_start( EventHook hook )
2335{
2336 /* create an event which we're going to wait for */
2337 FH fh = hook->fh;
2338 long flags = _socket_wanted_to_flags( hook->wanted );
2339
2340 hook->h = fh->event;
2341 if (hook->h == INVALID_HANDLE_VALUE) {
Yabin Cui815ad882015-09-02 17:44:28 -07002342 D( "_event_socket_start: no event for %s", fh->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002343 return 0;
2344 }
2345
2346 if ( flags != fh->mask ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002347 D( "_event_socket_start: hooking %s for %x (flags %ld)", hook->fh->name, hook->wanted, flags );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002348 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002349 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d", hook->fh->name, WSAGetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002350 CloseHandle( hook->h );
2351 hook->h = INVALID_HANDLE_VALUE;
2352 exit(1);
2353 return 0;
2354 }
2355 fh->mask = flags;
2356 }
2357 return 1;
2358}
2359
2360static void _event_socket_stop( EventHook hook )
2361{
2362 hook->h = INVALID_HANDLE_VALUE;
2363}
2364
2365static int _event_socket_check( EventHook hook )
2366{
2367 int result = 0;
2368 FH fh = hook->fh;
2369 WSANETWORKEVENTS evts;
2370
2371 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2372 _event_socket_verify( hook, &evts );
2373 result = (hook->ready != 0);
2374 if (result) {
2375 ResetEvent( hook->h );
2376 }
2377 }
Yabin Cui815ad882015-09-02 17:44:28 -07002378 D( "_event_socket_check %s returns %d", fh->name, result );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002379 return result;
2380}
2381
2382static int _event_socket_peek( EventHook hook )
2383{
2384 WSANETWORKEVENTS evts;
2385 FH fh = hook->fh;
2386
2387 /* look if some of the events we want already happened ? */
2388 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2389 _event_socket_verify( hook, &evts );
2390 if (hook->ready)
2391 ResetEvent( hook->h );
2392 }
2393
2394 return hook->ready != 0;
2395}
2396
2397
2398
2399static void _fh_socket_hook( FH f, int events, EventHook hook )
2400{
2401 hook->prepare = _event_socket_prepare;
2402 hook->start = _event_socket_start;
2403 hook->stop = _event_socket_stop;
2404 hook->check = _event_socket_check;
2405 hook->peek = _event_socket_peek;
2406
Spencer Low753d4852015-07-30 23:07:55 -07002407 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002408 _event_socket_start( hook );
2409}
2410
2411/** SOCKETPAIR EVENT HOOKS
2412 **/
2413
2414static void _event_socketpair_prepare( EventHook hook )
2415{
2416 FH fh = hook->fh;
2417 SocketPair pair = fh->fh_pair;
2418 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2419 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2420
2421 if (hook->wanted & FDE_READ && rbip->can_read)
2422 hook->ready |= FDE_READ;
2423
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002424 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002425 hook->ready |= FDE_WRITE;
2426 }
2427
2428 static int _event_socketpair_start( EventHook hook )
2429 {
2430 FH fh = hook->fh;
2431 SocketPair pair = fh->fh_pair;
2432 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2433 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2434
2435 if (hook->wanted == FDE_READ)
2436 hook->h = rbip->evt_read;
2437
2438 else if (hook->wanted == FDE_WRITE)
2439 hook->h = wbip->evt_write;
2440
2441 else {
Yabin Cui815ad882015-09-02 17:44:28 -07002442 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002443 return 0;
2444 }
Yabin Cui815ad882015-09-02 17:44:28 -07002445 D( "_event_socketpair_start: hook %s for %x wanted=%x",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002446 hook->fh->name, _fh_to_int(fh), hook->wanted);
2447 return 1;
2448}
2449
2450static int _event_socketpair_peek( EventHook hook )
2451{
2452 _event_socketpair_prepare( hook );
2453 return hook->ready != 0;
2454}
2455
2456static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2457{
2458 hook->prepare = _event_socketpair_prepare;
2459 hook->start = _event_socketpair_start;
2460 hook->peek = _event_socketpair_peek;
2461}
2462
2463
2464void
2465adb_sysdeps_init( void )
2466{
2467#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2468#include "mutex_list.h"
2469 InitializeCriticalSection( &_win32_lock );
2470}
2471
Spencer Lowbeb61982015-03-01 15:06:21 -08002472/**************************************************************************/
2473/**************************************************************************/
2474/***** *****/
2475/***** Console Window Terminal Emulation *****/
2476/***** *****/
2477/**************************************************************************/
2478/**************************************************************************/
2479
2480// This reads input from a Win32 console window and translates it into Unix
2481// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2482// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2483// is emulated instead of xterm because it is probably more popular than xterm:
2484// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2485// supports modern fonts, etc. It seems best to emulate the terminal that most
2486// Android developers use because they'll fix apps (the shell, etc.) to keep
2487// working with that terminal's emulation.
2488//
2489// The point of this emulation is not to be perfect or to solve all issues with
2490// console windows on Windows, but to be better than the original code which
2491// just called read() (which called ReadFile(), which called ReadConsoleA())
2492// which did not support Ctrl-C, tab completion, shell input line editing
2493// keys, server echo, and more.
2494//
2495// This implementation reconfigures the console with SetConsoleMode(), then
2496// calls ReadConsoleInput() to get raw input which it remaps to Unix
2497// terminal-style sequences which is returned via unix_read() which is used
2498// by the 'adb shell' command.
2499//
2500// Code organization:
2501//
David Pursell58805362015-10-28 14:29:51 -07002502// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08002503// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2504// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2505// * _console_read() is the main code of the emulation.
2506
David Pursell58805362015-10-28 14:29:51 -07002507// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
2508// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
2509// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
2510static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
2511 // First check isatty(); this is very fast and eliminates most non-console
2512 // FDs, but returns 1 for both consoles and character devices like NUL.
2513#pragma push_macro("isatty")
2514#undef isatty
2515 if (!isatty(fd)) {
2516 return nullptr;
2517 }
2518#pragma pop_macro("isatty")
2519
2520 // To differentiate between character devices and consoles we need to get
2521 // the underlying HANDLE and use GetConsoleMode(), which is what requires
2522 // GENERIC_READ permissions.
2523 const intptr_t intptr_handle = _get_osfhandle(fd);
2524 if (intptr_handle == -1) {
2525 return nullptr;
2526 }
2527 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
2528 DWORD temp_mode = 0;
2529 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
2530 return nullptr;
2531 }
2532
2533 return handle;
2534}
2535
2536// Returns a console handle if |stream| is a console, otherwise returns nullptr.
2537static HANDLE _get_console_handle(FILE* const stream) {
2538 const int fd = fileno(stream);
2539 if (fd < 0) {
2540 return nullptr;
2541 }
2542 return _get_console_handle(fd);
2543}
2544
2545int unix_isatty(int fd) {
2546 return _get_console_handle(fd) ? 1 : 0;
2547}
Spencer Lowbeb61982015-03-01 15:06:21 -08002548
2549// Read an input record from the console; one that should be processed.
2550static bool _get_interesting_input_record_uncached(const HANDLE console,
2551 INPUT_RECORD* const input_record) {
2552 for (;;) {
2553 DWORD read_count = 0;
2554 memset(input_record, 0, sizeof(*input_record));
2555 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2556 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
Spencer Low1711e012015-08-02 18:50:17 -07002557 "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002558 errno = EIO;
2559 return false;
2560 }
2561
2562 if (read_count == 0) { // should be impossible
2563 fatal("ReadConsoleInputA returned 0");
2564 }
2565
2566 if (read_count != 1) { // should be impossible
2567 fatal("ReadConsoleInputA did not return one input record");
2568 }
2569
2570 if ((input_record->EventType == KEY_EVENT) &&
2571 (input_record->Event.KeyEvent.bKeyDown)) {
2572 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2573 fatal("ReadConsoleInputA returned a key event with zero repeat"
2574 " count");
2575 }
2576
2577 // Got an interesting INPUT_RECORD, so return
2578 return true;
2579 }
2580 }
2581}
2582
2583// Cached input record (in case _console_read() is passed a buffer that doesn't
2584// have enough space to fit wRepeatCount number of key sequences). A non-zero
2585// wRepeatCount indicates that a record is cached.
2586static INPUT_RECORD _win32_input_record;
2587
2588// Get the next KEY_EVENT_RECORD that should be processed.
2589static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2590 // If nothing cached, read directly from the console until we get an
2591 // interesting record.
2592 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2593 if (!_get_interesting_input_record_uncached(console,
2594 &_win32_input_record)) {
2595 // There was an error, so make sure wRepeatCount is zero because
2596 // that signifies no cached input record.
2597 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2598 return NULL;
2599 }
2600 }
2601
2602 return &_win32_input_record.Event.KeyEvent;
2603}
2604
2605static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2606 return (control_key_state & SHIFT_PRESSED) != 0;
2607}
2608
2609static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2610 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2611}
2612
2613static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2614 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2615}
2616
2617static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2618 return (control_key_state & NUMLOCK_ON) != 0;
2619}
2620
2621static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2622 return (control_key_state & CAPSLOCK_ON) != 0;
2623}
2624
2625static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2626 return (control_key_state & ENHANCED_KEY) != 0;
2627}
2628
2629// Constants from MSDN for ToAscii().
2630static const BYTE TOASCII_KEY_OFF = 0x00;
2631static const BYTE TOASCII_KEY_DOWN = 0x80;
2632static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2633
2634// Given a key event, ignore a modifier key and return the character that was
2635// entered without the modifier. Writes to *ch and returns the number of bytes
2636// written.
2637static size_t _get_char_ignoring_modifier(char* const ch,
2638 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2639 const WORD modifier) {
2640 // If there is no character from Windows, try ignoring the specified
2641 // modifier and look for a character. Note that if AltGr is being used,
2642 // there will be a character from Windows.
2643 if (key_event->uChar.AsciiChar == '\0') {
2644 // Note that we read the control key state from the passed in argument
2645 // instead of from key_event since the argument has been normalized.
2646 if (((modifier == VK_SHIFT) &&
2647 _is_shift_pressed(control_key_state)) ||
2648 ((modifier == VK_CONTROL) &&
2649 _is_ctrl_pressed(control_key_state)) ||
2650 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2651
2652 BYTE key_state[256] = {0};
2653 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2654 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2655 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2656 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2657 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2658 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2659 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2660 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2661
2662 // cause this modifier to be ignored
2663 key_state[modifier] = TOASCII_KEY_OFF;
2664
2665 WORD translated = 0;
2666 if (ToAscii(key_event->wVirtualKeyCode,
2667 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2668 // Ignoring the modifier, we found a character.
2669 *ch = (CHAR)translated;
2670 return 1;
2671 }
2672 }
2673 }
2674
2675 // Just use whatever Windows told us originally.
2676 *ch = key_event->uChar.AsciiChar;
2677
2678 // If the character from Windows is NULL, return a size of zero.
2679 return (*ch == '\0') ? 0 : 1;
2680}
2681
2682// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2683// but taking into account the shift key. This is because for a sequence like
2684// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2685// we want to find the character ')'.
2686//
2687// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2688// because it is the default key-sequence to switch the input language.
2689// This is configurable in the Region and Language control panel.
2690static __inline__ size_t _get_non_control_char(char* const ch,
2691 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2692 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2693 VK_CONTROL);
2694}
2695
2696// Get without Alt.
2697static __inline__ size_t _get_non_alt_char(char* const ch,
2698 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2699 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2700 VK_MENU);
2701}
2702
2703// Ignore the control key, find the character from Windows, and apply any
2704// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2705// *pch and returns number of bytes written.
2706static size_t _get_control_character(char* const pch,
2707 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2708 const size_t len = _get_non_control_char(pch, key_event,
2709 control_key_state);
2710
2711 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2712 char ch = *pch;
2713 switch (ch) {
2714 case '2':
2715 case '@':
2716 case '`':
2717 ch = '\0';
2718 break;
2719 case '3':
2720 case '[':
2721 case '{':
2722 ch = '\x1b';
2723 break;
2724 case '4':
2725 case '\\':
2726 case '|':
2727 ch = '\x1c';
2728 break;
2729 case '5':
2730 case ']':
2731 case '}':
2732 ch = '\x1d';
2733 break;
2734 case '6':
2735 case '^':
2736 case '~':
2737 ch = '\x1e';
2738 break;
2739 case '7':
2740 case '-':
2741 case '_':
2742 ch = '\x1f';
2743 break;
2744 case '8':
2745 ch = '\x7f';
2746 break;
2747 case '/':
2748 if (!_is_alt_pressed(control_key_state)) {
2749 ch = '\x1f';
2750 }
2751 break;
2752 case '?':
2753 if (!_is_alt_pressed(control_key_state)) {
2754 ch = '\x7f';
2755 }
2756 break;
2757 }
2758 *pch = ch;
2759 }
2760
2761 return len;
2762}
2763
2764static DWORD _normalize_altgr_control_key_state(
2765 const KEY_EVENT_RECORD* const key_event) {
2766 DWORD control_key_state = key_event->dwControlKeyState;
2767
2768 // If we're in an AltGr situation where the AltGr key is down (depending on
2769 // the keyboard layout, that might be the physical right alt key which
2770 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2771 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2772 // a character (which indicates that there was an AltGr mapping), then act
2773 // as if alt and control are not really down for the purposes of modifiers.
2774 // This makes it so that if the user with, say, a German keyboard layout
2775 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2776 // output the key and we don't see the Alt and Ctrl keys.
2777 if (_is_ctrl_pressed(control_key_state) &&
2778 _is_alt_pressed(control_key_state)
2779 && (key_event->uChar.AsciiChar != '\0')) {
2780 // Try to remove as few bits as possible to improve our chances of
2781 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2782 // Left-Alt + Right-Ctrl + AltGr.
2783 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2784 // Remove Right-Alt.
2785 control_key_state &= ~RIGHT_ALT_PRESSED;
2786 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2787 // pressed, Left-Ctrl is almost always set, except if the user
2788 // presses Right-Ctrl, then AltGr (in that specific order) for
2789 // whatever reason. At any rate, make sure the bit is not set.
2790 control_key_state &= ~LEFT_CTRL_PRESSED;
2791 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2792 // Remove Left-Alt.
2793 control_key_state &= ~LEFT_ALT_PRESSED;
2794 // Whichever Ctrl key is down, remove it from the state. We only
2795 // remove one key, to improve our chances of detecting the
2796 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2797 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2798 // Remove Left-Ctrl.
2799 control_key_state &= ~LEFT_CTRL_PRESSED;
2800 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2801 // Remove Right-Ctrl.
2802 control_key_state &= ~RIGHT_CTRL_PRESSED;
2803 }
2804 }
2805
2806 // Note that this logic isn't 100% perfect because Windows doesn't
2807 // allow us to detect all combinations because a physical AltGr key
2808 // press shows up as two bits, plus some combinations are ambiguous
2809 // about what is actually physically pressed.
2810 }
2811
2812 return control_key_state;
2813}
2814
2815// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2816// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2817// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2818// appropriately.
2819static DWORD _normalize_keypad_control_key_state(const WORD vk,
2820 const DWORD control_key_state) {
2821 if (!_is_numlock_on(control_key_state)) {
2822 return control_key_state;
2823 }
2824 if (!_is_enhanced_key(control_key_state)) {
2825 switch (vk) {
2826 case VK_INSERT: // 0
2827 case VK_DELETE: // .
2828 case VK_END: // 1
2829 case VK_DOWN: // 2
2830 case VK_NEXT: // 3
2831 case VK_LEFT: // 4
2832 case VK_CLEAR: // 5
2833 case VK_RIGHT: // 6
2834 case VK_HOME: // 7
2835 case VK_UP: // 8
2836 case VK_PRIOR: // 9
2837 return control_key_state | SHIFT_PRESSED;
2838 }
2839 }
2840
2841 return control_key_state;
2842}
2843
2844static const char* _get_keypad_sequence(const DWORD control_key_state,
2845 const char* const normal, const char* const shifted) {
2846 if (_is_shift_pressed(control_key_state)) {
2847 // Shift is pressed and NumLock is off
2848 return shifted;
2849 } else {
2850 // Shift is not pressed and NumLock is off, or,
2851 // Shift is pressed and NumLock is on, in which case we want the
2852 // NumLock and Shift to neutralize each other, thus, we want the normal
2853 // sequence.
2854 return normal;
2855 }
2856 // If Shift is not pressed and NumLock is on, a different virtual key code
2857 // is returned by Windows, which can be taken care of by a different case
2858 // statement in _console_read().
2859}
2860
2861// Write sequence to buf and return the number of bytes written.
2862static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2863 DWORD control_key_state, const char* const normal) {
2864 // Copy the base sequence into buf.
2865 const size_t len = strlen(normal);
2866 memcpy(buf, normal, len);
2867
2868 int code = 0;
2869
2870 control_key_state = _normalize_keypad_control_key_state(vk,
2871 control_key_state);
2872
2873 if (_is_shift_pressed(control_key_state)) {
2874 code |= 0x1;
2875 }
2876 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2877 code |= 0x2;
2878 }
2879 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2880 code |= 0x4;
2881 }
2882 // If some modifier was held down, then we need to insert the modifier code
2883 if (code != 0) {
2884 if (len == 0) {
2885 // Should be impossible because caller should pass a string of
2886 // non-zero length.
2887 return 0;
2888 }
2889 size_t index = len - 1;
2890 const char lastChar = buf[index];
2891 if (lastChar != '~') {
2892 buf[index++] = '1';
2893 }
2894 buf[index++] = ';'; // modifier separator
2895 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2896 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2897 buf[index++] = '1' + code;
2898 buf[index++] = lastChar; // move ~ (or other last char) to the end
2899 return index;
2900 }
2901 return len;
2902}
2903
2904// Write sequence to buf and return the number of bytes written.
2905static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2906 const DWORD control_key_state, const char* const normal,
2907 const char shifted) {
2908 if (_is_shift_pressed(control_key_state)) {
2909 // Shift is pressed and NumLock is off
2910 if (shifted != '\0') {
2911 buf[0] = shifted;
2912 return sizeof(buf[0]);
2913 } else {
2914 return 0;
2915 }
2916 } else {
2917 // Shift is not pressed and NumLock is off, or,
2918 // Shift is pressed and NumLock is on, in which case we want the
2919 // NumLock and Shift to neutralize each other, thus, we want the normal
2920 // sequence.
2921 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2922 }
2923 // If Shift is not pressed and NumLock is on, a different virtual key code
2924 // is returned by Windows, which can be taken care of by a different case
2925 // statement in _console_read().
2926}
2927
2928// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2929// Standard German. Figure this out at runtime so we know what to output for
2930// Shift-VK_DELETE.
2931static char _get_decimal_char() {
2932 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2933}
2934
2935// Prefix the len bytes in buf with the escape character, and then return the
2936// new buffer length.
2937size_t _escape_prefix(char* const buf, const size_t len) {
2938 // If nothing to prefix, don't do anything. We might be called with
2939 // len == 0, if alt was held down with a dead key which produced nothing.
2940 if (len == 0) {
2941 return 0;
2942 }
2943
2944 memmove(&buf[1], buf, len);
2945 buf[0] = '\x1b';
2946 return len + 1;
2947}
2948
2949// Writes to buffer buf (of length len), returning number of bytes written or
2950// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2951// (as far as I can tell).
2952static int _console_read(const HANDLE console, void* buf, size_t len) {
2953 for (;;) {
2954 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2955 if (key_event == NULL) {
2956 return -1;
2957 }
2958
2959 const WORD vk = key_event->wVirtualKeyCode;
2960 const CHAR ch = key_event->uChar.AsciiChar;
2961 const DWORD control_key_state = _normalize_altgr_control_key_state(
2962 key_event);
2963
2964 // The following emulation code should write the output sequence to
2965 // either seqstr or to seqbuf and seqbuflen.
2966 const char* seqstr = NULL; // NULL terminated C-string
2967 // Enough space for max sequence string below, plus modifiers and/or
2968 // escape prefix.
2969 char seqbuf[16];
2970 size_t seqbuflen = 0; // Space used in seqbuf.
2971
2972#define MATCH(vk, normal) \
2973 case (vk): \
2974 { \
2975 seqstr = (normal); \
2976 } \
2977 break;
2978
2979 // Modifier keys should affect the output sequence.
2980#define MATCH_MODIFIER(vk, normal) \
2981 case (vk): \
2982 { \
2983 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2984 control_key_state, (normal)); \
2985 } \
2986 break;
2987
2988 // The shift key should affect the output sequence.
2989#define MATCH_KEYPAD(vk, normal, shifted) \
2990 case (vk): \
2991 { \
2992 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2993 (shifted)); \
2994 } \
2995 break;
2996
2997 // The shift key and other modifier keys should affect the output
2998 // sequence.
2999#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
3000 case (vk): \
3001 { \
3002 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
3003 control_key_state, (normal), (shifted)); \
3004 } \
3005 break;
3006
3007#define ESC "\x1b"
3008#define CSI ESC "["
3009#define SS3 ESC "O"
3010
3011 // Only support normal mode, not application mode.
3012
3013 // Enhanced keys:
3014 // * 6-pack: insert, delete, home, end, page up, page down
3015 // * cursor keys: up, down, right, left
3016 // * keypad: divide, enter
3017 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
3018 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
3019 if (_is_enhanced_key(control_key_state)) {
3020 switch (vk) {
3021 case VK_RETURN: // Enter key on keypad
3022 if (_is_ctrl_pressed(control_key_state)) {
3023 seqstr = "\n";
3024 } else {
3025 seqstr = "\r";
3026 }
3027 break;
3028
3029 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
3030 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
3031
3032 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
3033 // will be fixed soon to match xterm which sends CSI "F" and
3034 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
3035 MATCH(VK_END, CSI "F");
3036 MATCH(VK_HOME, CSI "H");
3037
3038 MATCH_MODIFIER(VK_LEFT, CSI "D");
3039 MATCH_MODIFIER(VK_UP, CSI "A");
3040 MATCH_MODIFIER(VK_RIGHT, CSI "C");
3041 MATCH_MODIFIER(VK_DOWN, CSI "B");
3042
3043 MATCH_MODIFIER(VK_INSERT, CSI "2~");
3044 MATCH_MODIFIER(VK_DELETE, CSI "3~");
3045
3046 MATCH(VK_DIVIDE, "/");
3047 }
3048 } else { // Non-enhanced keys:
3049 switch (vk) {
3050 case VK_BACK: // backspace
3051 if (_is_alt_pressed(control_key_state)) {
3052 seqstr = ESC "\x7f";
3053 } else {
3054 seqstr = "\x7f";
3055 }
3056 break;
3057
3058 case VK_TAB:
3059 if (_is_shift_pressed(control_key_state)) {
3060 seqstr = CSI "Z";
3061 } else {
3062 seqstr = "\t";
3063 }
3064 break;
3065
3066 // Number 5 key in keypad when NumLock is off, or if NumLock is
3067 // on and Shift is down.
3068 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
3069
3070 case VK_RETURN: // Enter key on main keyboard
3071 if (_is_alt_pressed(control_key_state)) {
3072 seqstr = ESC "\n";
3073 } else if (_is_ctrl_pressed(control_key_state)) {
3074 seqstr = "\n";
3075 } else {
3076 seqstr = "\r";
3077 }
3078 break;
3079
3080 // VK_ESCAPE: Don't do any special handling. The OS uses many
3081 // of the sequences with Escape and many of the remaining
3082 // sequences don't produce bKeyDown messages, only !bKeyDown
3083 // for whatever reason.
3084
3085 case VK_SPACE:
3086 if (_is_alt_pressed(control_key_state)) {
3087 seqstr = ESC " ";
3088 } else if (_is_ctrl_pressed(control_key_state)) {
3089 seqbuf[0] = '\0'; // NULL char
3090 seqbuflen = 1;
3091 } else {
3092 seqstr = " ";
3093 }
3094 break;
3095
3096 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
3097 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
3098
3099 MATCH_KEYPAD(VK_END, CSI "4~", "1");
3100 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
3101
3102 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
3103 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
3104 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
3105 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
3106
3107 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
3108 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
3109 _get_decimal_char());
3110
3111 case 0x30: // 0
3112 case 0x31: // 1
3113 case 0x39: // 9
3114 case VK_OEM_1: // ;:
3115 case VK_OEM_PLUS: // =+
3116 case VK_OEM_COMMA: // ,<
3117 case VK_OEM_PERIOD: // .>
3118 case VK_OEM_7: // '"
3119 case VK_OEM_102: // depends on keyboard, could be <> or \|
3120 case VK_OEM_2: // /?
3121 case VK_OEM_3: // `~
3122 case VK_OEM_4: // [{
3123 case VK_OEM_5: // \|
3124 case VK_OEM_6: // ]}
3125 {
3126 seqbuflen = _get_control_character(seqbuf, key_event,
3127 control_key_state);
3128
3129 if (_is_alt_pressed(control_key_state)) {
3130 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3131 }
3132 }
3133 break;
3134
3135 case 0x32: // 2
3136 case 0x36: // 6
3137 case VK_OEM_MINUS: // -_
3138 {
3139 seqbuflen = _get_control_character(seqbuf, key_event,
3140 control_key_state);
3141
3142 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3143 // prefix with escape.
3144 if (_is_alt_pressed(control_key_state) &&
3145 !(_is_ctrl_pressed(control_key_state) &&
3146 !_is_shift_pressed(control_key_state))) {
3147 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3148 }
3149 }
3150 break;
3151
3152 case 0x33: // 3
3153 case 0x34: // 4
3154 case 0x35: // 5
3155 case 0x37: // 7
3156 case 0x38: // 8
3157 {
3158 seqbuflen = _get_control_character(seqbuf, key_event,
3159 control_key_state);
3160
3161 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3162 // prefix with escape.
3163 if (_is_alt_pressed(control_key_state) &&
3164 !(_is_ctrl_pressed(control_key_state) &&
3165 !_is_shift_pressed(control_key_state))) {
3166 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3167 }
3168 }
3169 break;
3170
3171 case 0x41: // a
3172 case 0x42: // b
3173 case 0x43: // c
3174 case 0x44: // d
3175 case 0x45: // e
3176 case 0x46: // f
3177 case 0x47: // g
3178 case 0x48: // h
3179 case 0x49: // i
3180 case 0x4a: // j
3181 case 0x4b: // k
3182 case 0x4c: // l
3183 case 0x4d: // m
3184 case 0x4e: // n
3185 case 0x4f: // o
3186 case 0x50: // p
3187 case 0x51: // q
3188 case 0x52: // r
3189 case 0x53: // s
3190 case 0x54: // t
3191 case 0x55: // u
3192 case 0x56: // v
3193 case 0x57: // w
3194 case 0x58: // x
3195 case 0x59: // y
3196 case 0x5a: // z
3197 {
3198 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3199 control_key_state);
3200
3201 // If Alt is pressed, then prefix with escape.
3202 if (_is_alt_pressed(control_key_state)) {
3203 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3204 }
3205 }
3206 break;
3207
3208 // These virtual key codes are generated by the keys on the
3209 // keypad *when NumLock is on* and *Shift is up*.
3210 MATCH(VK_NUMPAD0, "0");
3211 MATCH(VK_NUMPAD1, "1");
3212 MATCH(VK_NUMPAD2, "2");
3213 MATCH(VK_NUMPAD3, "3");
3214 MATCH(VK_NUMPAD4, "4");
3215 MATCH(VK_NUMPAD5, "5");
3216 MATCH(VK_NUMPAD6, "6");
3217 MATCH(VK_NUMPAD7, "7");
3218 MATCH(VK_NUMPAD8, "8");
3219 MATCH(VK_NUMPAD9, "9");
3220
3221 MATCH(VK_MULTIPLY, "*");
3222 MATCH(VK_ADD, "+");
3223 MATCH(VK_SUBTRACT, "-");
3224 // VK_DECIMAL is generated by the . key on the keypad *when
3225 // NumLock is on* and *Shift is up* and the sequence is not
3226 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3227 // Windows Security screen to come up).
3228 case VK_DECIMAL:
3229 // U.S. English uses '.', Germany German uses ','.
3230 seqbuflen = _get_non_control_char(seqbuf, key_event,
3231 control_key_state);
3232 break;
3233
3234 MATCH_MODIFIER(VK_F1, SS3 "P");
3235 MATCH_MODIFIER(VK_F2, SS3 "Q");
3236 MATCH_MODIFIER(VK_F3, SS3 "R");
3237 MATCH_MODIFIER(VK_F4, SS3 "S");
3238 MATCH_MODIFIER(VK_F5, CSI "15~");
3239 MATCH_MODIFIER(VK_F6, CSI "17~");
3240 MATCH_MODIFIER(VK_F7, CSI "18~");
3241 MATCH_MODIFIER(VK_F8, CSI "19~");
3242 MATCH_MODIFIER(VK_F9, CSI "20~");
3243 MATCH_MODIFIER(VK_F10, CSI "21~");
3244 MATCH_MODIFIER(VK_F11, CSI "23~");
3245 MATCH_MODIFIER(VK_F12, CSI "24~");
3246
3247 MATCH_MODIFIER(VK_F13, CSI "25~");
3248 MATCH_MODIFIER(VK_F14, CSI "26~");
3249 MATCH_MODIFIER(VK_F15, CSI "28~");
3250 MATCH_MODIFIER(VK_F16, CSI "29~");
3251 MATCH_MODIFIER(VK_F17, CSI "31~");
3252 MATCH_MODIFIER(VK_F18, CSI "32~");
3253 MATCH_MODIFIER(VK_F19, CSI "33~");
3254 MATCH_MODIFIER(VK_F20, CSI "34~");
3255
3256 // MATCH_MODIFIER(VK_F21, ???);
3257 // MATCH_MODIFIER(VK_F22, ???);
3258 // MATCH_MODIFIER(VK_F23, ???);
3259 // MATCH_MODIFIER(VK_F24, ???);
3260 }
3261 }
3262
3263#undef MATCH
3264#undef MATCH_MODIFIER
3265#undef MATCH_KEYPAD
3266#undef MATCH_MODIFIER_KEYPAD
3267#undef ESC
3268#undef CSI
3269#undef SS3
3270
3271 const char* out;
3272 size_t outlen;
3273
3274 // Check for output in any of:
3275 // * seqstr is set (and strlen can be used to determine the length).
3276 // * seqbuf and seqbuflen are set
3277 // Fallback to ch from Windows.
3278 if (seqstr != NULL) {
3279 out = seqstr;
3280 outlen = strlen(seqstr);
3281 } else if (seqbuflen > 0) {
3282 out = seqbuf;
3283 outlen = seqbuflen;
3284 } else if (ch != '\0') {
3285 // Use whatever Windows told us it is.
3286 seqbuf[0] = ch;
3287 seqbuflen = 1;
3288 out = seqbuf;
3289 outlen = seqbuflen;
3290 } else {
3291 // No special handling for the virtual key code and Windows isn't
3292 // telling us a character code, then we don't know how to translate
3293 // the key press.
3294 //
3295 // Consume the input and 'continue' to cause us to get a new key
3296 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07003297 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08003298 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3299 key_event->wRepeatCount = 0;
3300 continue;
3301 }
3302
3303 int bytesRead = 0;
3304
3305 // put output wRepeatCount times into buf/len
3306 while (key_event->wRepeatCount > 0) {
3307 if (len >= outlen) {
3308 // Write to buf/len
3309 memcpy(buf, out, outlen);
3310 buf = (void*)((char*)buf + outlen);
3311 len -= outlen;
3312 bytesRead += outlen;
3313
3314 // consume the input
3315 --key_event->wRepeatCount;
3316 } else {
3317 // Not enough space, so just leave it in _win32_input_record
3318 // for a subsequent retrieval.
3319 if (bytesRead == 0) {
3320 // We didn't write anything because there wasn't enough
3321 // space to even write one sequence. This should never
3322 // happen if the caller uses sensible buffer sizes
3323 // (i.e. >= maximum sequence length which is probably a
3324 // few bytes long).
3325 D("_console_read: no buffer space to write one sequence; "
3326 "buffer: %ld, sequence: %ld\n", (long)len,
3327 (long)outlen);
3328 errno = ENOMEM;
3329 return -1;
3330 } else {
3331 // Stop trying to write to buf/len, just return whatever
3332 // we wrote so far.
3333 break;
3334 }
3335 }
3336 }
3337
3338 return bytesRead;
3339 }
3340}
3341
3342static DWORD _old_console_mode; // previous GetConsoleMode() result
3343static HANDLE _console_handle; // when set, console mode should be restored
3344
3345void stdin_raw_init(const int fd) {
3346 if (STDIN_FILENO == fd) {
David Pursell58805362015-10-28 14:29:51 -07003347 const HANDLE in = _get_console_handle(fd, &_old_console_mode);
Spencer Lowbeb61982015-03-01 15:06:21 -08003348
3349 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3350 // calling the process Ctrl-C routine (configured by
3351 // SetConsoleCtrlHandler()).
3352 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3353 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3354 // flag also seems necessary to have proper line-ending processing.
3355 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3356 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3357 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003358 D("stdin_raw_init: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003359 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003360 }
3361
3362 // Once this is set, it means that stdin has been configured for
3363 // reading from and that the old console mode should be restored later.
3364 _console_handle = in;
3365
3366 // Note that we don't need to configure C Runtime line-ending
3367 // translation because _console_read() does not call the C Runtime to
3368 // read from the console.
3369 }
3370}
3371
3372void stdin_raw_restore(const int fd) {
3373 if (STDIN_FILENO == fd) {
3374 if (_console_handle != NULL) {
3375 const HANDLE in = _console_handle;
3376 _console_handle = NULL; // clear state
3377
3378 if (!SetConsoleMode(in, _old_console_mode)) {
3379 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003380 D("stdin_raw_restore: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003381 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003382 }
3383 }
3384 }
3385}
3386
Spencer Low3a2421b2015-05-22 20:09:06 -07003387// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003388int unix_read(int fd, void* buf, size_t len) {
3389 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3390 // If it is a request to read from stdin, and stdin_raw_init() has been
3391 // called, and it successfully configured the console, then read from
3392 // the console using Win32 console APIs and partially emulate a unix
3393 // terminal.
3394 return _console_read(_console_handle, buf, len);
3395 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07003396 // On older versions of Windows (definitely 7, definitely not 10),
3397 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07003398 // we need to limit the read size.
3399 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07003400 len = 4096;
3401 }
Spencer Lowbeb61982015-03-01 15:06:21 -08003402 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003403 // can do LF/CR translation (which is overridable with _setmode()).
3404 // Undefine the macro that is set in sysdeps.h which bans calls to
3405 // plain read() in favor of unix_read() or adb_read().
3406#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003407#undef read
3408 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003409#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003410 }
3411}
Spencer Low6815c072015-05-11 01:08:48 -07003412
3413/**************************************************************************/
3414/**************************************************************************/
3415/***** *****/
3416/***** Unicode support *****/
3417/***** *****/
3418/**************************************************************************/
3419/**************************************************************************/
3420
3421// This implements support for using files with Unicode filenames and for
3422// outputting Unicode text to a Win32 console window. This is inspired from
3423// http://utf8everywhere.org/.
3424//
3425// Background
3426// ----------
3427//
3428// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3429// filenames to APIs such as open(). This works because filenames are largely
3430// opaque 'cookies' (perhaps excluding path separators).
3431//
3432// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3433// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3434// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3435// CreateFile() API is really just a macro that adds the W/A based on whether
3436// the UNICODE preprocessor symbol is defined).
3437//
3438// Options
3439// -------
3440//
3441// Thus, to write a portable program, there are a few options:
3442//
3443// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3444// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3445// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3446// open() API.
3447//
3448// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3449// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3450// potentially touching a lot of code.
3451//
3452// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3453// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3454// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3455// or C Runtime API.
3456//
3457// The Choice
3458// ----------
3459//
3460// The code below chooses option 3, the UTF-8 everywhere strategy. It
3461// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3462// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3463// args that are passed to main() at the beginning of program startup. We also
3464// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3465// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3466//
3467// Unicode console output
3468// ----------------------
3469//
3470// The way to output Unicode to a Win32 console window is to call
3471// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003472// such as Lucida Console or Consolas, and in the case of East Asian languages
3473// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3474// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3475// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003476//
3477// The problem is getting the C Runtime to make fprintf and related APIs call
3478// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3479// promising, but the various modes have issues:
3480//
3481// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3482// UTF-16 do not display properly.
3483// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3484// totally wrong.
3485// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3486// handler to be called (upon a later I/O call), aborting the process.
3487// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3488// to output nothing.
3489//
3490// So the only solution is to write our own adb_fprintf() that converts UTF-8
3491// to UTF-16 and then calls WriteConsoleW().
3492
3493
3494// Function prototype because attributes cannot be placed on func definitions.
3495static void _widen_fatal(const char *fmt, ...)
3496 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3497
3498// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3499// called from those functions.
3500static void _widen_fatal(const char *fmt, ...) {
3501 va_list ap;
3502 va_start(ap, fmt);
3503 // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3504 // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3505 // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3506 // By directly calling real C Runtime APIs that don't properly output
3507 // Unicode, but will be able to get a comprehendible message out. To do
3508 // this, make sure we don't call (v)fprintf macros by undefining them.
3509#pragma push_macro("fprintf")
3510#pragma push_macro("vfprintf")
3511#undef fprintf
3512#undef vfprintf
3513 fprintf(stderr, "error: ");
3514 vfprintf(stderr, fmt, ap);
3515 fprintf(stderr, "\n");
3516#pragma pop_macro("vfprintf")
3517#pragma pop_macro("fprintf")
3518 va_end(ap);
3519 exit(-1);
3520}
3521
3522// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3523// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3524
3525// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3526// string. Any other size specifies the number of chars to convert, excluding
3527// any NULL terminator (if you're passing an explicit size, you probably don't
3528// have a NULL terminated string in the first place).
3529std::wstring widen(const char* utf8, const int size) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003530 // Note: Do not call SystemErrorCodeToString() from widen() because
3531 // SystemErrorCodeToString() calls narrow() which may call fatal() which
3532 // calls adb_vfprintf() which calls widen(), potentially causing infinite
3533 // recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003534 const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3535 NULL, 0);
3536 if (chars_to_convert <= 0) {
3537 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3538 _widen_fatal("MultiByteToWideChar failed counting: %d, "
3539 "GetLastError: %lu", chars_to_convert, GetLastError());
3540 }
3541
3542 std::wstring utf16;
3543 size_t chars_to_allocate = chars_to_convert;
3544 if (size == -1) {
3545 // chars_to_convert includes a NULL terminator, so subtract space
3546 // for that because resize() includes that itself.
3547 --chars_to_allocate;
3548 }
3549 utf16.resize(chars_to_allocate);
3550
3551 // This uses &string[0] to get write-access to the entire string buffer
3552 // which may be assuming that the chars are all contiguous, but it seems
3553 // to work and saves us the hassle of using a temporary
3554 // std::vector<wchar_t>.
3555 const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3556 chars_to_convert);
3557 if (result != chars_to_convert) {
3558 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3559 _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3560 "GetLastError: %lu", result, GetLastError());
3561 }
3562
3563 // If a size was passed in (size != -1), then the string is NULL terminated
3564 // by a NULL char that was written by std::string::resize(). If size == -1,
3565 // then MultiByteToWideChar() read a NULL terminator from the original
3566 // string and converted it to a NULL UTF-16 char in the output.
3567
3568 return utf16;
3569}
3570
3571// Convert a NULL terminated string from UTF-8 to UTF-16.
3572std::wstring widen(const char* utf8) {
3573 // Pass -1 to let widen() determine the string length.
3574 return widen(utf8, -1);
3575}
3576
3577// Convert from UTF-8 to UTF-16.
3578std::wstring widen(const std::string& utf8) {
3579 return widen(utf8.c_str(), utf8.length());
3580}
3581
3582// Convert from UTF-16 to UTF-8.
3583std::string narrow(const std::wstring& utf16) {
3584 return narrow(utf16.c_str());
3585}
3586
3587// Convert from UTF-16 to UTF-8.
3588std::string narrow(const wchar_t* utf16) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003589 // Note: Do not call SystemErrorCodeToString() from narrow() because
Elliott Hughes1ba53092015-08-03 16:26:13 -07003590 // SystemErrorCodeToString() calls narrow() and we don't want potential
Spencer Lowcc467f12015-08-02 18:13:54 -07003591 // infinite recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003592 const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3593 0, NULL, NULL);
3594 if (chars_required <= 0) {
3595 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003596 fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003597 chars_required, GetLastError());
3598 }
3599
3600 std::string utf8;
3601 // Subtract space for the NULL terminator because resize() includes
3602 // that itself. Note that this could potentially throw a std::bad_alloc
3603 // exception.
3604 utf8.resize(chars_required - 1);
3605
3606 // This uses &string[0] to get write-access to the entire string buffer
3607 // which may be assuming that the chars are all contiguous, but it seems
3608 // to work and saves us the hassle of using a temporary
3609 // std::vector<char>.
3610 const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3611 chars_required, NULL, NULL);
3612 if (result != chars_required) {
3613 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003614 fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003615 result, GetLastError());
3616 }
3617
3618 return utf8;
3619}
3620
3621// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3622// be passed to main().
3623NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3624 narrow_args = new char*[argc + 1];
3625
3626 for (int i = 0; i < argc; ++i) {
3627 narrow_args[i] = strdup(narrow(argv[i]).c_str());
3628 }
3629 narrow_args[argc] = nullptr; // terminate
3630}
3631
3632NarrowArgs::~NarrowArgs() {
3633 if (narrow_args != nullptr) {
3634 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3635 free(*argp);
3636 }
3637 delete[] narrow_args;
3638 narrow_args = nullptr;
3639 }
3640}
3641
3642int unix_open(const char* path, int options, ...) {
3643 if ((options & O_CREAT) == 0) {
3644 return _wopen(widen(path).c_str(), options);
3645 } else {
3646 int mode;
3647 va_list args;
3648 va_start(args, options);
3649 mode = va_arg(args, int);
3650 va_end(args);
3651 return _wopen(widen(path).c_str(), options, mode);
3652 }
3653}
3654
3655// Version of stat() that takes a UTF-8 path.
3656int adb_stat(const char* f, struct adb_stat* s) {
3657#pragma push_macro("wstat")
3658// This definition of wstat seems to be missing from <sys/stat.h>.
3659#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3660#ifdef _USE_32BIT_TIME_T
3661#define wstat _wstat32i64
3662#else
3663#define wstat _wstat64
3664#endif
3665#else
3666// <sys/stat.h> has a function prototype for wstat() that should be available.
3667#endif
3668
3669 return wstat(widen(f).c_str(), s);
3670
3671#pragma pop_macro("wstat")
3672}
3673
3674// Version of opendir() that takes a UTF-8 path.
3675DIR* adb_opendir(const char* name) {
3676 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3677 // the fields, but right now all the callers treat the structure as
3678 // opaque.
3679 return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3680}
3681
3682// Version of readdir() that returns UTF-8 paths.
3683struct dirent* adb_readdir(DIR* dir) {
3684 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3685 struct _wdirent* const went = _wreaddir(wdir);
3686 if (went == nullptr) {
3687 return nullptr;
3688 }
3689 // Convert from UTF-16 to UTF-8.
3690 const std::string name_utf8(narrow(went->d_name));
3691
3692 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3693 // space for UTF-16 wchar_t's) with UTF-8 char's.
3694 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3695
3696 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3697 // Name too big to fit in existing buffer.
3698 errno = ENOMEM;
3699 return nullptr;
3700 }
3701
3702 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3703 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3704 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3705 // bigger than the caller expects because they expect a dirent structure
3706 // which has a smaller d_name field. Ignore this since the caller should be
3707 // resilient.
3708
3709 // Rewrite the UTF-16 d_name field to UTF-8.
3710 strcpy(ent->d_name, name_utf8.c_str());
3711
3712 return ent;
3713}
3714
3715// Version of closedir() to go with our version of adb_opendir().
3716int adb_closedir(DIR* dir) {
3717 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3718}
3719
3720// Version of unlink() that takes a UTF-8 path.
3721int adb_unlink(const char* path) {
3722 const std::wstring wpath(widen(path));
3723
3724 int rc = _wunlink(wpath.c_str());
3725
3726 if (rc == -1 && errno == EACCES) {
3727 /* unlink returns EACCES when the file is read-only, so we first */
3728 /* try to make it writable, then unlink again... */
3729 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3730 if (rc == 0)
3731 rc = _wunlink(wpath.c_str());
3732 }
3733 return rc;
3734}
3735
3736// Version of mkdir() that takes a UTF-8 path.
3737int adb_mkdir(const std::string& path, int mode) {
3738 return _wmkdir(widen(path.c_str()).c_str());
3739}
3740
3741// Version of utime() that takes a UTF-8 path.
3742int adb_utime(const char* path, struct utimbuf* u) {
3743 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3744 "utimbuf and _utimbuf should be the same size because they both "
3745 "contain the same types, namely time_t");
3746 return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3747}
3748
3749// Version of chmod() that takes a UTF-8 path.
3750int adb_chmod(const char* path, int mode) {
3751 return _wchmod(widen(path).c_str(), mode);
3752}
3753
Spencer Low6815c072015-05-11 01:08:48 -07003754// Internal helper function to write UTF-8 bytes to a console. Returns -1
3755// on error.
3756static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3757 HANDLE console) {
3758 // Convert from UTF-8 to UTF-16.
3759 // This could throw std::bad_alloc.
3760 const std::wstring output(widen(buf, size));
3761
3762 // Note that this does not do \n => \r\n translation because that
3763 // doesn't seem necessary for the Windows console. For the Windows
3764 // console \r moves to the beginning of the line and \n moves to a new
3765 // line.
3766
3767 // Flush any stream buffering so that our output is afterwards which
3768 // makes sense because our call is afterwards.
3769 (void)fflush(stream);
3770
3771 // Write UTF-16 to the console.
3772 DWORD written = 0;
3773 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3774 NULL)) {
3775 errno = EIO;
3776 return -1;
3777 }
3778
3779 // This is the number of UTF-16 chars written, which might be different
3780 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3781 // get this count correct.
3782 return written;
3783}
3784
3785// Function prototype because attributes cannot be placed on func definitions.
3786static int _console_vfprintf(const HANDLE console, FILE* stream,
3787 const char *format, va_list ap)
3788 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3789
3790// Internal function to format a UTF-8 string and write it to a Win32 console.
3791// Returns -1 on error.
3792static int _console_vfprintf(const HANDLE console, FILE* stream,
3793 const char *format, va_list ap) {
3794 std::string output_utf8;
3795
3796 // Format the string.
3797 // This could throw std::bad_alloc.
3798 android::base::StringAppendV(&output_utf8, format, ap);
3799
3800 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3801 stream, console);
3802}
3803
3804// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3805// Windows console.
3806int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3807 const HANDLE console = _get_console_handle(stream);
3808
3809 // If there is an associated Win32 console, write to it specially,
3810 // otherwise defer to the regular C Runtime, passing it UTF-8.
3811 if (console != NULL) {
3812 return _console_vfprintf(console, stream, format, ap);
3813 } else {
3814 // If vfprintf is a macro, undefine it, so we can call the real
3815 // C Runtime API.
3816#pragma push_macro("vfprintf")
3817#undef vfprintf
3818 return vfprintf(stream, format, ap);
3819#pragma pop_macro("vfprintf")
3820 }
3821}
3822
3823// Version of fprintf() that takes UTF-8 and can write Unicode to a
3824// Windows console.
3825int adb_fprintf(FILE *stream, const char *format, ...) {
3826 va_list ap;
3827 va_start(ap, format);
3828 const int result = adb_vfprintf(stream, format, ap);
3829 va_end(ap);
3830
3831 return result;
3832}
3833
3834// Version of printf() that takes UTF-8 and can write Unicode to a
3835// Windows console.
3836int adb_printf(const char *format, ...) {
3837 va_list ap;
3838 va_start(ap, format);
3839 const int result = adb_vfprintf(stdout, format, ap);
3840 va_end(ap);
3841
3842 return result;
3843}
3844
3845// Version of fputs() that takes UTF-8 and can write Unicode to a
3846// Windows console.
3847int adb_fputs(const char* buf, FILE* stream) {
3848 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3849 // which fputs (and hence adb_fputs) should return on error.
3850 return adb_fprintf(stream, "%s", buf);
3851}
3852
3853// Version of fputc() that takes UTF-8 and can write Unicode to a
3854// Windows console.
3855int adb_fputc(int ch, FILE* stream) {
3856 const int result = adb_fprintf(stream, "%c", ch);
3857 if (result <= 0) {
3858 // If there was an error, or if nothing was printed (which should be an
3859 // error), return an error, which fprintf signifies with EOF.
3860 return EOF;
3861 }
3862 // For success, fputc returns the char, cast to unsigned char, then to int.
3863 return static_cast<unsigned char>(ch);
3864}
3865
3866// Internal function to write UTF-8 to a Win32 console. Returns the number of
3867// items (of length size) written. On error, returns a short item count or 0.
3868static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3869 FILE* stream, HANDLE console) {
3870 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3871 // if we're passed only some of the bytes of a character (for example, from
3872 // the network socket for adb shell), we won't be able to convert the char
3873 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3874 // right.
3875 //
3876 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3877 //
3878 // For now we ignore this problem because the alternative is that we'd have
3879 // to parse UTF-8 and buffer things up (doable). At least this is better
3880 // than what we had before -- always incorrect multi-byte UTF-8 output.
3881 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3882 size * nmemb, stream, console);
3883 if (result == -1) {
3884 return 0;
3885 }
3886 return result / size;
3887}
3888
3889// Version of fwrite() that takes UTF-8 and can write Unicode to a
3890// Windows console.
3891size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3892 const HANDLE console = _get_console_handle(stream);
3893
3894 // If there is an associated Win32 console, write to it specially,
3895 // otherwise defer to the regular C Runtime, passing it UTF-8.
3896 if (console != NULL) {
3897 return _console_fwrite(ptr, size, nmemb, stream, console);
3898 } else {
3899 // If fwrite is a macro, undefine it, so we can call the real
3900 // C Runtime API.
3901#pragma push_macro("fwrite")
3902#undef fwrite
3903 return fwrite(ptr, size, nmemb, stream);
3904#pragma pop_macro("fwrite")
3905 }
3906}
3907
3908// Version of fopen() that takes a UTF-8 filename and can access a file with
3909// a Unicode filename.
3910FILE* adb_fopen(const char* f, const char* m) {
3911 return _wfopen(widen(f).c_str(), widen(m).c_str());
3912}
3913
Spencer Low50740f52015-09-08 17:13:04 -07003914// Return a lowercase version of the argument. Uses C Runtime tolower() on
3915// each byte which is not UTF-8 aware, and theoretically uses the current C
3916// Runtime locale (which in practice is not changed, so this becomes a ASCII
3917// conversion).
3918static std::string ToLower(const std::string& anycase) {
3919 // copy string
3920 std::string str(anycase);
3921 // transform the copy
3922 std::transform(str.begin(), str.end(), str.begin(), tolower);
3923 return str;
3924}
3925
3926extern "C" int main(int argc, char** argv);
3927
3928// Link with -municode to cause this wmain() to be used as the program
3929// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3930// regular main() with UTF-8 args.
3931extern "C" int wmain(int argc, wchar_t **argv) {
3932 // Convert args from UTF-16 to UTF-8 and pass that to main().
3933 NarrowArgs narrow_args(argc, argv);
3934 return main(argc, narrow_args.data());
3935}
3936
Spencer Low6815c072015-05-11 01:08:48 -07003937// Shadow UTF-8 environment variable name/value pairs that are created from
3938// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003939// currently updated if putenv, setenv, unsetenv are called. Note that no
3940// thread synchronization is done, but we're called early enough in
3941// single-threaded startup that things work ok.
Spencer Low6815c072015-05-11 01:08:48 -07003942static std::unordered_map<std::string, char*> g_environ_utf8;
3943
3944// Make sure that shadow UTF-8 environment variables are setup.
3945static void _ensure_env_setup() {
3946 // If some name/value pairs exist, then we've already done the setup below.
3947 if (g_environ_utf8.size() != 0) {
3948 return;
3949 }
3950
Spencer Low50740f52015-09-08 17:13:04 -07003951 if (_wenviron == nullptr) {
3952 // If _wenviron is null, then -municode probably wasn't used. That
3953 // linker flag will cause the entry point to setup _wenviron. It will
3954 // also require an implementation of wmain() (which we provide above).
3955 fatal("_wenviron is not set, did you link with -municode?");
3956 }
3957
Spencer Low6815c072015-05-11 01:08:48 -07003958 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3959 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3960 // to use the D() macro here because that tracing only works if the
3961 // ADB_TRACE environment variable is setup, but that env var can't be read
3962 // until this code completes.
3963 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3964 wchar_t* const equal = wcschr(*env, L'=');
3965 if (equal == nullptr) {
3966 // Malformed environment variable with no equal sign. Shouldn't
3967 // really happen, but we should be resilient to this.
3968 continue;
3969 }
3970
Spencer Low50740f52015-09-08 17:13:04 -07003971 // Store lowercase name so that we can do case-insensitive searches.
3972 const std::string name_utf8(ToLower(narrow(
3973 std::wstring(*env, equal - *env))));
Spencer Low6815c072015-05-11 01:08:48 -07003974 char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3975
Spencer Low50740f52015-09-08 17:13:04 -07003976 // Don't overwrite a previus env var with the same name. In reality,
3977 // the system probably won't let two env vars with the same name exist
3978 // in _wenviron.
3979 g_environ_utf8.insert({name_utf8, value_utf8});
Spencer Low6815c072015-05-11 01:08:48 -07003980 }
3981}
3982
3983// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07003984// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07003985char* adb_getenv(const char* name) {
3986 _ensure_env_setup();
3987
Spencer Low50740f52015-09-08 17:13:04 -07003988 // Case-insensitive search by searching for lowercase name in a map of
3989 // lowercase names.
3990 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07003991 if (it == g_environ_utf8.end()) {
3992 return nullptr;
3993 }
3994
3995 return it->second;
3996}
3997
3998// Version of getcwd() that returns the current working directory in UTF-8.
3999char* adb_getcwd(char* buf, int size) {
4000 wchar_t* wbuf = _wgetcwd(nullptr, 0);
4001 if (wbuf == nullptr) {
4002 return nullptr;
4003 }
4004
4005 const std::string buf_utf8(narrow(wbuf));
4006 free(wbuf);
4007 wbuf = nullptr;
4008
4009 // If size was specified, make sure all the chars will fit.
4010 if (size != 0) {
4011 if (size < static_cast<int>(buf_utf8.length() + 1)) {
4012 errno = ERANGE;
4013 return nullptr;
4014 }
4015 }
4016
4017 // If buf was not specified, allocate storage.
4018 if (buf == nullptr) {
4019 if (size == 0) {
4020 size = buf_utf8.length() + 1;
4021 }
4022 buf = reinterpret_cast<char*>(malloc(size));
4023 if (buf == nullptr) {
4024 return nullptr;
4025 }
4026 }
4027
4028 // Destination buffer was allocated with enough space, or we've already
4029 // checked an existing buffer size for enough space.
4030 strcpy(buf, buf_utf8.c_str());
4031
4032 return buf;
4033}