blob: 14d13758536bdf51722e28facfaacb92ce88e342 [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//
2502// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2503// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2504// * _console_read() is the main code of the emulation.
2505
2506
2507// Read an input record from the console; one that should be processed.
2508static bool _get_interesting_input_record_uncached(const HANDLE console,
2509 INPUT_RECORD* const input_record) {
2510 for (;;) {
2511 DWORD read_count = 0;
2512 memset(input_record, 0, sizeof(*input_record));
2513 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2514 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
Spencer Low1711e012015-08-02 18:50:17 -07002515 "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002516 errno = EIO;
2517 return false;
2518 }
2519
2520 if (read_count == 0) { // should be impossible
2521 fatal("ReadConsoleInputA returned 0");
2522 }
2523
2524 if (read_count != 1) { // should be impossible
2525 fatal("ReadConsoleInputA did not return one input record");
2526 }
2527
2528 if ((input_record->EventType == KEY_EVENT) &&
2529 (input_record->Event.KeyEvent.bKeyDown)) {
2530 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2531 fatal("ReadConsoleInputA returned a key event with zero repeat"
2532 " count");
2533 }
2534
2535 // Got an interesting INPUT_RECORD, so return
2536 return true;
2537 }
2538 }
2539}
2540
2541// Cached input record (in case _console_read() is passed a buffer that doesn't
2542// have enough space to fit wRepeatCount number of key sequences). A non-zero
2543// wRepeatCount indicates that a record is cached.
2544static INPUT_RECORD _win32_input_record;
2545
2546// Get the next KEY_EVENT_RECORD that should be processed.
2547static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2548 // If nothing cached, read directly from the console until we get an
2549 // interesting record.
2550 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2551 if (!_get_interesting_input_record_uncached(console,
2552 &_win32_input_record)) {
2553 // There was an error, so make sure wRepeatCount is zero because
2554 // that signifies no cached input record.
2555 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2556 return NULL;
2557 }
2558 }
2559
2560 return &_win32_input_record.Event.KeyEvent;
2561}
2562
2563static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2564 return (control_key_state & SHIFT_PRESSED) != 0;
2565}
2566
2567static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2568 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2569}
2570
2571static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2572 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2573}
2574
2575static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2576 return (control_key_state & NUMLOCK_ON) != 0;
2577}
2578
2579static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2580 return (control_key_state & CAPSLOCK_ON) != 0;
2581}
2582
2583static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2584 return (control_key_state & ENHANCED_KEY) != 0;
2585}
2586
2587// Constants from MSDN for ToAscii().
2588static const BYTE TOASCII_KEY_OFF = 0x00;
2589static const BYTE TOASCII_KEY_DOWN = 0x80;
2590static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2591
2592// Given a key event, ignore a modifier key and return the character that was
2593// entered without the modifier. Writes to *ch and returns the number of bytes
2594// written.
2595static size_t _get_char_ignoring_modifier(char* const ch,
2596 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2597 const WORD modifier) {
2598 // If there is no character from Windows, try ignoring the specified
2599 // modifier and look for a character. Note that if AltGr is being used,
2600 // there will be a character from Windows.
2601 if (key_event->uChar.AsciiChar == '\0') {
2602 // Note that we read the control key state from the passed in argument
2603 // instead of from key_event since the argument has been normalized.
2604 if (((modifier == VK_SHIFT) &&
2605 _is_shift_pressed(control_key_state)) ||
2606 ((modifier == VK_CONTROL) &&
2607 _is_ctrl_pressed(control_key_state)) ||
2608 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2609
2610 BYTE key_state[256] = {0};
2611 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2612 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2613 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2614 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2615 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2616 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2617 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2618 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2619
2620 // cause this modifier to be ignored
2621 key_state[modifier] = TOASCII_KEY_OFF;
2622
2623 WORD translated = 0;
2624 if (ToAscii(key_event->wVirtualKeyCode,
2625 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2626 // Ignoring the modifier, we found a character.
2627 *ch = (CHAR)translated;
2628 return 1;
2629 }
2630 }
2631 }
2632
2633 // Just use whatever Windows told us originally.
2634 *ch = key_event->uChar.AsciiChar;
2635
2636 // If the character from Windows is NULL, return a size of zero.
2637 return (*ch == '\0') ? 0 : 1;
2638}
2639
2640// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2641// but taking into account the shift key. This is because for a sequence like
2642// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2643// we want to find the character ')'.
2644//
2645// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2646// because it is the default key-sequence to switch the input language.
2647// This is configurable in the Region and Language control panel.
2648static __inline__ size_t _get_non_control_char(char* const ch,
2649 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2650 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2651 VK_CONTROL);
2652}
2653
2654// Get without Alt.
2655static __inline__ size_t _get_non_alt_char(char* const ch,
2656 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2657 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2658 VK_MENU);
2659}
2660
2661// Ignore the control key, find the character from Windows, and apply any
2662// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2663// *pch and returns number of bytes written.
2664static size_t _get_control_character(char* const pch,
2665 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2666 const size_t len = _get_non_control_char(pch, key_event,
2667 control_key_state);
2668
2669 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2670 char ch = *pch;
2671 switch (ch) {
2672 case '2':
2673 case '@':
2674 case '`':
2675 ch = '\0';
2676 break;
2677 case '3':
2678 case '[':
2679 case '{':
2680 ch = '\x1b';
2681 break;
2682 case '4':
2683 case '\\':
2684 case '|':
2685 ch = '\x1c';
2686 break;
2687 case '5':
2688 case ']':
2689 case '}':
2690 ch = '\x1d';
2691 break;
2692 case '6':
2693 case '^':
2694 case '~':
2695 ch = '\x1e';
2696 break;
2697 case '7':
2698 case '-':
2699 case '_':
2700 ch = '\x1f';
2701 break;
2702 case '8':
2703 ch = '\x7f';
2704 break;
2705 case '/':
2706 if (!_is_alt_pressed(control_key_state)) {
2707 ch = '\x1f';
2708 }
2709 break;
2710 case '?':
2711 if (!_is_alt_pressed(control_key_state)) {
2712 ch = '\x7f';
2713 }
2714 break;
2715 }
2716 *pch = ch;
2717 }
2718
2719 return len;
2720}
2721
2722static DWORD _normalize_altgr_control_key_state(
2723 const KEY_EVENT_RECORD* const key_event) {
2724 DWORD control_key_state = key_event->dwControlKeyState;
2725
2726 // If we're in an AltGr situation where the AltGr key is down (depending on
2727 // the keyboard layout, that might be the physical right alt key which
2728 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2729 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2730 // a character (which indicates that there was an AltGr mapping), then act
2731 // as if alt and control are not really down for the purposes of modifiers.
2732 // This makes it so that if the user with, say, a German keyboard layout
2733 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2734 // output the key and we don't see the Alt and Ctrl keys.
2735 if (_is_ctrl_pressed(control_key_state) &&
2736 _is_alt_pressed(control_key_state)
2737 && (key_event->uChar.AsciiChar != '\0')) {
2738 // Try to remove as few bits as possible to improve our chances of
2739 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2740 // Left-Alt + Right-Ctrl + AltGr.
2741 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2742 // Remove Right-Alt.
2743 control_key_state &= ~RIGHT_ALT_PRESSED;
2744 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2745 // pressed, Left-Ctrl is almost always set, except if the user
2746 // presses Right-Ctrl, then AltGr (in that specific order) for
2747 // whatever reason. At any rate, make sure the bit is not set.
2748 control_key_state &= ~LEFT_CTRL_PRESSED;
2749 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2750 // Remove Left-Alt.
2751 control_key_state &= ~LEFT_ALT_PRESSED;
2752 // Whichever Ctrl key is down, remove it from the state. We only
2753 // remove one key, to improve our chances of detecting the
2754 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2755 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2756 // Remove Left-Ctrl.
2757 control_key_state &= ~LEFT_CTRL_PRESSED;
2758 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2759 // Remove Right-Ctrl.
2760 control_key_state &= ~RIGHT_CTRL_PRESSED;
2761 }
2762 }
2763
2764 // Note that this logic isn't 100% perfect because Windows doesn't
2765 // allow us to detect all combinations because a physical AltGr key
2766 // press shows up as two bits, plus some combinations are ambiguous
2767 // about what is actually physically pressed.
2768 }
2769
2770 return control_key_state;
2771}
2772
2773// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2774// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2775// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2776// appropriately.
2777static DWORD _normalize_keypad_control_key_state(const WORD vk,
2778 const DWORD control_key_state) {
2779 if (!_is_numlock_on(control_key_state)) {
2780 return control_key_state;
2781 }
2782 if (!_is_enhanced_key(control_key_state)) {
2783 switch (vk) {
2784 case VK_INSERT: // 0
2785 case VK_DELETE: // .
2786 case VK_END: // 1
2787 case VK_DOWN: // 2
2788 case VK_NEXT: // 3
2789 case VK_LEFT: // 4
2790 case VK_CLEAR: // 5
2791 case VK_RIGHT: // 6
2792 case VK_HOME: // 7
2793 case VK_UP: // 8
2794 case VK_PRIOR: // 9
2795 return control_key_state | SHIFT_PRESSED;
2796 }
2797 }
2798
2799 return control_key_state;
2800}
2801
2802static const char* _get_keypad_sequence(const DWORD control_key_state,
2803 const char* const normal, const char* const shifted) {
2804 if (_is_shift_pressed(control_key_state)) {
2805 // Shift is pressed and NumLock is off
2806 return shifted;
2807 } else {
2808 // Shift is not pressed and NumLock is off, or,
2809 // Shift is pressed and NumLock is on, in which case we want the
2810 // NumLock and Shift to neutralize each other, thus, we want the normal
2811 // sequence.
2812 return normal;
2813 }
2814 // If Shift is not pressed and NumLock is on, a different virtual key code
2815 // is returned by Windows, which can be taken care of by a different case
2816 // statement in _console_read().
2817}
2818
2819// Write sequence to buf and return the number of bytes written.
2820static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2821 DWORD control_key_state, const char* const normal) {
2822 // Copy the base sequence into buf.
2823 const size_t len = strlen(normal);
2824 memcpy(buf, normal, len);
2825
2826 int code = 0;
2827
2828 control_key_state = _normalize_keypad_control_key_state(vk,
2829 control_key_state);
2830
2831 if (_is_shift_pressed(control_key_state)) {
2832 code |= 0x1;
2833 }
2834 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2835 code |= 0x2;
2836 }
2837 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2838 code |= 0x4;
2839 }
2840 // If some modifier was held down, then we need to insert the modifier code
2841 if (code != 0) {
2842 if (len == 0) {
2843 // Should be impossible because caller should pass a string of
2844 // non-zero length.
2845 return 0;
2846 }
2847 size_t index = len - 1;
2848 const char lastChar = buf[index];
2849 if (lastChar != '~') {
2850 buf[index++] = '1';
2851 }
2852 buf[index++] = ';'; // modifier separator
2853 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2854 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2855 buf[index++] = '1' + code;
2856 buf[index++] = lastChar; // move ~ (or other last char) to the end
2857 return index;
2858 }
2859 return len;
2860}
2861
2862// Write sequence to buf and return the number of bytes written.
2863static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2864 const DWORD control_key_state, const char* const normal,
2865 const char shifted) {
2866 if (_is_shift_pressed(control_key_state)) {
2867 // Shift is pressed and NumLock is off
2868 if (shifted != '\0') {
2869 buf[0] = shifted;
2870 return sizeof(buf[0]);
2871 } else {
2872 return 0;
2873 }
2874 } else {
2875 // Shift is not pressed and NumLock is off, or,
2876 // Shift is pressed and NumLock is on, in which case we want the
2877 // NumLock and Shift to neutralize each other, thus, we want the normal
2878 // sequence.
2879 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2880 }
2881 // If Shift is not pressed and NumLock is on, a different virtual key code
2882 // is returned by Windows, which can be taken care of by a different case
2883 // statement in _console_read().
2884}
2885
2886// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2887// Standard German. Figure this out at runtime so we know what to output for
2888// Shift-VK_DELETE.
2889static char _get_decimal_char() {
2890 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2891}
2892
2893// Prefix the len bytes in buf with the escape character, and then return the
2894// new buffer length.
2895size_t _escape_prefix(char* const buf, const size_t len) {
2896 // If nothing to prefix, don't do anything. We might be called with
2897 // len == 0, if alt was held down with a dead key which produced nothing.
2898 if (len == 0) {
2899 return 0;
2900 }
2901
2902 memmove(&buf[1], buf, len);
2903 buf[0] = '\x1b';
2904 return len + 1;
2905}
2906
2907// Writes to buffer buf (of length len), returning number of bytes written or
2908// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2909// (as far as I can tell).
2910static int _console_read(const HANDLE console, void* buf, size_t len) {
2911 for (;;) {
2912 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2913 if (key_event == NULL) {
2914 return -1;
2915 }
2916
2917 const WORD vk = key_event->wVirtualKeyCode;
2918 const CHAR ch = key_event->uChar.AsciiChar;
2919 const DWORD control_key_state = _normalize_altgr_control_key_state(
2920 key_event);
2921
2922 // The following emulation code should write the output sequence to
2923 // either seqstr or to seqbuf and seqbuflen.
2924 const char* seqstr = NULL; // NULL terminated C-string
2925 // Enough space for max sequence string below, plus modifiers and/or
2926 // escape prefix.
2927 char seqbuf[16];
2928 size_t seqbuflen = 0; // Space used in seqbuf.
2929
2930#define MATCH(vk, normal) \
2931 case (vk): \
2932 { \
2933 seqstr = (normal); \
2934 } \
2935 break;
2936
2937 // Modifier keys should affect the output sequence.
2938#define MATCH_MODIFIER(vk, normal) \
2939 case (vk): \
2940 { \
2941 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2942 control_key_state, (normal)); \
2943 } \
2944 break;
2945
2946 // The shift key should affect the output sequence.
2947#define MATCH_KEYPAD(vk, normal, shifted) \
2948 case (vk): \
2949 { \
2950 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2951 (shifted)); \
2952 } \
2953 break;
2954
2955 // The shift key and other modifier keys should affect the output
2956 // sequence.
2957#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2958 case (vk): \
2959 { \
2960 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2961 control_key_state, (normal), (shifted)); \
2962 } \
2963 break;
2964
2965#define ESC "\x1b"
2966#define CSI ESC "["
2967#define SS3 ESC "O"
2968
2969 // Only support normal mode, not application mode.
2970
2971 // Enhanced keys:
2972 // * 6-pack: insert, delete, home, end, page up, page down
2973 // * cursor keys: up, down, right, left
2974 // * keypad: divide, enter
2975 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2976 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2977 if (_is_enhanced_key(control_key_state)) {
2978 switch (vk) {
2979 case VK_RETURN: // Enter key on keypad
2980 if (_is_ctrl_pressed(control_key_state)) {
2981 seqstr = "\n";
2982 } else {
2983 seqstr = "\r";
2984 }
2985 break;
2986
2987 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2988 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2989
2990 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2991 // will be fixed soon to match xterm which sends CSI "F" and
2992 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2993 MATCH(VK_END, CSI "F");
2994 MATCH(VK_HOME, CSI "H");
2995
2996 MATCH_MODIFIER(VK_LEFT, CSI "D");
2997 MATCH_MODIFIER(VK_UP, CSI "A");
2998 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2999 MATCH_MODIFIER(VK_DOWN, CSI "B");
3000
3001 MATCH_MODIFIER(VK_INSERT, CSI "2~");
3002 MATCH_MODIFIER(VK_DELETE, CSI "3~");
3003
3004 MATCH(VK_DIVIDE, "/");
3005 }
3006 } else { // Non-enhanced keys:
3007 switch (vk) {
3008 case VK_BACK: // backspace
3009 if (_is_alt_pressed(control_key_state)) {
3010 seqstr = ESC "\x7f";
3011 } else {
3012 seqstr = "\x7f";
3013 }
3014 break;
3015
3016 case VK_TAB:
3017 if (_is_shift_pressed(control_key_state)) {
3018 seqstr = CSI "Z";
3019 } else {
3020 seqstr = "\t";
3021 }
3022 break;
3023
3024 // Number 5 key in keypad when NumLock is off, or if NumLock is
3025 // on and Shift is down.
3026 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
3027
3028 case VK_RETURN: // Enter key on main keyboard
3029 if (_is_alt_pressed(control_key_state)) {
3030 seqstr = ESC "\n";
3031 } else if (_is_ctrl_pressed(control_key_state)) {
3032 seqstr = "\n";
3033 } else {
3034 seqstr = "\r";
3035 }
3036 break;
3037
3038 // VK_ESCAPE: Don't do any special handling. The OS uses many
3039 // of the sequences with Escape and many of the remaining
3040 // sequences don't produce bKeyDown messages, only !bKeyDown
3041 // for whatever reason.
3042
3043 case VK_SPACE:
3044 if (_is_alt_pressed(control_key_state)) {
3045 seqstr = ESC " ";
3046 } else if (_is_ctrl_pressed(control_key_state)) {
3047 seqbuf[0] = '\0'; // NULL char
3048 seqbuflen = 1;
3049 } else {
3050 seqstr = " ";
3051 }
3052 break;
3053
3054 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
3055 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
3056
3057 MATCH_KEYPAD(VK_END, CSI "4~", "1");
3058 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
3059
3060 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
3061 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
3062 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
3063 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
3064
3065 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
3066 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
3067 _get_decimal_char());
3068
3069 case 0x30: // 0
3070 case 0x31: // 1
3071 case 0x39: // 9
3072 case VK_OEM_1: // ;:
3073 case VK_OEM_PLUS: // =+
3074 case VK_OEM_COMMA: // ,<
3075 case VK_OEM_PERIOD: // .>
3076 case VK_OEM_7: // '"
3077 case VK_OEM_102: // depends on keyboard, could be <> or \|
3078 case VK_OEM_2: // /?
3079 case VK_OEM_3: // `~
3080 case VK_OEM_4: // [{
3081 case VK_OEM_5: // \|
3082 case VK_OEM_6: // ]}
3083 {
3084 seqbuflen = _get_control_character(seqbuf, key_event,
3085 control_key_state);
3086
3087 if (_is_alt_pressed(control_key_state)) {
3088 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3089 }
3090 }
3091 break;
3092
3093 case 0x32: // 2
3094 case 0x36: // 6
3095 case VK_OEM_MINUS: // -_
3096 {
3097 seqbuflen = _get_control_character(seqbuf, key_event,
3098 control_key_state);
3099
3100 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3101 // prefix with escape.
3102 if (_is_alt_pressed(control_key_state) &&
3103 !(_is_ctrl_pressed(control_key_state) &&
3104 !_is_shift_pressed(control_key_state))) {
3105 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3106 }
3107 }
3108 break;
3109
3110 case 0x33: // 3
3111 case 0x34: // 4
3112 case 0x35: // 5
3113 case 0x37: // 7
3114 case 0x38: // 8
3115 {
3116 seqbuflen = _get_control_character(seqbuf, key_event,
3117 control_key_state);
3118
3119 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3120 // prefix with escape.
3121 if (_is_alt_pressed(control_key_state) &&
3122 !(_is_ctrl_pressed(control_key_state) &&
3123 !_is_shift_pressed(control_key_state))) {
3124 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3125 }
3126 }
3127 break;
3128
3129 case 0x41: // a
3130 case 0x42: // b
3131 case 0x43: // c
3132 case 0x44: // d
3133 case 0x45: // e
3134 case 0x46: // f
3135 case 0x47: // g
3136 case 0x48: // h
3137 case 0x49: // i
3138 case 0x4a: // j
3139 case 0x4b: // k
3140 case 0x4c: // l
3141 case 0x4d: // m
3142 case 0x4e: // n
3143 case 0x4f: // o
3144 case 0x50: // p
3145 case 0x51: // q
3146 case 0x52: // r
3147 case 0x53: // s
3148 case 0x54: // t
3149 case 0x55: // u
3150 case 0x56: // v
3151 case 0x57: // w
3152 case 0x58: // x
3153 case 0x59: // y
3154 case 0x5a: // z
3155 {
3156 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3157 control_key_state);
3158
3159 // If Alt is pressed, then prefix with escape.
3160 if (_is_alt_pressed(control_key_state)) {
3161 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3162 }
3163 }
3164 break;
3165
3166 // These virtual key codes are generated by the keys on the
3167 // keypad *when NumLock is on* and *Shift is up*.
3168 MATCH(VK_NUMPAD0, "0");
3169 MATCH(VK_NUMPAD1, "1");
3170 MATCH(VK_NUMPAD2, "2");
3171 MATCH(VK_NUMPAD3, "3");
3172 MATCH(VK_NUMPAD4, "4");
3173 MATCH(VK_NUMPAD5, "5");
3174 MATCH(VK_NUMPAD6, "6");
3175 MATCH(VK_NUMPAD7, "7");
3176 MATCH(VK_NUMPAD8, "8");
3177 MATCH(VK_NUMPAD9, "9");
3178
3179 MATCH(VK_MULTIPLY, "*");
3180 MATCH(VK_ADD, "+");
3181 MATCH(VK_SUBTRACT, "-");
3182 // VK_DECIMAL is generated by the . key on the keypad *when
3183 // NumLock is on* and *Shift is up* and the sequence is not
3184 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3185 // Windows Security screen to come up).
3186 case VK_DECIMAL:
3187 // U.S. English uses '.', Germany German uses ','.
3188 seqbuflen = _get_non_control_char(seqbuf, key_event,
3189 control_key_state);
3190 break;
3191
3192 MATCH_MODIFIER(VK_F1, SS3 "P");
3193 MATCH_MODIFIER(VK_F2, SS3 "Q");
3194 MATCH_MODIFIER(VK_F3, SS3 "R");
3195 MATCH_MODIFIER(VK_F4, SS3 "S");
3196 MATCH_MODIFIER(VK_F5, CSI "15~");
3197 MATCH_MODIFIER(VK_F6, CSI "17~");
3198 MATCH_MODIFIER(VK_F7, CSI "18~");
3199 MATCH_MODIFIER(VK_F8, CSI "19~");
3200 MATCH_MODIFIER(VK_F9, CSI "20~");
3201 MATCH_MODIFIER(VK_F10, CSI "21~");
3202 MATCH_MODIFIER(VK_F11, CSI "23~");
3203 MATCH_MODIFIER(VK_F12, CSI "24~");
3204
3205 MATCH_MODIFIER(VK_F13, CSI "25~");
3206 MATCH_MODIFIER(VK_F14, CSI "26~");
3207 MATCH_MODIFIER(VK_F15, CSI "28~");
3208 MATCH_MODIFIER(VK_F16, CSI "29~");
3209 MATCH_MODIFIER(VK_F17, CSI "31~");
3210 MATCH_MODIFIER(VK_F18, CSI "32~");
3211 MATCH_MODIFIER(VK_F19, CSI "33~");
3212 MATCH_MODIFIER(VK_F20, CSI "34~");
3213
3214 // MATCH_MODIFIER(VK_F21, ???);
3215 // MATCH_MODIFIER(VK_F22, ???);
3216 // MATCH_MODIFIER(VK_F23, ???);
3217 // MATCH_MODIFIER(VK_F24, ???);
3218 }
3219 }
3220
3221#undef MATCH
3222#undef MATCH_MODIFIER
3223#undef MATCH_KEYPAD
3224#undef MATCH_MODIFIER_KEYPAD
3225#undef ESC
3226#undef CSI
3227#undef SS3
3228
3229 const char* out;
3230 size_t outlen;
3231
3232 // Check for output in any of:
3233 // * seqstr is set (and strlen can be used to determine the length).
3234 // * seqbuf and seqbuflen are set
3235 // Fallback to ch from Windows.
3236 if (seqstr != NULL) {
3237 out = seqstr;
3238 outlen = strlen(seqstr);
3239 } else if (seqbuflen > 0) {
3240 out = seqbuf;
3241 outlen = seqbuflen;
3242 } else if (ch != '\0') {
3243 // Use whatever Windows told us it is.
3244 seqbuf[0] = ch;
3245 seqbuflen = 1;
3246 out = seqbuf;
3247 outlen = seqbuflen;
3248 } else {
3249 // No special handling for the virtual key code and Windows isn't
3250 // telling us a character code, then we don't know how to translate
3251 // the key press.
3252 //
3253 // Consume the input and 'continue' to cause us to get a new key
3254 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07003255 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08003256 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3257 key_event->wRepeatCount = 0;
3258 continue;
3259 }
3260
3261 int bytesRead = 0;
3262
3263 // put output wRepeatCount times into buf/len
3264 while (key_event->wRepeatCount > 0) {
3265 if (len >= outlen) {
3266 // Write to buf/len
3267 memcpy(buf, out, outlen);
3268 buf = (void*)((char*)buf + outlen);
3269 len -= outlen;
3270 bytesRead += outlen;
3271
3272 // consume the input
3273 --key_event->wRepeatCount;
3274 } else {
3275 // Not enough space, so just leave it in _win32_input_record
3276 // for a subsequent retrieval.
3277 if (bytesRead == 0) {
3278 // We didn't write anything because there wasn't enough
3279 // space to even write one sequence. This should never
3280 // happen if the caller uses sensible buffer sizes
3281 // (i.e. >= maximum sequence length which is probably a
3282 // few bytes long).
3283 D("_console_read: no buffer space to write one sequence; "
3284 "buffer: %ld, sequence: %ld\n", (long)len,
3285 (long)outlen);
3286 errno = ENOMEM;
3287 return -1;
3288 } else {
3289 // Stop trying to write to buf/len, just return whatever
3290 // we wrote so far.
3291 break;
3292 }
3293 }
3294 }
3295
3296 return bytesRead;
3297 }
3298}
3299
3300static DWORD _old_console_mode; // previous GetConsoleMode() result
3301static HANDLE _console_handle; // when set, console mode should be restored
3302
3303void stdin_raw_init(const int fd) {
3304 if (STDIN_FILENO == fd) {
3305 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3306 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3307 return;
3308 }
3309
3310 if (GetFileType(in) != FILE_TYPE_CHAR) {
3311 // stdin might be a file or pipe.
3312 return;
3313 }
3314
3315 if (!GetConsoleMode(in, &_old_console_mode)) {
3316 // If GetConsoleMode() fails, stdin is probably is not a console.
3317 return;
3318 }
3319
3320 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3321 // calling the process Ctrl-C routine (configured by
3322 // SetConsoleCtrlHandler()).
3323 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3324 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3325 // flag also seems necessary to have proper line-ending processing.
3326 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3327 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3328 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003329 D("stdin_raw_init: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003330 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003331 }
3332
3333 // Once this is set, it means that stdin has been configured for
3334 // reading from and that the old console mode should be restored later.
3335 _console_handle = in;
3336
3337 // Note that we don't need to configure C Runtime line-ending
3338 // translation because _console_read() does not call the C Runtime to
3339 // read from the console.
3340 }
3341}
3342
3343void stdin_raw_restore(const int fd) {
3344 if (STDIN_FILENO == fd) {
3345 if (_console_handle != NULL) {
3346 const HANDLE in = _console_handle;
3347 _console_handle = NULL; // clear state
3348
3349 if (!SetConsoleMode(in, _old_console_mode)) {
3350 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003351 D("stdin_raw_restore: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003352 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003353 }
3354 }
3355 }
3356}
3357
Spencer Low3a2421b2015-05-22 20:09:06 -07003358// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003359int unix_read(int fd, void* buf, size_t len) {
3360 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3361 // If it is a request to read from stdin, and stdin_raw_init() has been
3362 // called, and it successfully configured the console, then read from
3363 // the console using Win32 console APIs and partially emulate a unix
3364 // terminal.
3365 return _console_read(_console_handle, buf, len);
3366 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07003367 // On older versions of Windows (definitely 7, definitely not 10),
3368 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
3369 // we need to limit the read size. This may also catch devices like NUL,
3370 // but that is OK as we just want to avoid capping pipes and files which
3371 // don't need size limiting. This isatty() test is very simple and quick
3372 // and doesn't call the OS.
3373 if (isatty(fd) && len > 4096) {
3374 len = 4096;
3375 }
Spencer Lowbeb61982015-03-01 15:06:21 -08003376 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003377 // can do LF/CR translation (which is overridable with _setmode()).
3378 // Undefine the macro that is set in sysdeps.h which bans calls to
3379 // plain read() in favor of unix_read() or adb_read().
3380#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003381#undef read
3382 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003383#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003384 }
3385}
Spencer Low6815c072015-05-11 01:08:48 -07003386
3387/**************************************************************************/
3388/**************************************************************************/
3389/***** *****/
3390/***** Unicode support *****/
3391/***** *****/
3392/**************************************************************************/
3393/**************************************************************************/
3394
3395// This implements support for using files with Unicode filenames and for
3396// outputting Unicode text to a Win32 console window. This is inspired from
3397// http://utf8everywhere.org/.
3398//
3399// Background
3400// ----------
3401//
3402// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3403// filenames to APIs such as open(). This works because filenames are largely
3404// opaque 'cookies' (perhaps excluding path separators).
3405//
3406// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3407// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3408// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3409// CreateFile() API is really just a macro that adds the W/A based on whether
3410// the UNICODE preprocessor symbol is defined).
3411//
3412// Options
3413// -------
3414//
3415// Thus, to write a portable program, there are a few options:
3416//
3417// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3418// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3419// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3420// open() API.
3421//
3422// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3423// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3424// potentially touching a lot of code.
3425//
3426// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3427// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3428// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3429// or C Runtime API.
3430//
3431// The Choice
3432// ----------
3433//
3434// The code below chooses option 3, the UTF-8 everywhere strategy. It
3435// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3436// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3437// args that are passed to main() at the beginning of program startup. We also
3438// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3439// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3440//
3441// Unicode console output
3442// ----------------------
3443//
3444// The way to output Unicode to a Win32 console window is to call
3445// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003446// such as Lucida Console or Consolas, and in the case of East Asian languages
3447// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3448// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3449// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003450//
3451// The problem is getting the C Runtime to make fprintf and related APIs call
3452// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3453// promising, but the various modes have issues:
3454//
3455// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3456// UTF-16 do not display properly.
3457// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3458// totally wrong.
3459// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3460// handler to be called (upon a later I/O call), aborting the process.
3461// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3462// to output nothing.
3463//
3464// So the only solution is to write our own adb_fprintf() that converts UTF-8
3465// to UTF-16 and then calls WriteConsoleW().
3466
3467
3468// Function prototype because attributes cannot be placed on func definitions.
3469static void _widen_fatal(const char *fmt, ...)
3470 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3471
3472// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3473// called from those functions.
3474static void _widen_fatal(const char *fmt, ...) {
3475 va_list ap;
3476 va_start(ap, fmt);
3477 // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3478 // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3479 // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3480 // By directly calling real C Runtime APIs that don't properly output
3481 // Unicode, but will be able to get a comprehendible message out. To do
3482 // this, make sure we don't call (v)fprintf macros by undefining them.
3483#pragma push_macro("fprintf")
3484#pragma push_macro("vfprintf")
3485#undef fprintf
3486#undef vfprintf
3487 fprintf(stderr, "error: ");
3488 vfprintf(stderr, fmt, ap);
3489 fprintf(stderr, "\n");
3490#pragma pop_macro("vfprintf")
3491#pragma pop_macro("fprintf")
3492 va_end(ap);
3493 exit(-1);
3494}
3495
3496// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3497// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3498
3499// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3500// string. Any other size specifies the number of chars to convert, excluding
3501// any NULL terminator (if you're passing an explicit size, you probably don't
3502// have a NULL terminated string in the first place).
3503std::wstring widen(const char* utf8, const int size) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003504 // Note: Do not call SystemErrorCodeToString() from widen() because
3505 // SystemErrorCodeToString() calls narrow() which may call fatal() which
3506 // calls adb_vfprintf() which calls widen(), potentially causing infinite
3507 // recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003508 const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3509 NULL, 0);
3510 if (chars_to_convert <= 0) {
3511 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3512 _widen_fatal("MultiByteToWideChar failed counting: %d, "
3513 "GetLastError: %lu", chars_to_convert, GetLastError());
3514 }
3515
3516 std::wstring utf16;
3517 size_t chars_to_allocate = chars_to_convert;
3518 if (size == -1) {
3519 // chars_to_convert includes a NULL terminator, so subtract space
3520 // for that because resize() includes that itself.
3521 --chars_to_allocate;
3522 }
3523 utf16.resize(chars_to_allocate);
3524
3525 // This uses &string[0] to get write-access to the entire string buffer
3526 // which may be assuming that the chars are all contiguous, but it seems
3527 // to work and saves us the hassle of using a temporary
3528 // std::vector<wchar_t>.
3529 const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3530 chars_to_convert);
3531 if (result != chars_to_convert) {
3532 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3533 _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3534 "GetLastError: %lu", result, GetLastError());
3535 }
3536
3537 // If a size was passed in (size != -1), then the string is NULL terminated
3538 // by a NULL char that was written by std::string::resize(). If size == -1,
3539 // then MultiByteToWideChar() read a NULL terminator from the original
3540 // string and converted it to a NULL UTF-16 char in the output.
3541
3542 return utf16;
3543}
3544
3545// Convert a NULL terminated string from UTF-8 to UTF-16.
3546std::wstring widen(const char* utf8) {
3547 // Pass -1 to let widen() determine the string length.
3548 return widen(utf8, -1);
3549}
3550
3551// Convert from UTF-8 to UTF-16.
3552std::wstring widen(const std::string& utf8) {
3553 return widen(utf8.c_str(), utf8.length());
3554}
3555
3556// Convert from UTF-16 to UTF-8.
3557std::string narrow(const std::wstring& utf16) {
3558 return narrow(utf16.c_str());
3559}
3560
3561// Convert from UTF-16 to UTF-8.
3562std::string narrow(const wchar_t* utf16) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003563 // Note: Do not call SystemErrorCodeToString() from narrow() because
Elliott Hughes1ba53092015-08-03 16:26:13 -07003564 // SystemErrorCodeToString() calls narrow() and we don't want potential
Spencer Lowcc467f12015-08-02 18:13:54 -07003565 // infinite recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003566 const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3567 0, NULL, NULL);
3568 if (chars_required <= 0) {
3569 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003570 fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003571 chars_required, GetLastError());
3572 }
3573
3574 std::string utf8;
3575 // Subtract space for the NULL terminator because resize() includes
3576 // that itself. Note that this could potentially throw a std::bad_alloc
3577 // exception.
3578 utf8.resize(chars_required - 1);
3579
3580 // This uses &string[0] to get write-access to the entire string buffer
3581 // which may be assuming that the chars are all contiguous, but it seems
3582 // to work and saves us the hassle of using a temporary
3583 // std::vector<char>.
3584 const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3585 chars_required, NULL, NULL);
3586 if (result != chars_required) {
3587 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003588 fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003589 result, GetLastError());
3590 }
3591
3592 return utf8;
3593}
3594
3595// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3596// be passed to main().
3597NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3598 narrow_args = new char*[argc + 1];
3599
3600 for (int i = 0; i < argc; ++i) {
3601 narrow_args[i] = strdup(narrow(argv[i]).c_str());
3602 }
3603 narrow_args[argc] = nullptr; // terminate
3604}
3605
3606NarrowArgs::~NarrowArgs() {
3607 if (narrow_args != nullptr) {
3608 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3609 free(*argp);
3610 }
3611 delete[] narrow_args;
3612 narrow_args = nullptr;
3613 }
3614}
3615
3616int unix_open(const char* path, int options, ...) {
3617 if ((options & O_CREAT) == 0) {
3618 return _wopen(widen(path).c_str(), options);
3619 } else {
3620 int mode;
3621 va_list args;
3622 va_start(args, options);
3623 mode = va_arg(args, int);
3624 va_end(args);
3625 return _wopen(widen(path).c_str(), options, mode);
3626 }
3627}
3628
3629// Version of stat() that takes a UTF-8 path.
3630int adb_stat(const char* f, struct adb_stat* s) {
3631#pragma push_macro("wstat")
3632// This definition of wstat seems to be missing from <sys/stat.h>.
3633#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3634#ifdef _USE_32BIT_TIME_T
3635#define wstat _wstat32i64
3636#else
3637#define wstat _wstat64
3638#endif
3639#else
3640// <sys/stat.h> has a function prototype for wstat() that should be available.
3641#endif
3642
3643 return wstat(widen(f).c_str(), s);
3644
3645#pragma pop_macro("wstat")
3646}
3647
3648// Version of opendir() that takes a UTF-8 path.
3649DIR* adb_opendir(const char* name) {
3650 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3651 // the fields, but right now all the callers treat the structure as
3652 // opaque.
3653 return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3654}
3655
3656// Version of readdir() that returns UTF-8 paths.
3657struct dirent* adb_readdir(DIR* dir) {
3658 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3659 struct _wdirent* const went = _wreaddir(wdir);
3660 if (went == nullptr) {
3661 return nullptr;
3662 }
3663 // Convert from UTF-16 to UTF-8.
3664 const std::string name_utf8(narrow(went->d_name));
3665
3666 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3667 // space for UTF-16 wchar_t's) with UTF-8 char's.
3668 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3669
3670 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3671 // Name too big to fit in existing buffer.
3672 errno = ENOMEM;
3673 return nullptr;
3674 }
3675
3676 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3677 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3678 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3679 // bigger than the caller expects because they expect a dirent structure
3680 // which has a smaller d_name field. Ignore this since the caller should be
3681 // resilient.
3682
3683 // Rewrite the UTF-16 d_name field to UTF-8.
3684 strcpy(ent->d_name, name_utf8.c_str());
3685
3686 return ent;
3687}
3688
3689// Version of closedir() to go with our version of adb_opendir().
3690int adb_closedir(DIR* dir) {
3691 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3692}
3693
3694// Version of unlink() that takes a UTF-8 path.
3695int adb_unlink(const char* path) {
3696 const std::wstring wpath(widen(path));
3697
3698 int rc = _wunlink(wpath.c_str());
3699
3700 if (rc == -1 && errno == EACCES) {
3701 /* unlink returns EACCES when the file is read-only, so we first */
3702 /* try to make it writable, then unlink again... */
3703 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3704 if (rc == 0)
3705 rc = _wunlink(wpath.c_str());
3706 }
3707 return rc;
3708}
3709
3710// Version of mkdir() that takes a UTF-8 path.
3711int adb_mkdir(const std::string& path, int mode) {
3712 return _wmkdir(widen(path.c_str()).c_str());
3713}
3714
3715// Version of utime() that takes a UTF-8 path.
3716int adb_utime(const char* path, struct utimbuf* u) {
3717 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3718 "utimbuf and _utimbuf should be the same size because they both "
3719 "contain the same types, namely time_t");
3720 return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3721}
3722
3723// Version of chmod() that takes a UTF-8 path.
3724int adb_chmod(const char* path, int mode) {
3725 return _wchmod(widen(path).c_str(), mode);
3726}
3727
3728// Internal function to get a Win32 console HANDLE from a C Runtime FILE*.
3729static HANDLE _get_console_handle(FILE* const stream) {
3730 // Get a C Runtime file descriptor number from the FILE* structure.
3731 const int fd = fileno(stream);
3732 if (fd < 0) {
3733 return NULL;
3734 }
3735
3736 // If it is not a "character device", it is probably a file and not a
3737 // console. Do this check early because it is probably cheap. Still do more
3738 // checks after this since there are devices that pass this test, but are
3739 // not a console, such as NUL, the Windows /dev/null equivalent (I think).
3740 if (!isatty(fd)) {
3741 return NULL;
3742 }
3743
3744 // Given a C Runtime file descriptor number, get the underlying OS
3745 // file handle.
3746 const intptr_t osfh = _get_osfhandle(fd);
3747 if (osfh == -1) {
3748 return NULL;
3749 }
3750
3751 const HANDLE h = reinterpret_cast<const HANDLE>(osfh);
3752
3753 DWORD old_mode = 0;
3754 if (!GetConsoleMode(h, &old_mode)) {
3755 return NULL;
3756 }
3757
3758 // If GetConsoleMode() was successful, assume this is a console.
3759 return h;
3760}
3761
3762// Internal helper function to write UTF-8 bytes to a console. Returns -1
3763// on error.
3764static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3765 HANDLE console) {
3766 // Convert from UTF-8 to UTF-16.
3767 // This could throw std::bad_alloc.
3768 const std::wstring output(widen(buf, size));
3769
3770 // Note that this does not do \n => \r\n translation because that
3771 // doesn't seem necessary for the Windows console. For the Windows
3772 // console \r moves to the beginning of the line and \n moves to a new
3773 // line.
3774
3775 // Flush any stream buffering so that our output is afterwards which
3776 // makes sense because our call is afterwards.
3777 (void)fflush(stream);
3778
3779 // Write UTF-16 to the console.
3780 DWORD written = 0;
3781 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3782 NULL)) {
3783 errno = EIO;
3784 return -1;
3785 }
3786
3787 // This is the number of UTF-16 chars written, which might be different
3788 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3789 // get this count correct.
3790 return written;
3791}
3792
3793// Function prototype because attributes cannot be placed on func definitions.
3794static int _console_vfprintf(const HANDLE console, FILE* stream,
3795 const char *format, va_list ap)
3796 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3797
3798// Internal function to format a UTF-8 string and write it to a Win32 console.
3799// Returns -1 on error.
3800static int _console_vfprintf(const HANDLE console, FILE* stream,
3801 const char *format, va_list ap) {
3802 std::string output_utf8;
3803
3804 // Format the string.
3805 // This could throw std::bad_alloc.
3806 android::base::StringAppendV(&output_utf8, format, ap);
3807
3808 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3809 stream, console);
3810}
3811
3812// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3813// Windows console.
3814int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3815 const HANDLE console = _get_console_handle(stream);
3816
3817 // If there is an associated Win32 console, write to it specially,
3818 // otherwise defer to the regular C Runtime, passing it UTF-8.
3819 if (console != NULL) {
3820 return _console_vfprintf(console, stream, format, ap);
3821 } else {
3822 // If vfprintf is a macro, undefine it, so we can call the real
3823 // C Runtime API.
3824#pragma push_macro("vfprintf")
3825#undef vfprintf
3826 return vfprintf(stream, format, ap);
3827#pragma pop_macro("vfprintf")
3828 }
3829}
3830
3831// Version of fprintf() that takes UTF-8 and can write Unicode to a
3832// Windows console.
3833int adb_fprintf(FILE *stream, const char *format, ...) {
3834 va_list ap;
3835 va_start(ap, format);
3836 const int result = adb_vfprintf(stream, format, ap);
3837 va_end(ap);
3838
3839 return result;
3840}
3841
3842// Version of printf() that takes UTF-8 and can write Unicode to a
3843// Windows console.
3844int adb_printf(const char *format, ...) {
3845 va_list ap;
3846 va_start(ap, format);
3847 const int result = adb_vfprintf(stdout, format, ap);
3848 va_end(ap);
3849
3850 return result;
3851}
3852
3853// Version of fputs() that takes UTF-8 and can write Unicode to a
3854// Windows console.
3855int adb_fputs(const char* buf, FILE* stream) {
3856 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3857 // which fputs (and hence adb_fputs) should return on error.
3858 return adb_fprintf(stream, "%s", buf);
3859}
3860
3861// Version of fputc() that takes UTF-8 and can write Unicode to a
3862// Windows console.
3863int adb_fputc(int ch, FILE* stream) {
3864 const int result = adb_fprintf(stream, "%c", ch);
3865 if (result <= 0) {
3866 // If there was an error, or if nothing was printed (which should be an
3867 // error), return an error, which fprintf signifies with EOF.
3868 return EOF;
3869 }
3870 // For success, fputc returns the char, cast to unsigned char, then to int.
3871 return static_cast<unsigned char>(ch);
3872}
3873
3874// Internal function to write UTF-8 to a Win32 console. Returns the number of
3875// items (of length size) written. On error, returns a short item count or 0.
3876static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3877 FILE* stream, HANDLE console) {
3878 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3879 // if we're passed only some of the bytes of a character (for example, from
3880 // the network socket for adb shell), we won't be able to convert the char
3881 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3882 // right.
3883 //
3884 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3885 //
3886 // For now we ignore this problem because the alternative is that we'd have
3887 // to parse UTF-8 and buffer things up (doable). At least this is better
3888 // than what we had before -- always incorrect multi-byte UTF-8 output.
3889 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3890 size * nmemb, stream, console);
3891 if (result == -1) {
3892 return 0;
3893 }
3894 return result / size;
3895}
3896
3897// Version of fwrite() that takes UTF-8 and can write Unicode to a
3898// Windows console.
3899size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3900 const HANDLE console = _get_console_handle(stream);
3901
3902 // If there is an associated Win32 console, write to it specially,
3903 // otherwise defer to the regular C Runtime, passing it UTF-8.
3904 if (console != NULL) {
3905 return _console_fwrite(ptr, size, nmemb, stream, console);
3906 } else {
3907 // If fwrite is a macro, undefine it, so we can call the real
3908 // C Runtime API.
3909#pragma push_macro("fwrite")
3910#undef fwrite
3911 return fwrite(ptr, size, nmemb, stream);
3912#pragma pop_macro("fwrite")
3913 }
3914}
3915
3916// Version of fopen() that takes a UTF-8 filename and can access a file with
3917// a Unicode filename.
3918FILE* adb_fopen(const char* f, const char* m) {
3919 return _wfopen(widen(f).c_str(), widen(m).c_str());
3920}
3921
Spencer Low50740f52015-09-08 17:13:04 -07003922// Return a lowercase version of the argument. Uses C Runtime tolower() on
3923// each byte which is not UTF-8 aware, and theoretically uses the current C
3924// Runtime locale (which in practice is not changed, so this becomes a ASCII
3925// conversion).
3926static std::string ToLower(const std::string& anycase) {
3927 // copy string
3928 std::string str(anycase);
3929 // transform the copy
3930 std::transform(str.begin(), str.end(), str.begin(), tolower);
3931 return str;
3932}
3933
3934extern "C" int main(int argc, char** argv);
3935
3936// Link with -municode to cause this wmain() to be used as the program
3937// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3938// regular main() with UTF-8 args.
3939extern "C" int wmain(int argc, wchar_t **argv) {
3940 // Convert args from UTF-16 to UTF-8 and pass that to main().
3941 NarrowArgs narrow_args(argc, argv);
3942 return main(argc, narrow_args.data());
3943}
3944
Spencer Low6815c072015-05-11 01:08:48 -07003945// Shadow UTF-8 environment variable name/value pairs that are created from
3946// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003947// currently updated if putenv, setenv, unsetenv are called. Note that no
3948// thread synchronization is done, but we're called early enough in
3949// single-threaded startup that things work ok.
Spencer Low6815c072015-05-11 01:08:48 -07003950static std::unordered_map<std::string, char*> g_environ_utf8;
3951
3952// Make sure that shadow UTF-8 environment variables are setup.
3953static void _ensure_env_setup() {
3954 // If some name/value pairs exist, then we've already done the setup below.
3955 if (g_environ_utf8.size() != 0) {
3956 return;
3957 }
3958
Spencer Low50740f52015-09-08 17:13:04 -07003959 if (_wenviron == nullptr) {
3960 // If _wenviron is null, then -municode probably wasn't used. That
3961 // linker flag will cause the entry point to setup _wenviron. It will
3962 // also require an implementation of wmain() (which we provide above).
3963 fatal("_wenviron is not set, did you link with -municode?");
3964 }
3965
Spencer Low6815c072015-05-11 01:08:48 -07003966 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3967 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3968 // to use the D() macro here because that tracing only works if the
3969 // ADB_TRACE environment variable is setup, but that env var can't be read
3970 // until this code completes.
3971 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3972 wchar_t* const equal = wcschr(*env, L'=');
3973 if (equal == nullptr) {
3974 // Malformed environment variable with no equal sign. Shouldn't
3975 // really happen, but we should be resilient to this.
3976 continue;
3977 }
3978
Spencer Low50740f52015-09-08 17:13:04 -07003979 // Store lowercase name so that we can do case-insensitive searches.
3980 const std::string name_utf8(ToLower(narrow(
3981 std::wstring(*env, equal - *env))));
Spencer Low6815c072015-05-11 01:08:48 -07003982 char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3983
Spencer Low50740f52015-09-08 17:13:04 -07003984 // Don't overwrite a previus env var with the same name. In reality,
3985 // the system probably won't let two env vars with the same name exist
3986 // in _wenviron.
3987 g_environ_utf8.insert({name_utf8, value_utf8});
Spencer Low6815c072015-05-11 01:08:48 -07003988 }
3989}
3990
3991// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07003992// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07003993char* adb_getenv(const char* name) {
3994 _ensure_env_setup();
3995
Spencer Low50740f52015-09-08 17:13:04 -07003996 // Case-insensitive search by searching for lowercase name in a map of
3997 // lowercase names.
3998 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07003999 if (it == g_environ_utf8.end()) {
4000 return nullptr;
4001 }
4002
4003 return it->second;
4004}
4005
4006// Version of getcwd() that returns the current working directory in UTF-8.
4007char* adb_getcwd(char* buf, int size) {
4008 wchar_t* wbuf = _wgetcwd(nullptr, 0);
4009 if (wbuf == nullptr) {
4010 return nullptr;
4011 }
4012
4013 const std::string buf_utf8(narrow(wbuf));
4014 free(wbuf);
4015 wbuf = nullptr;
4016
4017 // If size was specified, make sure all the chars will fit.
4018 if (size != 0) {
4019 if (size < static_cast<int>(buf_utf8.length() + 1)) {
4020 errno = ERANGE;
4021 return nullptr;
4022 }
4023 }
4024
4025 // If buf was not specified, allocate storage.
4026 if (buf == nullptr) {
4027 if (size == 0) {
4028 size = buf_utf8.length() + 1;
4029 }
4030 buf = reinterpret_cast<char*>(malloc(size));
4031 if (buf == nullptr) {
4032 return nullptr;
4033 }
4034 }
4035
4036 // Destination buffer was allocated with enough space, or we've already
4037 // checked an existing buffer size for enough space.
4038 strcpy(buf, buf_utf8.c_str());
4039
4040 return buf;
4041}