blob: 42f6d9b768b3310019ada68d03f82393caec40fb [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
559/**************************************************************************/
560/**************************************************************************/
561/***** *****/
562/***** socket-based file descriptors *****/
563/***** *****/
564/**************************************************************************/
565/**************************************************************************/
566
Spencer Low31aafa62015-01-25 14:40:16 -0800567#undef setsockopt
568
Spencer Low753d4852015-07-30 23:07:55 -0700569static void _socket_set_errno( const DWORD err ) {
570 // The Windows C Runtime (MSVCRT.DLL) strerror() does not support a lot of
571 // POSIX and socket error codes, so this can only meaningfully map so much.
572 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800573 case 0: errno = 0; break;
Spencer Low32625852015-08-11 16:45:32 -0700574 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
575 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
576 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800577 case WSAEWOULDBLOCK: errno = EAGAIN; break;
578 case WSAEINTR: errno = EINTR; break;
Spencer Low753d4852015-07-30 23:07:55 -0700579 case WSAEFAULT: errno = EFAULT; break;
580 case WSAEINVAL: errno = EINVAL; break;
581 case WSAEMFILE: errno = EMFILE; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800582 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800583 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700584 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700585 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800586 }
587}
588
Elliott Hughes6a096932015-04-16 16:47:02 -0700589static void _fh_socket_init( FH f ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800590 f->fh_socket = INVALID_SOCKET;
591 f->event = WSACreateEvent();
Spencer Low753d4852015-07-30 23:07:55 -0700592 if (f->event == WSA_INVALID_EVENT) {
Yabin Cui815ad882015-09-02 17:44:28 -0700593 D("WSACreateEvent failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700594 SystemErrorCodeToString(WSAGetLastError()).c_str());
595
596 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
597 // on failure, instead of NULL which is what Windows really returns on
598 // error. It might be better to change all the other code to look for
599 // NULL, but that is a much riskier change.
600 f->event = INVALID_HANDLE_VALUE;
601 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800602 f->mask = 0;
603}
604
Elliott Hughes6a096932015-04-16 16:47:02 -0700605static int _fh_socket_close( FH f ) {
Spencer Low753d4852015-07-30 23:07:55 -0700606 if (f->fh_socket != INVALID_SOCKET) {
607 /* gently tell any peer that we're closing the socket */
608 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
609 // If the socket is not connected, this returns an error. We want to
610 // minimize logging spam, so don't log these errors for now.
611#if 0
Yabin Cui815ad882015-09-02 17:44:28 -0700612 D("socket shutdown failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700613 SystemErrorCodeToString(WSAGetLastError()).c_str());
614#endif
615 }
616 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Yabin Cui815ad882015-09-02 17:44:28 -0700617 D("closesocket failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700618 SystemErrorCodeToString(WSAGetLastError()).c_str());
619 }
620 f->fh_socket = INVALID_SOCKET;
621 }
622 if (f->event != NULL) {
623 if (!CloseHandle(f->event)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700624 D("CloseHandle failed: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700625 SystemErrorCodeToString(GetLastError()).c_str());
626 }
627 f->event = NULL;
628 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800629 f->mask = 0;
630 return 0;
631}
632
Elliott Hughes6a096932015-04-16 16:47:02 -0700633static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800634 errno = EPIPE;
635 return -1;
636}
637
Elliott Hughes6a096932015-04-16 16:47:02 -0700638static int _fh_socket_read(FH f, void* buf, int len) {
639 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800640 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700641 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700642 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
643 // that to reduce spam and confusion.
644 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700645 D("recv fd %d failed: %s", _fh_to_int(f),
Spencer Low32625852015-08-11 16:45:32 -0700646 SystemErrorCodeToString(err).c_str());
647 }
Spencer Low753d4852015-07-30 23:07:55 -0700648 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800649 result = -1;
650 }
651 return result;
652}
653
Elliott Hughes6a096932015-04-16 16:47:02 -0700654static int _fh_socket_write(FH f, const void* buf, int len) {
655 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800656 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700657 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -0700658 D("send fd %d failed: %s", _fh_to_int(f),
Spencer Low753d4852015-07-30 23:07:55 -0700659 SystemErrorCodeToString(err).c_str());
660 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800661 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700662 } else {
663 // According to https://code.google.com/p/chromium/issues/detail?id=27870
664 // Winsock Layered Service Providers may cause this.
665 CHECK_LE(result, len) << "Tried to write " << len << " bytes to "
666 << f->name << ", but " << result
667 << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800668 }
669 return result;
670}
671
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800672/**************************************************************************/
673/**************************************************************************/
674/***** *****/
675/***** replacement for libs/cutils/socket_xxxx.c *****/
676/***** *****/
677/**************************************************************************/
678/**************************************************************************/
679
680#include <winsock2.h>
681
682static int _winsock_init;
683
684static void
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800685_init_winsock( void )
686{
Spencer Low753d4852015-07-30 23:07:55 -0700687 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700688 // to WSAStartup() which offers no real benefit.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800689 if (!_winsock_init) {
690 WSADATA wsaData;
691 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
692 if (rc != 0) {
Spencer Low753d4852015-07-30 23:07:55 -0700693 fatal( "adb: could not initialize Winsock: %s",
694 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800695 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800696 _winsock_init = 1;
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700697
698 // Note that we do not call atexit() to register WSACleanup to be called
699 // at normal process termination because:
700 // 1) When exit() is called, there are still threads actively using
701 // Winsock because we don't cleanly shutdown all threads, so it
702 // doesn't make sense to call WSACleanup() and may cause problems
703 // with those threads.
704 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
705 // calls WSACleanup() which tries to unload a DLL, which tries to
706 // grab the LoaderLock. This conflicts with the device_poll_thread
707 // which holds the LoaderLock because AdbWinApi.dll calls
708 // setupapi.dll which tries to load wintrust.dll which tries to load
709 // crypt32.dll which calls atexit() which tries to acquire the C
710 // Runtime lock that the other thread holds.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800711 }
712}
713
Spencer Lowc7c45612015-09-29 15:05:29 -0700714// Map a socket type to an explicit socket protocol instead of using the socket
715// protocol of 0. Explicit socket protocols are used by most apps and we should
716// do the same to reduce the chance of exercising uncommon code-paths that might
717// have problems or that might load different Winsock service providers that
718// have problems.
719static int GetSocketProtocolFromSocketType(int type) {
720 switch (type) {
721 case SOCK_STREAM:
722 return IPPROTO_TCP;
723 case SOCK_DGRAM:
724 return IPPROTO_UDP;
725 default:
726 LOG(FATAL) << "Unknown socket type: " << type;
727 return 0;
728 }
729}
730
Spencer Low753d4852015-07-30 23:07:55 -0700731int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800732 struct sockaddr_in addr;
733 SOCKET s;
734
Spencer Low753d4852015-07-30 23:07:55 -0700735 unique_fh f(_fh_alloc(&_fh_socket_class));
736 if (!f) {
737 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800738 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700739 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800740
741 if (!_winsock_init)
742 _init_winsock();
743
744 memset(&addr, 0, sizeof(addr));
745 addr.sin_family = AF_INET;
746 addr.sin_port = htons(port);
747 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
748
Spencer Lowc7c45612015-09-29 15:05:29 -0700749 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800750 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700751 *error = android::base::StringPrintf("cannot create socket: %s",
752 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700753 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700754 return -1;
755 }
756 f->fh_socket = s;
757
758 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700759 // Save err just in case inet_ntoa() or ntohs() changes the last error.
760 const DWORD err = WSAGetLastError();
761 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
762 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
763 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700764 D("could not connect to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700765 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800766 return -1;
767 }
768
Spencer Low753d4852015-07-30 23:07:55 -0700769 const int fd = _fh_to_int(f.get());
770 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
771 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700772 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700773 fd );
774 f.release();
775 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800776}
777
778#define LISTEN_BACKLOG 4
779
Spencer Low753d4852015-07-30 23:07:55 -0700780// interface_address is INADDR_LOOPBACK or INADDR_ANY.
781static int _network_server(int port, int type, u_long interface_address,
782 std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800783 struct sockaddr_in addr;
784 SOCKET s;
785 int n;
786
Spencer Low753d4852015-07-30 23:07:55 -0700787 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800788 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700789 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800790 return -1;
791 }
792
793 if (!_winsock_init)
794 _init_winsock();
795
796 memset(&addr, 0, sizeof(addr));
797 addr.sin_family = AF_INET;
798 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700799 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800800
Spencer Low753d4852015-07-30 23:07:55 -0700801 // TODO: Consider using dual-stack socket that can simultaneously listen on
802 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700803 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700804 if (s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700805 *error = android::base::StringPrintf("cannot create socket: %s",
806 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700807 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700808 return -1;
809 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800810
811 f->fh_socket = s;
812
Spencer Low32625852015-08-11 16:45:32 -0700813 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
814 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800815 n = 1;
Spencer Low753d4852015-07-30 23:07:55 -0700816 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
817 sizeof(n)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700818 *error = android::base::StringPrintf(
819 "cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
820 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700821 D("%s", error->c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700822 return -1;
823 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800824
Spencer Low32625852015-08-11 16:45:32 -0700825 if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
826 // Save err just in case inet_ntoa() or ntohs() changes the last error.
827 const DWORD err = WSAGetLastError();
828 *error = android::base::StringPrintf("cannot bind to %s:%u: %s",
829 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
830 SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700831 D("could not bind to %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700832 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800833 return -1;
834 }
835 if (type == SOCK_STREAM) {
Spencer Low753d4852015-07-30 23:07:55 -0700836 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700837 *error = android::base::StringPrintf("cannot listen on socket: %s",
838 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700839 D("could not listen on %s:%d: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700840 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800841 return -1;
842 }
843 }
Spencer Low753d4852015-07-30 23:07:55 -0700844 const int fd = _fh_to_int(f.get());
845 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
846 interface_address == INADDR_LOOPBACK ? "lo" : "any",
847 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700848 D( "port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp",
Spencer Low753d4852015-07-30 23:07:55 -0700849 fd );
850 f.release();
851 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800852}
853
Spencer Low753d4852015-07-30 23:07:55 -0700854int network_loopback_server(int port, int type, std::string* error) {
855 return _network_server(port, type, INADDR_LOOPBACK, error);
856}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800857
Spencer Low753d4852015-07-30 23:07:55 -0700858int network_inaddr_any_server(int port, int type, std::string* error) {
859 return _network_server(port, type, INADDR_ANY, error);
860}
861
862int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
863 unique_fh f(_fh_alloc(&_fh_socket_class));
864 if (!f) {
865 *error = strerror(errno);
866 return -1;
867 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800868
Elliott Hughes43df1092015-07-23 17:12:58 -0700869 if (!_winsock_init) _init_winsock();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800870
Spencer Low753d4852015-07-30 23:07:55 -0700871 struct addrinfo hints;
872 memset(&hints, 0, sizeof(hints));
873 hints.ai_family = AF_UNSPEC;
874 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700875 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700876
877 char port_str[16];
878 snprintf(port_str, sizeof(port_str), "%d", port);
879
880 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700881
882#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
883 // TODO: When the Android SDK tools increases the Windows system
884 // requirements >= WinXP SP2, switch to GetAddrInfoW(widen(host).c_str()).
885#else
886 // Otherwise, keep using getaddrinfo(), or do runtime API detection
887 // with GetProcAddress("GetAddrInfoW").
888#endif
Spencer Low753d4852015-07-30 23:07:55 -0700889 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Spencer Low32625852015-08-11 16:45:32 -0700890 *error = android::base::StringPrintf(
891 "cannot resolve host '%s' and port %s: %s", host.c_str(),
892 port_str, SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700893 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800894 return -1;
895 }
Spencer Low753d4852015-07-30 23:07:55 -0700896 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
897 addrinfo(addrinfo_ptr, freeaddrinfo);
898 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800899
Spencer Low753d4852015-07-30 23:07:55 -0700900 // TODO: Try all the addresses if there's more than one? This just uses
901 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
902 // which tries all addresses, takes a timeout and more.
903 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
904 addrinfo->ai_protocol);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800905 if(s == INVALID_SOCKET) {
Spencer Low32625852015-08-11 16:45:32 -0700906 *error = android::base::StringPrintf("cannot create socket: %s",
907 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700908 D("%s", error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800909 return -1;
910 }
911 f->fh_socket = s;
912
Spencer Low753d4852015-07-30 23:07:55 -0700913 // TODO: Implement timeouts for Windows. Seems like the default in theory
914 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
915 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700916 // TODO: Use WSAAddressToString or inet_ntop on address.
917 *error = android::base::StringPrintf("cannot connect to %s:%s: %s",
918 host.c_str(), port_str,
919 SystemErrorCodeToString(WSAGetLastError()).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700920 D("could not connect to %s:%s:%s: %s",
Spencer Low753d4852015-07-30 23:07:55 -0700921 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
922 error->c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800923 return -1;
924 }
925
Spencer Low753d4852015-07-30 23:07:55 -0700926 const int fd = _fh_to_int(f.get());
927 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
928 type != SOCK_STREAM ? "udp:" : "", port );
Yabin Cui815ad882015-09-02 17:44:28 -0700929 D( "host '%s' port %d type %s => fd %d", host.c_str(), port,
Spencer Low753d4852015-07-30 23:07:55 -0700930 type != SOCK_STREAM ? "udp" : "tcp", fd );
931 f.release();
932 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800933}
934
935#undef accept
936int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
937{
Spencer Low3a2421b2015-05-22 20:09:06 -0700938 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200939
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800940 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700941 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low753d4852015-07-30 23:07:55 -0700942 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800943 return -1;
944 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200945
Spencer Low753d4852015-07-30 23:07:55 -0700946 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800947 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700948 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
949 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800950 return -1;
951 }
952
953 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
954 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700955 const DWORD err = WSAGetLastError();
Spencer Low753d4852015-07-30 23:07:55 -0700956 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
957 " failed: " + SystemErrorCodeToString(err);
958 _socket_set_errno( err );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800959 return -1;
960 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200961
Spencer Low753d4852015-07-30 23:07:55 -0700962 const int fd = _fh_to_int(fh.get());
963 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui815ad882015-09-02 17:44:28 -0700964 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low753d4852015-07-30 23:07:55 -0700965 fh.release();
966 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800967}
968
969
Spencer Low31aafa62015-01-25 14:40:16 -0800970int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800971{
Spencer Low3a2421b2015-05-22 20:09:06 -0700972 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200973
Spencer Low31aafa62015-01-25 14:40:16 -0800974 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui815ad882015-09-02 17:44:28 -0700975 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700976 errno = EBADF;
977 return -1;
978 }
Spencer Lowc7c45612015-09-29 15:05:29 -0700979
980 // TODO: Once we can assume Windows Vista or later, if the caller is trying
981 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
982 // auto-tuning.
983
Spencer Low753d4852015-07-30 23:07:55 -0700984 int result = setsockopt( fh->fh_socket, level, optname,
985 reinterpret_cast<const char*>(optval), optlen );
986 if ( result == SOCKET_ERROR ) {
987 const DWORD err = WSAGetLastError();
988 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
989 "failed: %s\n", fd, level, optname,
990 SystemErrorCodeToString(err).c_str() );
991 _socket_set_errno( err );
992 result = -1;
993 }
994 return result;
995}
996
997
998int adb_shutdown(int fd)
999{
1000 FH f = _fh_from_int(fd, __func__);
1001
1002 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui815ad882015-09-02 17:44:28 -07001003 D("adb_shutdown: invalid fd %d", fd);
Spencer Low753d4852015-07-30 23:07:55 -07001004 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001005 return -1;
1006 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001007
Yabin Cui815ad882015-09-02 17:44:28 -07001008 D( "adb_shutdown: %s", f->name);
Spencer Low753d4852015-07-30 23:07:55 -07001009 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
1010 const DWORD err = WSAGetLastError();
Yabin Cui815ad882015-09-02 17:44:28 -07001011 D("socket shutdown fd %d failed: %s", fd,
Spencer Low753d4852015-07-30 23:07:55 -07001012 SystemErrorCodeToString(err).c_str());
1013 _socket_set_errno(err);
1014 return -1;
1015 }
1016 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001017}
1018
1019/**************************************************************************/
1020/**************************************************************************/
1021/***** *****/
1022/***** emulated socketpairs *****/
1023/***** *****/
1024/**************************************************************************/
1025/**************************************************************************/
1026
1027/* we implement socketpairs directly in use space for the following reasons:
1028 * - it avoids copying data from/to the Nt kernel
1029 * - it allows us to implement fdevent hooks easily and cheaply, something
1030 * that is not possible with standard Win32 pipes !!
1031 *
1032 * basically, we use two circular buffers, each one corresponding to a given
1033 * direction.
1034 *
1035 * each buffer is implemented as two regions:
1036 *
1037 * region A which is (a_start,a_end)
1038 * region B which is (0, b_end) with b_end <= a_start
1039 *
1040 * an empty buffer has: a_start = a_end = b_end = 0
1041 *
1042 * a_start is the pointer where we start reading data
1043 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
1044 * then you start writing at b_end
1045 *
1046 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
1047 *
1048 * there is room when b_end < a_start || a_end < BUFER_SIZE
1049 *
1050 * when reading, a_start is incremented, it a_start meets a_end, then
1051 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
1052 */
1053
1054#define BIP_BUFFER_SIZE 4096
1055
1056#if 0
1057#include <stdio.h>
1058# define BIPD(x) D x
1059# define BIPDUMP bip_dump_hex
1060
1061static void bip_dump_hex( const unsigned char* ptr, size_t len )
1062{
1063 int nn, len2 = len;
1064
1065 if (len2 > 8) len2 = 8;
1066
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001067 for (nn = 0; nn < len2; nn++)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001068 printf("%02x", ptr[nn]);
1069 printf(" ");
1070
1071 for (nn = 0; nn < len2; nn++) {
1072 int c = ptr[nn];
1073 if (c < 32 || c > 127)
1074 c = '.';
1075 printf("%c", c);
1076 }
1077 printf("\n");
1078 fflush(stdout);
1079}
1080
1081#else
1082# define BIPD(x) do {} while (0)
1083# define BIPDUMP(p,l) BIPD(p)
1084#endif
1085
1086typedef struct BipBufferRec_
1087{
1088 int a_start;
1089 int a_end;
1090 int b_end;
1091 int fdin;
1092 int fdout;
1093 int closed;
1094 int can_write; /* boolean */
1095 HANDLE evt_write; /* event signaled when one can write to a buffer */
1096 int can_read; /* boolean */
1097 HANDLE evt_read; /* event signaled when one can read from a buffer */
1098 CRITICAL_SECTION lock;
1099 unsigned char buff[ BIP_BUFFER_SIZE ];
1100
1101} BipBufferRec, *BipBuffer;
1102
1103static void
1104bip_buffer_init( BipBuffer buffer )
1105{
Yabin Cui815ad882015-09-02 17:44:28 -07001106 D( "bit_buffer_init %p", buffer );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001107 buffer->a_start = 0;
1108 buffer->a_end = 0;
1109 buffer->b_end = 0;
1110 buffer->can_write = 1;
1111 buffer->can_read = 0;
1112 buffer->fdin = 0;
1113 buffer->fdout = 0;
1114 buffer->closed = 0;
1115 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1116 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1117 InitializeCriticalSection( &buffer->lock );
1118}
1119
1120static void
1121bip_buffer_close( BipBuffer bip )
1122{
1123 bip->closed = 1;
1124
1125 if (!bip->can_read) {
1126 SetEvent( bip->evt_read );
1127 }
1128 if (!bip->can_write) {
1129 SetEvent( bip->evt_write );
1130 }
1131}
1132
1133static void
1134bip_buffer_done( BipBuffer bip )
1135{
Yabin Cui815ad882015-09-02 17:44:28 -07001136 BIPD(( "bip_buffer_done: %d->%d", bip->fdin, bip->fdout ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001137 CloseHandle( bip->evt_read );
1138 CloseHandle( bip->evt_write );
1139 DeleteCriticalSection( &bip->lock );
1140}
1141
1142static int
1143bip_buffer_write( BipBuffer bip, const void* src, int len )
1144{
1145 int avail, count = 0;
1146
1147 if (len <= 0)
1148 return 0;
1149
Yabin Cui815ad882015-09-02 17:44:28 -07001150 BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001151 BIPDUMP( src, len );
1152
David Pursell7616ae12015-09-11 16:06:59 -07001153 if (bip->closed) {
1154 errno = EPIPE;
1155 return -1;
1156 }
1157
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001158 EnterCriticalSection( &bip->lock );
1159
1160 while (!bip->can_write) {
1161 int ret;
1162 LeaveCriticalSection( &bip->lock );
1163
1164 if (bip->closed) {
1165 errno = EPIPE;
1166 return -1;
1167 }
1168 /* spinlocking here is probably unfair, but let's live with it */
1169 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1170 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
Yabin Cui815ad882015-09-02 17:44:28 -07001171 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 -08001172 return 0;
1173 }
1174 if (bip->closed) {
1175 errno = EPIPE;
1176 return -1;
1177 }
1178 EnterCriticalSection( &bip->lock );
1179 }
1180
Yabin Cui815ad882015-09-02 17:44:28 -07001181 BIPD(( "bip_buffer_write: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001182
1183 avail = BIP_BUFFER_SIZE - bip->a_end;
1184 if (avail > 0)
1185 {
1186 /* we can append to region A */
1187 if (avail > len)
1188 avail = len;
1189
1190 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001191 src = (const char *)src + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001192 count += avail;
1193 len -= avail;
1194
1195 bip->a_end += avail;
1196 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1197 bip->can_write = 0;
1198 ResetEvent( bip->evt_write );
1199 goto Exit;
1200 }
1201 }
1202
1203 if (len == 0)
1204 goto Exit;
1205
1206 avail = bip->a_start - bip->b_end;
1207 assert( avail > 0 ); /* since can_write is TRUE */
1208
1209 if (avail > len)
1210 avail = len;
1211
1212 memcpy( bip->buff + bip->b_end, src, avail );
1213 count += avail;
1214 bip->b_end += avail;
1215
1216 if (bip->b_end == bip->a_start) {
1217 bip->can_write = 0;
1218 ResetEvent( bip->evt_write );
1219 }
1220
1221Exit:
1222 assert( count > 0 );
1223
1224 if ( !bip->can_read ) {
1225 bip->can_read = 1;
1226 SetEvent( bip->evt_read );
1227 }
1228
Yabin Cui815ad882015-09-02 17:44:28 -07001229 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 -08001230 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1231 LeaveCriticalSection( &bip->lock );
1232
1233 return count;
1234 }
1235
1236static int
1237bip_buffer_read( BipBuffer bip, void* dst, int len )
1238{
1239 int avail, count = 0;
1240
1241 if (len <= 0)
1242 return 0;
1243
Yabin Cui815ad882015-09-02 17:44:28 -07001244 BIPD(( "bip_buffer_read: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001245
1246 EnterCriticalSection( &bip->lock );
1247 while ( !bip->can_read )
1248 {
1249#if 0
1250 LeaveCriticalSection( &bip->lock );
1251 errno = EAGAIN;
1252 return -1;
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001253#else
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001254 int ret;
1255 LeaveCriticalSection( &bip->lock );
1256
1257 if (bip->closed) {
1258 errno = EPIPE;
1259 return -1;
1260 }
1261
1262 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1263 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
Yabin Cui815ad882015-09-02 17:44:28 -07001264 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 -08001265 return 0;
1266 }
1267 if (bip->closed) {
1268 errno = EPIPE;
1269 return -1;
1270 }
1271 EnterCriticalSection( &bip->lock );
1272#endif
1273 }
1274
Yabin Cui815ad882015-09-02 17:44:28 -07001275 BIPD(( "bip_buffer_read: exec %d->%d len %d", bip->fdin, bip->fdout, len ));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001276
1277 avail = bip->a_end - bip->a_start;
1278 assert( avail > 0 ); /* since can_read is TRUE */
1279
1280 if (avail > len)
1281 avail = len;
1282
1283 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn63e39f22014-04-30 09:10:31 -07001284 dst = (char *)dst + avail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001285 count += avail;
1286 len -= avail;
1287
1288 bip->a_start += avail;
1289 if (bip->a_start < bip->a_end)
1290 goto Exit;
1291
1292 bip->a_start = 0;
1293 bip->a_end = bip->b_end;
1294 bip->b_end = 0;
1295
1296 avail = bip->a_end;
1297 if (avail > 0) {
1298 if (avail > len)
1299 avail = len;
1300 memcpy( dst, bip->buff, avail );
1301 count += avail;
1302 bip->a_start += avail;
1303
1304 if ( bip->a_start < bip->a_end )
1305 goto Exit;
1306
1307 bip->a_start = bip->a_end = 0;
1308 }
1309
1310 bip->can_read = 0;
1311 ResetEvent( bip->evt_read );
1312
1313Exit:
1314 assert( count > 0 );
1315
1316 if (!bip->can_write ) {
1317 bip->can_write = 1;
1318 SetEvent( bip->evt_write );
1319 }
1320
1321 BIPDUMP( (const unsigned char*)dst - count, count );
Yabin Cui815ad882015-09-02 17:44:28 -07001322 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 -08001323 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1324 LeaveCriticalSection( &bip->lock );
1325
1326 return count;
1327}
1328
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001329typedef struct SocketPairRec_
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001330{
1331 BipBufferRec a2b_bip;
1332 BipBufferRec b2a_bip;
1333 FH a_fd;
1334 int used;
1335
1336} SocketPairRec;
1337
1338void _fh_socketpair_init( FH f )
1339{
1340 f->fh_pair = NULL;
1341}
1342
1343static int
1344_fh_socketpair_close( FH f )
1345{
1346 if ( f->fh_pair ) {
1347 SocketPair pair = f->fh_pair;
1348
1349 if ( f == pair->a_fd ) {
1350 pair->a_fd = NULL;
1351 }
1352
1353 bip_buffer_close( &pair->b2a_bip );
1354 bip_buffer_close( &pair->a2b_bip );
1355
1356 if ( --pair->used == 0 ) {
1357 bip_buffer_done( &pair->b2a_bip );
1358 bip_buffer_done( &pair->a2b_bip );
1359 free( pair );
1360 }
1361 f->fh_pair = NULL;
1362 }
1363 return 0;
1364}
1365
1366static int
1367_fh_socketpair_lseek( FH f, int pos, int origin )
1368{
1369 errno = ESPIPE;
1370 return -1;
1371}
1372
1373static int
1374_fh_socketpair_read( FH f, void* buf, int len )
1375{
1376 SocketPair pair = f->fh_pair;
1377 BipBuffer bip;
1378
1379 if (!pair)
1380 return -1;
1381
1382 if ( f == pair->a_fd )
1383 bip = &pair->b2a_bip;
1384 else
1385 bip = &pair->a2b_bip;
1386
1387 return bip_buffer_read( bip, buf, len );
1388}
1389
1390static int
1391_fh_socketpair_write( FH f, const void* buf, int len )
1392{
1393 SocketPair pair = f->fh_pair;
1394 BipBuffer bip;
1395
1396 if (!pair)
1397 return -1;
1398
1399 if ( f == pair->a_fd )
1400 bip = &pair->a2b_bip;
1401 else
1402 bip = &pair->b2a_bip;
1403
1404 return bip_buffer_write( bip, buf, len );
1405}
1406
1407
1408static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1409
1410static const FHClassRec _fh_socketpair_class =
1411{
1412 _fh_socketpair_init,
1413 _fh_socketpair_close,
1414 _fh_socketpair_lseek,
1415 _fh_socketpair_read,
1416 _fh_socketpair_write,
1417 _fh_socketpair_hook
1418};
1419
1420
Elliott Hughes6a096932015-04-16 16:47:02 -07001421int adb_socketpair(int sv[2]) {
1422 SocketPair pair;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001423
Spencer Low753d4852015-07-30 23:07:55 -07001424 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1425 if (!fa) {
1426 return -1;
1427 }
1428 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1429 if (!fb) {
1430 return -1;
1431 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001432
Elliott Hughes6a096932015-04-16 16:47:02 -07001433 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001434 if (pair == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001435 D("adb_socketpair: not enough memory to allocate pipes" );
Spencer Low753d4852015-07-30 23:07:55 -07001436 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001437 }
1438
1439 bip_buffer_init( &pair->a2b_bip );
1440 bip_buffer_init( &pair->b2a_bip );
1441
1442 fa->fh_pair = pair;
1443 fb->fh_pair = pair;
1444 pair->used = 2;
Spencer Low753d4852015-07-30 23:07:55 -07001445 pair->a_fd = fa.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001446
Spencer Low753d4852015-07-30 23:07:55 -07001447 sv[0] = _fh_to_int(fa.get());
1448 sv[1] = _fh_to_int(fb.get());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001449
1450 pair->a2b_bip.fdin = sv[0];
1451 pair->a2b_bip.fdout = sv[1];
1452 pair->b2a_bip.fdin = sv[1];
1453 pair->b2a_bip.fdout = sv[0];
1454
1455 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1456 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
Yabin Cui815ad882015-09-02 17:44:28 -07001457 D( "adb_socketpair: returns (%d, %d)", sv[0], sv[1] );
Spencer Low753d4852015-07-30 23:07:55 -07001458 fa.release();
1459 fb.release();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001460 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001461}
1462
1463/**************************************************************************/
1464/**************************************************************************/
1465/***** *****/
1466/***** fdevents emulation *****/
1467/***** *****/
1468/***** this is a very simple implementation, we rely on the fact *****/
1469/***** that ADB doesn't use FDE_ERROR. *****/
1470/***** *****/
1471/**************************************************************************/
1472/**************************************************************************/
1473
1474#define FATAL(x...) fatal(__FUNCTION__, x)
1475
1476#if DEBUG
1477static void dump_fde(fdevent *fde, const char *info)
1478{
1479 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1480 fde->state & FDE_READ ? 'R' : ' ',
1481 fde->state & FDE_WRITE ? 'W' : ' ',
1482 fde->state & FDE_ERROR ? 'E' : ' ',
1483 info);
1484}
1485#else
1486#define dump_fde(fde, info) do { } while(0)
1487#endif
1488
1489#define FDE_EVENTMASK 0x00ff
1490#define FDE_STATEMASK 0xff00
1491
1492#define FDE_ACTIVE 0x0100
1493#define FDE_PENDING 0x0200
1494#define FDE_CREATED 0x0400
1495
1496static void fdevent_plist_enqueue(fdevent *node);
1497static void fdevent_plist_remove(fdevent *node);
1498static fdevent *fdevent_plist_dequeue(void);
1499
1500static fdevent list_pending = {
1501 .next = &list_pending,
1502 .prev = &list_pending,
1503};
1504
1505static fdevent **fd_table = 0;
1506static int fd_table_max = 0;
1507
1508typedef struct EventLooperRec_* EventLooper;
1509
1510typedef struct EventHookRec_
1511{
1512 EventHook next;
1513 FH fh;
1514 HANDLE h;
1515 int wanted; /* wanted event flags */
1516 int ready; /* ready event flags */
1517 void* aux;
1518 void (*prepare)( EventHook hook );
1519 int (*start) ( EventHook hook );
1520 void (*stop) ( EventHook hook );
1521 int (*check) ( EventHook hook );
1522 int (*peek) ( EventHook hook );
1523} EventHookRec;
1524
1525static EventHook _free_hooks;
1526
1527static EventHook
Elliott Hughes6a096932015-04-16 16:47:02 -07001528event_hook_alloc(FH fh) {
1529 EventHook hook = _free_hooks;
1530 if (hook != NULL) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001531 _free_hooks = hook->next;
Elliott Hughes6a096932015-04-16 16:47:02 -07001532 } else {
1533 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001534 if (hook == NULL)
1535 fatal( "could not allocate event hook\n" );
1536 }
1537 hook->next = NULL;
1538 hook->fh = fh;
1539 hook->wanted = 0;
1540 hook->ready = 0;
1541 hook->h = INVALID_HANDLE_VALUE;
1542 hook->aux = NULL;
1543
1544 hook->prepare = NULL;
1545 hook->start = NULL;
1546 hook->stop = NULL;
1547 hook->check = NULL;
1548 hook->peek = NULL;
1549
1550 return hook;
1551}
1552
1553static void
1554event_hook_free( EventHook hook )
1555{
1556 hook->fh = NULL;
1557 hook->wanted = 0;
1558 hook->ready = 0;
1559 hook->next = _free_hooks;
1560 _free_hooks = hook;
1561}
1562
1563
1564static void
1565event_hook_signal( EventHook hook )
1566{
1567 FH f = hook->fh;
1568 int fd = _fh_to_int(f);
1569 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1570
1571 if (fde != NULL && fde->fd == fd) {
1572 if ((fde->state & FDE_PENDING) == 0) {
1573 fde->state |= FDE_PENDING;
1574 fdevent_plist_enqueue( fde );
1575 }
1576 fde->events |= hook->wanted;
1577 }
1578}
1579
1580
1581#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1582
1583typedef struct EventLooperRec_
1584{
1585 EventHook hooks;
1586 HANDLE htab[ MAX_LOOPER_HANDLES ];
1587 int htab_count;
1588
1589} EventLooperRec;
1590
1591static EventHook*
1592event_looper_find_p( EventLooper looper, FH fh )
1593{
1594 EventHook *pnode = &looper->hooks;
1595 EventHook node = *pnode;
1596 for (;;) {
1597 if ( node == NULL || node->fh == fh )
1598 break;
1599 pnode = &node->next;
1600 node = *pnode;
1601 }
1602 return pnode;
1603}
1604
1605static void
1606event_looper_hook( EventLooper looper, int fd, int events )
1607{
Spencer Low3a2421b2015-05-22 20:09:06 -07001608 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001609 EventHook *pnode;
1610 EventHook node;
1611
1612 if (f == NULL) /* invalid arg */ {
Yabin Cui815ad882015-09-02 17:44:28 -07001613 D("event_looper_hook: invalid fd=%d", fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001614 return;
1615 }
1616
1617 pnode = event_looper_find_p( looper, f );
1618 node = *pnode;
1619 if ( node == NULL ) {
1620 node = event_hook_alloc( f );
1621 node->next = *pnode;
1622 *pnode = node;
1623 }
1624
1625 if ( (node->wanted & events) != events ) {
1626 /* this should update start/stop/check/peek */
Yabin Cui815ad882015-09-02 17:44:28 -07001627 D("event_looper_hook: call hook for %d (new=%x, old=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001628 fd, node->wanted, events);
1629 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1630 node->wanted |= events;
1631 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07001632 D("event_looper_hook: ignoring events %x for %d wanted=%x)",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001633 events, fd, node->wanted);
1634 }
1635}
1636
1637static void
1638event_looper_unhook( EventLooper looper, int fd, int events )
1639{
Spencer Low3a2421b2015-05-22 20:09:06 -07001640 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001641 EventHook *pnode = event_looper_find_p( looper, fh );
1642 EventHook node = *pnode;
1643
1644 if (node != NULL) {
1645 int events2 = events & node->wanted;
1646 if ( events2 == 0 ) {
Yabin Cui815ad882015-09-02 17:44:28 -07001647 D( "event_looper_unhook: events %x not registered for fd %d", events, fd );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001648 return;
1649 }
1650 node->wanted &= ~events2;
1651 if (!node->wanted) {
1652 *pnode = node->next;
1653 event_hook_free( node );
1654 }
1655 }
1656}
1657
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001658/*
1659 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1660 * handles to wait on.
1661 *
1662 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1663 * instance, this may happen if there are more than 64 processes running on a
1664 * device, or there are multiple devices connected (including the emulator) with
1665 * the combined number of running processes greater than 64. In this case using
1666 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1667 * because of the API limitations (64 handles max). So, we need to provide a way
1668 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1669 * easiest (and "Microsoft recommended") way to do that would be dividing the
1670 * handle array into chunks with the chunk size less than 64, and fire up as many
1671 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1672 * handles, and will report back to the caller which handle has been set.
1673 * Here is the implementation of that algorithm.
1674 */
1675
1676/* Number of handles to wait on in each wating thread. */
1677#define WAIT_ALL_CHUNK_SIZE 63
1678
1679/* Descriptor for a wating thread */
1680typedef struct WaitForAllParam {
1681 /* A handle to an event to signal when waiting is over. This handle is shared
1682 * accross all the waiting threads, so each waiting thread knows when any
1683 * other thread has exited, so it can exit too. */
1684 HANDLE main_event;
1685 /* Upon exit from a waiting thread contains the index of the handle that has
1686 * been signaled. The index is an absolute index of the signaled handle in
1687 * the original array. This pointer is shared accross all the waiting threads
1688 * and it's not guaranteed (due to a race condition) that when all the
1689 * waiting threads exit, the value contained here would indicate the first
1690 * handle that was signaled. This is fine, because the caller cares only
1691 * about any handle being signaled. It doesn't care about the order, nor
1692 * about the whole list of handles that were signaled. */
1693 LONG volatile *signaled_index;
1694 /* Array of handles to wait on in a waiting thread. */
1695 HANDLE* handles;
1696 /* Number of handles in 'handles' array to wait on. */
1697 int handles_count;
1698 /* Index inside the main array of the first handle in the 'handles' array. */
1699 int first_handle_index;
1700 /* Waiting thread handle. */
1701 HANDLE thread;
1702} WaitForAllParam;
1703
1704/* Waiting thread routine. */
1705static unsigned __stdcall
1706_in_waiter_thread(void* arg)
1707{
1708 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1709 int res;
1710 WaitForAllParam* const param = (WaitForAllParam*)arg;
1711
1712 /* We have to wait on the main_event in order to be notified when any of the
1713 * sibling threads is exiting. */
1714 wait_on[0] = param->main_event;
1715 /* The rest of the handles go behind the main event handle. */
1716 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1717
1718 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1719 if (res > 0 && res < (param->handles_count + 1)) {
1720 /* One of the original handles got signaled. Save its absolute index into
1721 * the output variable. */
1722 InterlockedCompareExchange(param->signaled_index,
1723 res - 1L + param->first_handle_index, -1L);
1724 }
1725
1726 /* Notify the caller (and the siblings) that the wait is over. */
1727 SetEvent(param->main_event);
1728
1729 _endthreadex(0);
1730 return 0;
1731}
1732
1733/* WaitForMultipeObjects fixer routine.
1734 * Param:
1735 * handles Array of handles to wait on.
1736 * handles_count Number of handles in the array.
1737 * Return:
1738 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1739 * WAIT_FAILED on an error.
1740 */
1741static int
1742_wait_for_all(HANDLE* handles, int handles_count)
1743{
1744 WaitForAllParam* threads;
1745 HANDLE main_event;
1746 int chunks, chunk, remains;
1747
1748 /* This variable is going to be accessed by several threads at the same time,
1749 * this is bound to fail randomly when the core is run on multi-core machines.
1750 * To solve this, we need to do the following (1 _and_ 2):
1751 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1752 * out the reads/writes in this function unexpectedly.
1753 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1754 * all accesses inside a critical section. But we can also use
1755 * InterlockedCompareExchange() which always provide a full memory barrier
1756 * on Win32.
1757 */
1758 volatile LONG sig_index = -1;
1759
1760 /* Calculate number of chunks, and allocate thread param array. */
1761 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1762 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1763 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1764 sizeof(WaitForAllParam));
1765 if (threads == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001766 D("Unable to allocate thread array for %d handles.", handles_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001767 return (int)WAIT_FAILED;
1768 }
1769
1770 /* Create main event to wait on for all waiting threads. This is a "manualy
1771 * reset" event that will remain set once it was set. */
1772 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1773 if (main_event == NULL) {
Yabin Cui815ad882015-09-02 17:44:28 -07001774 D("Unable to create main event. Error: %ld", GetLastError());
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001775 free(threads);
1776 return (int)WAIT_FAILED;
1777 }
1778
1779 /*
1780 * Initialize waiting thread parameters.
1781 */
1782
1783 for (chunk = 0; chunk < chunks; chunk++) {
1784 threads[chunk].main_event = main_event;
1785 threads[chunk].signaled_index = &sig_index;
1786 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1787 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1788 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1789 }
1790 if (remains) {
1791 threads[chunk].main_event = main_event;
1792 threads[chunk].signaled_index = &sig_index;
1793 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1794 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1795 threads[chunk].handles_count = remains;
1796 chunks++;
1797 }
1798
1799 /* Start the waiting threads. */
1800 for (chunk = 0; chunk < chunks; chunk++) {
1801 /* Note that using adb_thread_create is not appropriate here, since we
1802 * need a handle to wait on for thread termination. */
1803 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1804 &threads[chunk], 0, NULL);
1805 if (threads[chunk].thread == NULL) {
1806 /* Unable to create a waiter thread. Collapse. */
Yabin Cui815ad882015-09-02 17:44:28 -07001807 D("Unable to create a waiting thread %d of %d. errno=%d",
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001808 chunk, chunks, errno);
1809 chunks = chunk;
1810 SetEvent(main_event);
1811 break;
1812 }
1813 }
1814
1815 /* Wait on any of the threads to get signaled. */
1816 WaitForSingleObject(main_event, INFINITE);
1817
1818 /* Wait on all the waiting threads to exit. */
1819 for (chunk = 0; chunk < chunks; chunk++) {
1820 WaitForSingleObject(threads[chunk].thread, INFINITE);
1821 CloseHandle(threads[chunk].thread);
1822 }
1823
1824 CloseHandle(main_event);
1825 free(threads);
1826
1827
1828 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1829 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1830}
1831
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001832static EventLooperRec win32_looper;
1833
1834static void fdevent_init(void)
1835{
1836 win32_looper.htab_count = 0;
1837 win32_looper.hooks = NULL;
1838}
1839
1840static void fdevent_connect(fdevent *fde)
1841{
1842 EventLooper looper = &win32_looper;
1843 int events = fde->state & FDE_EVENTMASK;
1844
1845 if (events != 0)
1846 event_looper_hook( looper, fde->fd, events );
1847}
1848
1849static void fdevent_disconnect(fdevent *fde)
1850{
1851 EventLooper looper = &win32_looper;
1852 int events = fde->state & FDE_EVENTMASK;
1853
1854 if (events != 0)
1855 event_looper_unhook( looper, fde->fd, events );
1856}
1857
1858static void fdevent_update(fdevent *fde, unsigned events)
1859{
1860 EventLooper looper = &win32_looper;
1861 unsigned events0 = fde->state & FDE_EVENTMASK;
1862
1863 if (events != events0) {
1864 int removes = events0 & ~events;
1865 int adds = events & ~events0;
1866 if (removes) {
Yabin Cui815ad882015-09-02 17:44:28 -07001867 D("fdevent_update: remove %x from %d", removes, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001868 event_looper_unhook( looper, fde->fd, removes );
1869 }
1870 if (adds) {
Yabin Cui815ad882015-09-02 17:44:28 -07001871 D("fdevent_update: add %x to %d", adds, fde->fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001872 event_looper_hook ( looper, fde->fd, adds );
1873 }
1874 }
1875}
1876
1877static void fdevent_process()
1878{
1879 EventLooper looper = &win32_looper;
1880 EventHook hook;
1881 int gotone = 0;
1882
1883 /* if we have at least one ready hook, execute it/them */
1884 for (hook = looper->hooks; hook; hook = hook->next) {
1885 hook->ready = 0;
1886 if (hook->prepare) {
1887 hook->prepare(hook);
1888 if (hook->ready != 0) {
1889 event_hook_signal( hook );
1890 gotone = 1;
1891 }
1892 }
1893 }
1894
1895 /* nothing's ready yet, so wait for something to happen */
1896 if (!gotone)
1897 {
1898 looper->htab_count = 0;
1899
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001900 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001901 {
1902 if (hook->start && !hook->start(hook)) {
Yabin Cui815ad882015-09-02 17:44:28 -07001903 D( "fdevent_process: error when starting a hook" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001904 return;
1905 }
1906 if (hook->h != INVALID_HANDLE_VALUE) {
1907 int nn;
1908
1909 for (nn = 0; nn < looper->htab_count; nn++)
1910 {
1911 if ( looper->htab[nn] == hook->h )
1912 goto DontAdd;
1913 }
1914 looper->htab[ looper->htab_count++ ] = hook->h;
1915 DontAdd:
1916 ;
1917 }
1918 }
1919
1920 if (looper->htab_count == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -07001921 D( "fdevent_process: nothing to wait for !!" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001922 return;
1923 }
1924
1925 do
1926 {
1927 int wait_ret;
1928
Yabin Cui815ad882015-09-02 17:44:28 -07001929 D( "adb_win32: waiting for %d events", looper->htab_count );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001930 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Yabin Cui815ad882015-09-02 17:44:28 -07001931 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.", looper->htab_count);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08001932 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1933 } else {
1934 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001935 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001936 if (wait_ret == (int)WAIT_FAILED) {
Yabin Cui815ad882015-09-02 17:44:28 -07001937 D( "adb_win32: wait failed, error %ld", GetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001938 } else {
Yabin Cui815ad882015-09-02 17:44:28 -07001939 D( "adb_win32: got one (index %d)", wait_ret );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001940
1941 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1942 * like mouse movements. we need to filter these with the "check" function
1943 */
1944 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1945 {
1946 for (hook = looper->hooks; hook; hook = hook->next)
1947 {
1948 if ( looper->htab[wait_ret] == hook->h &&
1949 (!hook->check || hook->check(hook)) )
1950 {
Yabin Cui815ad882015-09-02 17:44:28 -07001951 D( "adb_win32: signaling %s for %x", hook->fh->name, hook->ready );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001952 event_hook_signal( hook );
1953 gotone = 1;
1954 break;
1955 }
1956 }
1957 }
1958 }
1959 }
1960 while (!gotone);
1961
1962 for (hook = looper->hooks; hook; hook = hook->next) {
1963 if (hook->stop)
1964 hook->stop( hook );
1965 }
1966 }
1967
1968 for (hook = looper->hooks; hook; hook = hook->next) {
1969 if (hook->peek && hook->peek(hook))
1970 event_hook_signal( hook );
1971 }
1972}
1973
1974
1975static void fdevent_register(fdevent *fde)
1976{
1977 int fd = fde->fd - WIN32_FH_BASE;
1978
1979 if(fd < 0) {
1980 FATAL("bogus negative fd (%d)\n", fde->fd);
1981 }
1982
1983 if(fd >= fd_table_max) {
1984 int oldmax = fd_table_max;
1985 if(fde->fd > 32000) {
1986 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1987 }
1988 if(fd_table_max == 0) {
1989 fdevent_init();
1990 fd_table_max = 256;
1991 }
1992 while(fd_table_max <= fd) {
1993 fd_table_max *= 2;
1994 }
Elliott Hughes6a096932015-04-16 16:47:02 -07001995 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001996 if(fd_table == 0) {
1997 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1998 }
1999 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
2000 }
2001
2002 fd_table[fd] = fde;
2003}
2004
2005static void fdevent_unregister(fdevent *fde)
2006{
2007 int fd = fde->fd - WIN32_FH_BASE;
2008
2009 if((fd < 0) || (fd >= fd_table_max)) {
2010 FATAL("fd out of range (%d)\n", fde->fd);
2011 }
2012
2013 if(fd_table[fd] != fde) {
2014 FATAL("fd_table out of sync");
2015 }
2016
2017 fd_table[fd] = 0;
2018
2019 if(!(fde->state & FDE_DONT_CLOSE)) {
2020 dump_fde(fde, "close");
2021 adb_close(fde->fd);
2022 }
2023}
2024
2025static void fdevent_plist_enqueue(fdevent *node)
2026{
2027 fdevent *list = &list_pending;
2028
2029 node->next = list;
2030 node->prev = list->prev;
2031 node->prev->next = node;
2032 list->prev = node;
2033}
2034
2035static void fdevent_plist_remove(fdevent *node)
2036{
2037 node->prev->next = node->next;
2038 node->next->prev = node->prev;
2039 node->next = 0;
2040 node->prev = 0;
2041}
2042
2043static fdevent *fdevent_plist_dequeue(void)
2044{
2045 fdevent *list = &list_pending;
2046 fdevent *node = list->next;
2047
2048 if(node == list) return 0;
2049
2050 list->next = node->next;
2051 list->next->prev = list;
2052 node->next = 0;
2053 node->prev = 0;
2054
2055 return node;
2056}
2057
2058fdevent *fdevent_create(int fd, fd_func func, void *arg)
2059{
2060 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
2061 if(fde == 0) return 0;
2062 fdevent_install(fde, fd, func, arg);
2063 fde->state |= FDE_CREATED;
2064 return fde;
2065}
2066
2067void fdevent_destroy(fdevent *fde)
2068{
2069 if(fde == 0) return;
2070 if(!(fde->state & FDE_CREATED)) {
2071 FATAL("fde %p not created by fdevent_create()\n", fde);
2072 }
2073 fdevent_remove(fde);
2074}
2075
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002076void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002077{
2078 memset(fde, 0, sizeof(fdevent));
2079 fde->state = FDE_ACTIVE;
2080 fde->fd = fd;
2081 fde->func = func;
2082 fde->arg = arg;
2083
2084 fdevent_register(fde);
2085 dump_fde(fde, "connect");
2086 fdevent_connect(fde);
2087 fde->state |= FDE_ACTIVE;
2088}
2089
2090void fdevent_remove(fdevent *fde)
2091{
2092 if(fde->state & FDE_PENDING) {
2093 fdevent_plist_remove(fde);
2094 }
2095
2096 if(fde->state & FDE_ACTIVE) {
2097 fdevent_disconnect(fde);
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002098 dump_fde(fde, "disconnect");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002099 fdevent_unregister(fde);
2100 }
2101
2102 fde->state = 0;
2103 fde->events = 0;
2104}
2105
2106
2107void fdevent_set(fdevent *fde, unsigned events)
2108{
2109 events &= FDE_EVENTMASK;
2110
2111 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2112
2113 if(fde->state & FDE_ACTIVE) {
2114 fdevent_update(fde, events);
2115 dump_fde(fde, "update");
2116 }
2117
2118 fde->state = (fde->state & FDE_STATEMASK) | events;
2119
2120 if(fde->state & FDE_PENDING) {
2121 /* if we're pending, make sure
2122 ** we don't signal an event that
2123 ** is no longer wanted.
2124 */
2125 fde->events &= (~events);
2126 if(fde->events == 0) {
2127 fdevent_plist_remove(fde);
2128 fde->state &= (~FDE_PENDING);
2129 }
2130 }
2131}
2132
2133void fdevent_add(fdevent *fde, unsigned events)
2134{
2135 fdevent_set(
2136 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2137}
2138
2139void fdevent_del(fdevent *fde, unsigned events)
2140{
2141 fdevent_set(
2142 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2143}
2144
2145void fdevent_loop()
2146{
2147 fdevent *fde;
2148
2149 for(;;) {
2150#if DEBUG
2151 fprintf(stderr,"--- ---- waiting for events\n");
2152#endif
2153 fdevent_process();
2154
2155 while((fde = fdevent_plist_dequeue())) {
2156 unsigned events = fde->events;
2157 fde->events = 0;
2158 fde->state &= (~FDE_PENDING);
2159 dump_fde(fde, "callback");
2160 fde->func(fde->fd, events, fde->arg);
2161 }
2162 }
2163}
2164
2165/** FILE EVENT HOOKS
2166 **/
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02002167
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002168static void _event_file_prepare( EventHook hook )
2169{
2170 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2171 /* we can always read/write */
2172 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2173 }
2174}
2175
2176static int _event_file_peek( EventHook hook )
2177{
2178 return (hook->wanted & (FDE_READ|FDE_WRITE));
2179}
2180
2181static void _fh_file_hook( FH f, int events, EventHook hook )
2182{
2183 hook->h = f->fh_handle;
2184 hook->prepare = _event_file_prepare;
2185 hook->peek = _event_file_peek;
2186}
2187
2188/** SOCKET EVENT HOOKS
2189 **/
2190
2191static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2192{
2193 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2194 if (hook->wanted & FDE_READ)
2195 hook->ready |= FDE_READ;
2196 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2197 hook->ready |= FDE_ERROR;
2198 }
2199 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2200 if (hook->wanted & FDE_WRITE)
2201 hook->ready |= FDE_WRITE;
2202 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2203 hook->ready |= FDE_ERROR;
2204 }
2205 if ( evts->lNetworkEvents & FD_OOB ) {
2206 if (hook->wanted & FDE_ERROR)
2207 hook->ready |= FDE_ERROR;
2208 }
2209}
2210
2211static void _event_socket_prepare( EventHook hook )
2212{
2213 WSANETWORKEVENTS evts;
2214
2215 /* look if some of the events we want already happened ? */
2216 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2217 _event_socket_verify( hook, &evts );
2218}
2219
2220static int _socket_wanted_to_flags( int wanted )
2221{
2222 int flags = 0;
2223 if (wanted & FDE_READ)
2224 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2225
2226 if (wanted & FDE_WRITE)
2227 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2228
2229 if (wanted & FDE_ERROR)
2230 flags |= FD_OOB;
2231
2232 return flags;
2233}
2234
2235static int _event_socket_start( EventHook hook )
2236{
2237 /* create an event which we're going to wait for */
2238 FH fh = hook->fh;
2239 long flags = _socket_wanted_to_flags( hook->wanted );
2240
2241 hook->h = fh->event;
2242 if (hook->h == INVALID_HANDLE_VALUE) {
Yabin Cui815ad882015-09-02 17:44:28 -07002243 D( "_event_socket_start: no event for %s", fh->name );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002244 return 0;
2245 }
2246
2247 if ( flags != fh->mask ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002248 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 -08002249 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
Yabin Cui815ad882015-09-02 17:44:28 -07002250 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d", hook->fh->name, WSAGetLastError() );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002251 CloseHandle( hook->h );
2252 hook->h = INVALID_HANDLE_VALUE;
2253 exit(1);
2254 return 0;
2255 }
2256 fh->mask = flags;
2257 }
2258 return 1;
2259}
2260
2261static void _event_socket_stop( EventHook hook )
2262{
2263 hook->h = INVALID_HANDLE_VALUE;
2264}
2265
2266static int _event_socket_check( EventHook hook )
2267{
2268 int result = 0;
2269 FH fh = hook->fh;
2270 WSANETWORKEVENTS evts;
2271
2272 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2273 _event_socket_verify( hook, &evts );
2274 result = (hook->ready != 0);
2275 if (result) {
2276 ResetEvent( hook->h );
2277 }
2278 }
Yabin Cui815ad882015-09-02 17:44:28 -07002279 D( "_event_socket_check %s returns %d", fh->name, result );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002280 return result;
2281}
2282
2283static int _event_socket_peek( EventHook hook )
2284{
2285 WSANETWORKEVENTS evts;
2286 FH fh = hook->fh;
2287
2288 /* look if some of the events we want already happened ? */
2289 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2290 _event_socket_verify( hook, &evts );
2291 if (hook->ready)
2292 ResetEvent( hook->h );
2293 }
2294
2295 return hook->ready != 0;
2296}
2297
2298
2299
2300static void _fh_socket_hook( FH f, int events, EventHook hook )
2301{
2302 hook->prepare = _event_socket_prepare;
2303 hook->start = _event_socket_start;
2304 hook->stop = _event_socket_stop;
2305 hook->check = _event_socket_check;
2306 hook->peek = _event_socket_peek;
2307
Spencer Low753d4852015-07-30 23:07:55 -07002308 // TODO: check return value?
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002309 _event_socket_start( hook );
2310}
2311
2312/** SOCKETPAIR EVENT HOOKS
2313 **/
2314
2315static void _event_socketpair_prepare( EventHook hook )
2316{
2317 FH fh = hook->fh;
2318 SocketPair pair = fh->fh_pair;
2319 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2320 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2321
2322 if (hook->wanted & FDE_READ && rbip->can_read)
2323 hook->ready |= FDE_READ;
2324
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -08002325 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002326 hook->ready |= FDE_WRITE;
2327 }
2328
2329 static int _event_socketpair_start( EventHook hook )
2330 {
2331 FH fh = hook->fh;
2332 SocketPair pair = fh->fh_pair;
2333 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2334 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2335
2336 if (hook->wanted == FDE_READ)
2337 hook->h = rbip->evt_read;
2338
2339 else if (hook->wanted == FDE_WRITE)
2340 hook->h = wbip->evt_write;
2341
2342 else {
Yabin Cui815ad882015-09-02 17:44:28 -07002343 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE" );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002344 return 0;
2345 }
Yabin Cui815ad882015-09-02 17:44:28 -07002346 D( "_event_socketpair_start: hook %s for %x wanted=%x",
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002347 hook->fh->name, _fh_to_int(fh), hook->wanted);
2348 return 1;
2349}
2350
2351static int _event_socketpair_peek( EventHook hook )
2352{
2353 _event_socketpair_prepare( hook );
2354 return hook->ready != 0;
2355}
2356
2357static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2358{
2359 hook->prepare = _event_socketpair_prepare;
2360 hook->start = _event_socketpair_start;
2361 hook->peek = _event_socketpair_peek;
2362}
2363
2364
2365void
2366adb_sysdeps_init( void )
2367{
2368#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2369#include "mutex_list.h"
2370 InitializeCriticalSection( &_win32_lock );
2371}
2372
Spencer Lowbeb61982015-03-01 15:06:21 -08002373/**************************************************************************/
2374/**************************************************************************/
2375/***** *****/
2376/***** Console Window Terminal Emulation *****/
2377/***** *****/
2378/**************************************************************************/
2379/**************************************************************************/
2380
2381// This reads input from a Win32 console window and translates it into Unix
2382// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2383// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2384// is emulated instead of xterm because it is probably more popular than xterm:
2385// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2386// supports modern fonts, etc. It seems best to emulate the terminal that most
2387// Android developers use because they'll fix apps (the shell, etc.) to keep
2388// working with that terminal's emulation.
2389//
2390// The point of this emulation is not to be perfect or to solve all issues with
2391// console windows on Windows, but to be better than the original code which
2392// just called read() (which called ReadFile(), which called ReadConsoleA())
2393// which did not support Ctrl-C, tab completion, shell input line editing
2394// keys, server echo, and more.
2395//
2396// This implementation reconfigures the console with SetConsoleMode(), then
2397// calls ReadConsoleInput() to get raw input which it remaps to Unix
2398// terminal-style sequences which is returned via unix_read() which is used
2399// by the 'adb shell' command.
2400//
2401// Code organization:
2402//
2403// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2404// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2405// * _console_read() is the main code of the emulation.
2406
2407
2408// Read an input record from the console; one that should be processed.
2409static bool _get_interesting_input_record_uncached(const HANDLE console,
2410 INPUT_RECORD* const input_record) {
2411 for (;;) {
2412 DWORD read_count = 0;
2413 memset(input_record, 0, sizeof(*input_record));
2414 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2415 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
Spencer Low1711e012015-08-02 18:50:17 -07002416 "failed: %s\n", SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002417 errno = EIO;
2418 return false;
2419 }
2420
2421 if (read_count == 0) { // should be impossible
2422 fatal("ReadConsoleInputA returned 0");
2423 }
2424
2425 if (read_count != 1) { // should be impossible
2426 fatal("ReadConsoleInputA did not return one input record");
2427 }
2428
2429 if ((input_record->EventType == KEY_EVENT) &&
2430 (input_record->Event.KeyEvent.bKeyDown)) {
2431 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2432 fatal("ReadConsoleInputA returned a key event with zero repeat"
2433 " count");
2434 }
2435
2436 // Got an interesting INPUT_RECORD, so return
2437 return true;
2438 }
2439 }
2440}
2441
2442// Cached input record (in case _console_read() is passed a buffer that doesn't
2443// have enough space to fit wRepeatCount number of key sequences). A non-zero
2444// wRepeatCount indicates that a record is cached.
2445static INPUT_RECORD _win32_input_record;
2446
2447// Get the next KEY_EVENT_RECORD that should be processed.
2448static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2449 // If nothing cached, read directly from the console until we get an
2450 // interesting record.
2451 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2452 if (!_get_interesting_input_record_uncached(console,
2453 &_win32_input_record)) {
2454 // There was an error, so make sure wRepeatCount is zero because
2455 // that signifies no cached input record.
2456 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2457 return NULL;
2458 }
2459 }
2460
2461 return &_win32_input_record.Event.KeyEvent;
2462}
2463
2464static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2465 return (control_key_state & SHIFT_PRESSED) != 0;
2466}
2467
2468static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2469 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2470}
2471
2472static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2473 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2474}
2475
2476static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2477 return (control_key_state & NUMLOCK_ON) != 0;
2478}
2479
2480static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2481 return (control_key_state & CAPSLOCK_ON) != 0;
2482}
2483
2484static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2485 return (control_key_state & ENHANCED_KEY) != 0;
2486}
2487
2488// Constants from MSDN for ToAscii().
2489static const BYTE TOASCII_KEY_OFF = 0x00;
2490static const BYTE TOASCII_KEY_DOWN = 0x80;
2491static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2492
2493// Given a key event, ignore a modifier key and return the character that was
2494// entered without the modifier. Writes to *ch and returns the number of bytes
2495// written.
2496static size_t _get_char_ignoring_modifier(char* const ch,
2497 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2498 const WORD modifier) {
2499 // If there is no character from Windows, try ignoring the specified
2500 // modifier and look for a character. Note that if AltGr is being used,
2501 // there will be a character from Windows.
2502 if (key_event->uChar.AsciiChar == '\0') {
2503 // Note that we read the control key state from the passed in argument
2504 // instead of from key_event since the argument has been normalized.
2505 if (((modifier == VK_SHIFT) &&
2506 _is_shift_pressed(control_key_state)) ||
2507 ((modifier == VK_CONTROL) &&
2508 _is_ctrl_pressed(control_key_state)) ||
2509 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2510
2511 BYTE key_state[256] = {0};
2512 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2513 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2514 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2515 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2516 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2517 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2518 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2519 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2520
2521 // cause this modifier to be ignored
2522 key_state[modifier] = TOASCII_KEY_OFF;
2523
2524 WORD translated = 0;
2525 if (ToAscii(key_event->wVirtualKeyCode,
2526 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2527 // Ignoring the modifier, we found a character.
2528 *ch = (CHAR)translated;
2529 return 1;
2530 }
2531 }
2532 }
2533
2534 // Just use whatever Windows told us originally.
2535 *ch = key_event->uChar.AsciiChar;
2536
2537 // If the character from Windows is NULL, return a size of zero.
2538 return (*ch == '\0') ? 0 : 1;
2539}
2540
2541// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2542// but taking into account the shift key. This is because for a sequence like
2543// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2544// we want to find the character ')'.
2545//
2546// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2547// because it is the default key-sequence to switch the input language.
2548// This is configurable in the Region and Language control panel.
2549static __inline__ size_t _get_non_control_char(char* const ch,
2550 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2551 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2552 VK_CONTROL);
2553}
2554
2555// Get without Alt.
2556static __inline__ size_t _get_non_alt_char(char* const ch,
2557 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2558 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2559 VK_MENU);
2560}
2561
2562// Ignore the control key, find the character from Windows, and apply any
2563// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2564// *pch and returns number of bytes written.
2565static size_t _get_control_character(char* const pch,
2566 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2567 const size_t len = _get_non_control_char(pch, key_event,
2568 control_key_state);
2569
2570 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2571 char ch = *pch;
2572 switch (ch) {
2573 case '2':
2574 case '@':
2575 case '`':
2576 ch = '\0';
2577 break;
2578 case '3':
2579 case '[':
2580 case '{':
2581 ch = '\x1b';
2582 break;
2583 case '4':
2584 case '\\':
2585 case '|':
2586 ch = '\x1c';
2587 break;
2588 case '5':
2589 case ']':
2590 case '}':
2591 ch = '\x1d';
2592 break;
2593 case '6':
2594 case '^':
2595 case '~':
2596 ch = '\x1e';
2597 break;
2598 case '7':
2599 case '-':
2600 case '_':
2601 ch = '\x1f';
2602 break;
2603 case '8':
2604 ch = '\x7f';
2605 break;
2606 case '/':
2607 if (!_is_alt_pressed(control_key_state)) {
2608 ch = '\x1f';
2609 }
2610 break;
2611 case '?':
2612 if (!_is_alt_pressed(control_key_state)) {
2613 ch = '\x7f';
2614 }
2615 break;
2616 }
2617 *pch = ch;
2618 }
2619
2620 return len;
2621}
2622
2623static DWORD _normalize_altgr_control_key_state(
2624 const KEY_EVENT_RECORD* const key_event) {
2625 DWORD control_key_state = key_event->dwControlKeyState;
2626
2627 // If we're in an AltGr situation where the AltGr key is down (depending on
2628 // the keyboard layout, that might be the physical right alt key which
2629 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2630 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2631 // a character (which indicates that there was an AltGr mapping), then act
2632 // as if alt and control are not really down for the purposes of modifiers.
2633 // This makes it so that if the user with, say, a German keyboard layout
2634 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2635 // output the key and we don't see the Alt and Ctrl keys.
2636 if (_is_ctrl_pressed(control_key_state) &&
2637 _is_alt_pressed(control_key_state)
2638 && (key_event->uChar.AsciiChar != '\0')) {
2639 // Try to remove as few bits as possible to improve our chances of
2640 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2641 // Left-Alt + Right-Ctrl + AltGr.
2642 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2643 // Remove Right-Alt.
2644 control_key_state &= ~RIGHT_ALT_PRESSED;
2645 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2646 // pressed, Left-Ctrl is almost always set, except if the user
2647 // presses Right-Ctrl, then AltGr (in that specific order) for
2648 // whatever reason. At any rate, make sure the bit is not set.
2649 control_key_state &= ~LEFT_CTRL_PRESSED;
2650 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2651 // Remove Left-Alt.
2652 control_key_state &= ~LEFT_ALT_PRESSED;
2653 // Whichever Ctrl key is down, remove it from the state. We only
2654 // remove one key, to improve our chances of detecting the
2655 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2656 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2657 // Remove Left-Ctrl.
2658 control_key_state &= ~LEFT_CTRL_PRESSED;
2659 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2660 // Remove Right-Ctrl.
2661 control_key_state &= ~RIGHT_CTRL_PRESSED;
2662 }
2663 }
2664
2665 // Note that this logic isn't 100% perfect because Windows doesn't
2666 // allow us to detect all combinations because a physical AltGr key
2667 // press shows up as two bits, plus some combinations are ambiguous
2668 // about what is actually physically pressed.
2669 }
2670
2671 return control_key_state;
2672}
2673
2674// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2675// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2676// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2677// appropriately.
2678static DWORD _normalize_keypad_control_key_state(const WORD vk,
2679 const DWORD control_key_state) {
2680 if (!_is_numlock_on(control_key_state)) {
2681 return control_key_state;
2682 }
2683 if (!_is_enhanced_key(control_key_state)) {
2684 switch (vk) {
2685 case VK_INSERT: // 0
2686 case VK_DELETE: // .
2687 case VK_END: // 1
2688 case VK_DOWN: // 2
2689 case VK_NEXT: // 3
2690 case VK_LEFT: // 4
2691 case VK_CLEAR: // 5
2692 case VK_RIGHT: // 6
2693 case VK_HOME: // 7
2694 case VK_UP: // 8
2695 case VK_PRIOR: // 9
2696 return control_key_state | SHIFT_PRESSED;
2697 }
2698 }
2699
2700 return control_key_state;
2701}
2702
2703static const char* _get_keypad_sequence(const DWORD control_key_state,
2704 const char* const normal, const char* const shifted) {
2705 if (_is_shift_pressed(control_key_state)) {
2706 // Shift is pressed and NumLock is off
2707 return shifted;
2708 } else {
2709 // Shift is not pressed and NumLock is off, or,
2710 // Shift is pressed and NumLock is on, in which case we want the
2711 // NumLock and Shift to neutralize each other, thus, we want the normal
2712 // sequence.
2713 return normal;
2714 }
2715 // If Shift is not pressed and NumLock is on, a different virtual key code
2716 // is returned by Windows, which can be taken care of by a different case
2717 // statement in _console_read().
2718}
2719
2720// Write sequence to buf and return the number of bytes written.
2721static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2722 DWORD control_key_state, const char* const normal) {
2723 // Copy the base sequence into buf.
2724 const size_t len = strlen(normal);
2725 memcpy(buf, normal, len);
2726
2727 int code = 0;
2728
2729 control_key_state = _normalize_keypad_control_key_state(vk,
2730 control_key_state);
2731
2732 if (_is_shift_pressed(control_key_state)) {
2733 code |= 0x1;
2734 }
2735 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2736 code |= 0x2;
2737 }
2738 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2739 code |= 0x4;
2740 }
2741 // If some modifier was held down, then we need to insert the modifier code
2742 if (code != 0) {
2743 if (len == 0) {
2744 // Should be impossible because caller should pass a string of
2745 // non-zero length.
2746 return 0;
2747 }
2748 size_t index = len - 1;
2749 const char lastChar = buf[index];
2750 if (lastChar != '~') {
2751 buf[index++] = '1';
2752 }
2753 buf[index++] = ';'; // modifier separator
2754 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2755 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2756 buf[index++] = '1' + code;
2757 buf[index++] = lastChar; // move ~ (or other last char) to the end
2758 return index;
2759 }
2760 return len;
2761}
2762
2763// Write sequence to buf and return the number of bytes written.
2764static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2765 const DWORD control_key_state, const char* const normal,
2766 const char shifted) {
2767 if (_is_shift_pressed(control_key_state)) {
2768 // Shift is pressed and NumLock is off
2769 if (shifted != '\0') {
2770 buf[0] = shifted;
2771 return sizeof(buf[0]);
2772 } else {
2773 return 0;
2774 }
2775 } else {
2776 // Shift is not pressed and NumLock is off, or,
2777 // Shift is pressed and NumLock is on, in which case we want the
2778 // NumLock and Shift to neutralize each other, thus, we want the normal
2779 // sequence.
2780 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2781 }
2782 // If Shift is not pressed and NumLock is on, a different virtual key code
2783 // is returned by Windows, which can be taken care of by a different case
2784 // statement in _console_read().
2785}
2786
2787// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2788// Standard German. Figure this out at runtime so we know what to output for
2789// Shift-VK_DELETE.
2790static char _get_decimal_char() {
2791 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2792}
2793
2794// Prefix the len bytes in buf with the escape character, and then return the
2795// new buffer length.
2796size_t _escape_prefix(char* const buf, const size_t len) {
2797 // If nothing to prefix, don't do anything. We might be called with
2798 // len == 0, if alt was held down with a dead key which produced nothing.
2799 if (len == 0) {
2800 return 0;
2801 }
2802
2803 memmove(&buf[1], buf, len);
2804 buf[0] = '\x1b';
2805 return len + 1;
2806}
2807
2808// Writes to buffer buf (of length len), returning number of bytes written or
2809// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2810// (as far as I can tell).
2811static int _console_read(const HANDLE console, void* buf, size_t len) {
2812 for (;;) {
2813 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2814 if (key_event == NULL) {
2815 return -1;
2816 }
2817
2818 const WORD vk = key_event->wVirtualKeyCode;
2819 const CHAR ch = key_event->uChar.AsciiChar;
2820 const DWORD control_key_state = _normalize_altgr_control_key_state(
2821 key_event);
2822
2823 // The following emulation code should write the output sequence to
2824 // either seqstr or to seqbuf and seqbuflen.
2825 const char* seqstr = NULL; // NULL terminated C-string
2826 // Enough space for max sequence string below, plus modifiers and/or
2827 // escape prefix.
2828 char seqbuf[16];
2829 size_t seqbuflen = 0; // Space used in seqbuf.
2830
2831#define MATCH(vk, normal) \
2832 case (vk): \
2833 { \
2834 seqstr = (normal); \
2835 } \
2836 break;
2837
2838 // Modifier keys should affect the output sequence.
2839#define MATCH_MODIFIER(vk, normal) \
2840 case (vk): \
2841 { \
2842 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2843 control_key_state, (normal)); \
2844 } \
2845 break;
2846
2847 // The shift key should affect the output sequence.
2848#define MATCH_KEYPAD(vk, normal, shifted) \
2849 case (vk): \
2850 { \
2851 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2852 (shifted)); \
2853 } \
2854 break;
2855
2856 // The shift key and other modifier keys should affect the output
2857 // sequence.
2858#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2859 case (vk): \
2860 { \
2861 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2862 control_key_state, (normal), (shifted)); \
2863 } \
2864 break;
2865
2866#define ESC "\x1b"
2867#define CSI ESC "["
2868#define SS3 ESC "O"
2869
2870 // Only support normal mode, not application mode.
2871
2872 // Enhanced keys:
2873 // * 6-pack: insert, delete, home, end, page up, page down
2874 // * cursor keys: up, down, right, left
2875 // * keypad: divide, enter
2876 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2877 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2878 if (_is_enhanced_key(control_key_state)) {
2879 switch (vk) {
2880 case VK_RETURN: // Enter key on keypad
2881 if (_is_ctrl_pressed(control_key_state)) {
2882 seqstr = "\n";
2883 } else {
2884 seqstr = "\r";
2885 }
2886 break;
2887
2888 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2889 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2890
2891 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2892 // will be fixed soon to match xterm which sends CSI "F" and
2893 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2894 MATCH(VK_END, CSI "F");
2895 MATCH(VK_HOME, CSI "H");
2896
2897 MATCH_MODIFIER(VK_LEFT, CSI "D");
2898 MATCH_MODIFIER(VK_UP, CSI "A");
2899 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2900 MATCH_MODIFIER(VK_DOWN, CSI "B");
2901
2902 MATCH_MODIFIER(VK_INSERT, CSI "2~");
2903 MATCH_MODIFIER(VK_DELETE, CSI "3~");
2904
2905 MATCH(VK_DIVIDE, "/");
2906 }
2907 } else { // Non-enhanced keys:
2908 switch (vk) {
2909 case VK_BACK: // backspace
2910 if (_is_alt_pressed(control_key_state)) {
2911 seqstr = ESC "\x7f";
2912 } else {
2913 seqstr = "\x7f";
2914 }
2915 break;
2916
2917 case VK_TAB:
2918 if (_is_shift_pressed(control_key_state)) {
2919 seqstr = CSI "Z";
2920 } else {
2921 seqstr = "\t";
2922 }
2923 break;
2924
2925 // Number 5 key in keypad when NumLock is off, or if NumLock is
2926 // on and Shift is down.
2927 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2928
2929 case VK_RETURN: // Enter key on main keyboard
2930 if (_is_alt_pressed(control_key_state)) {
2931 seqstr = ESC "\n";
2932 } else if (_is_ctrl_pressed(control_key_state)) {
2933 seqstr = "\n";
2934 } else {
2935 seqstr = "\r";
2936 }
2937 break;
2938
2939 // VK_ESCAPE: Don't do any special handling. The OS uses many
2940 // of the sequences with Escape and many of the remaining
2941 // sequences don't produce bKeyDown messages, only !bKeyDown
2942 // for whatever reason.
2943
2944 case VK_SPACE:
2945 if (_is_alt_pressed(control_key_state)) {
2946 seqstr = ESC " ";
2947 } else if (_is_ctrl_pressed(control_key_state)) {
2948 seqbuf[0] = '\0'; // NULL char
2949 seqbuflen = 1;
2950 } else {
2951 seqstr = " ";
2952 }
2953 break;
2954
2955 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2956 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
2957
2958 MATCH_KEYPAD(VK_END, CSI "4~", "1");
2959 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2960
2961 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
2962 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
2963 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2964 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
2965
2966 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2967 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2968 _get_decimal_char());
2969
2970 case 0x30: // 0
2971 case 0x31: // 1
2972 case 0x39: // 9
2973 case VK_OEM_1: // ;:
2974 case VK_OEM_PLUS: // =+
2975 case VK_OEM_COMMA: // ,<
2976 case VK_OEM_PERIOD: // .>
2977 case VK_OEM_7: // '"
2978 case VK_OEM_102: // depends on keyboard, could be <> or \|
2979 case VK_OEM_2: // /?
2980 case VK_OEM_3: // `~
2981 case VK_OEM_4: // [{
2982 case VK_OEM_5: // \|
2983 case VK_OEM_6: // ]}
2984 {
2985 seqbuflen = _get_control_character(seqbuf, key_event,
2986 control_key_state);
2987
2988 if (_is_alt_pressed(control_key_state)) {
2989 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2990 }
2991 }
2992 break;
2993
2994 case 0x32: // 2
2995 case 0x36: // 6
2996 case VK_OEM_MINUS: // -_
2997 {
2998 seqbuflen = _get_control_character(seqbuf, key_event,
2999 control_key_state);
3000
3001 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3002 // prefix with escape.
3003 if (_is_alt_pressed(control_key_state) &&
3004 !(_is_ctrl_pressed(control_key_state) &&
3005 !_is_shift_pressed(control_key_state))) {
3006 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3007 }
3008 }
3009 break;
3010
3011 case 0x33: // 3
3012 case 0x34: // 4
3013 case 0x35: // 5
3014 case 0x37: // 7
3015 case 0x38: // 8
3016 {
3017 seqbuflen = _get_control_character(seqbuf, key_event,
3018 control_key_state);
3019
3020 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
3021 // prefix with escape.
3022 if (_is_alt_pressed(control_key_state) &&
3023 !(_is_ctrl_pressed(control_key_state) &&
3024 !_is_shift_pressed(control_key_state))) {
3025 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3026 }
3027 }
3028 break;
3029
3030 case 0x41: // a
3031 case 0x42: // b
3032 case 0x43: // c
3033 case 0x44: // d
3034 case 0x45: // e
3035 case 0x46: // f
3036 case 0x47: // g
3037 case 0x48: // h
3038 case 0x49: // i
3039 case 0x4a: // j
3040 case 0x4b: // k
3041 case 0x4c: // l
3042 case 0x4d: // m
3043 case 0x4e: // n
3044 case 0x4f: // o
3045 case 0x50: // p
3046 case 0x51: // q
3047 case 0x52: // r
3048 case 0x53: // s
3049 case 0x54: // t
3050 case 0x55: // u
3051 case 0x56: // v
3052 case 0x57: // w
3053 case 0x58: // x
3054 case 0x59: // y
3055 case 0x5a: // z
3056 {
3057 seqbuflen = _get_non_alt_char(seqbuf, key_event,
3058 control_key_state);
3059
3060 // If Alt is pressed, then prefix with escape.
3061 if (_is_alt_pressed(control_key_state)) {
3062 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
3063 }
3064 }
3065 break;
3066
3067 // These virtual key codes are generated by the keys on the
3068 // keypad *when NumLock is on* and *Shift is up*.
3069 MATCH(VK_NUMPAD0, "0");
3070 MATCH(VK_NUMPAD1, "1");
3071 MATCH(VK_NUMPAD2, "2");
3072 MATCH(VK_NUMPAD3, "3");
3073 MATCH(VK_NUMPAD4, "4");
3074 MATCH(VK_NUMPAD5, "5");
3075 MATCH(VK_NUMPAD6, "6");
3076 MATCH(VK_NUMPAD7, "7");
3077 MATCH(VK_NUMPAD8, "8");
3078 MATCH(VK_NUMPAD9, "9");
3079
3080 MATCH(VK_MULTIPLY, "*");
3081 MATCH(VK_ADD, "+");
3082 MATCH(VK_SUBTRACT, "-");
3083 // VK_DECIMAL is generated by the . key on the keypad *when
3084 // NumLock is on* and *Shift is up* and the sequence is not
3085 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
3086 // Windows Security screen to come up).
3087 case VK_DECIMAL:
3088 // U.S. English uses '.', Germany German uses ','.
3089 seqbuflen = _get_non_control_char(seqbuf, key_event,
3090 control_key_state);
3091 break;
3092
3093 MATCH_MODIFIER(VK_F1, SS3 "P");
3094 MATCH_MODIFIER(VK_F2, SS3 "Q");
3095 MATCH_MODIFIER(VK_F3, SS3 "R");
3096 MATCH_MODIFIER(VK_F4, SS3 "S");
3097 MATCH_MODIFIER(VK_F5, CSI "15~");
3098 MATCH_MODIFIER(VK_F6, CSI "17~");
3099 MATCH_MODIFIER(VK_F7, CSI "18~");
3100 MATCH_MODIFIER(VK_F8, CSI "19~");
3101 MATCH_MODIFIER(VK_F9, CSI "20~");
3102 MATCH_MODIFIER(VK_F10, CSI "21~");
3103 MATCH_MODIFIER(VK_F11, CSI "23~");
3104 MATCH_MODIFIER(VK_F12, CSI "24~");
3105
3106 MATCH_MODIFIER(VK_F13, CSI "25~");
3107 MATCH_MODIFIER(VK_F14, CSI "26~");
3108 MATCH_MODIFIER(VK_F15, CSI "28~");
3109 MATCH_MODIFIER(VK_F16, CSI "29~");
3110 MATCH_MODIFIER(VK_F17, CSI "31~");
3111 MATCH_MODIFIER(VK_F18, CSI "32~");
3112 MATCH_MODIFIER(VK_F19, CSI "33~");
3113 MATCH_MODIFIER(VK_F20, CSI "34~");
3114
3115 // MATCH_MODIFIER(VK_F21, ???);
3116 // MATCH_MODIFIER(VK_F22, ???);
3117 // MATCH_MODIFIER(VK_F23, ???);
3118 // MATCH_MODIFIER(VK_F24, ???);
3119 }
3120 }
3121
3122#undef MATCH
3123#undef MATCH_MODIFIER
3124#undef MATCH_KEYPAD
3125#undef MATCH_MODIFIER_KEYPAD
3126#undef ESC
3127#undef CSI
3128#undef SS3
3129
3130 const char* out;
3131 size_t outlen;
3132
3133 // Check for output in any of:
3134 // * seqstr is set (and strlen can be used to determine the length).
3135 // * seqbuf and seqbuflen are set
3136 // Fallback to ch from Windows.
3137 if (seqstr != NULL) {
3138 out = seqstr;
3139 outlen = strlen(seqstr);
3140 } else if (seqbuflen > 0) {
3141 out = seqbuf;
3142 outlen = seqbuflen;
3143 } else if (ch != '\0') {
3144 // Use whatever Windows told us it is.
3145 seqbuf[0] = ch;
3146 seqbuflen = 1;
3147 out = seqbuf;
3148 outlen = seqbuflen;
3149 } else {
3150 // No special handling for the virtual key code and Windows isn't
3151 // telling us a character code, then we don't know how to translate
3152 // the key press.
3153 //
3154 // Consume the input and 'continue' to cause us to get a new key
3155 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07003156 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08003157 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3158 key_event->wRepeatCount = 0;
3159 continue;
3160 }
3161
3162 int bytesRead = 0;
3163
3164 // put output wRepeatCount times into buf/len
3165 while (key_event->wRepeatCount > 0) {
3166 if (len >= outlen) {
3167 // Write to buf/len
3168 memcpy(buf, out, outlen);
3169 buf = (void*)((char*)buf + outlen);
3170 len -= outlen;
3171 bytesRead += outlen;
3172
3173 // consume the input
3174 --key_event->wRepeatCount;
3175 } else {
3176 // Not enough space, so just leave it in _win32_input_record
3177 // for a subsequent retrieval.
3178 if (bytesRead == 0) {
3179 // We didn't write anything because there wasn't enough
3180 // space to even write one sequence. This should never
3181 // happen if the caller uses sensible buffer sizes
3182 // (i.e. >= maximum sequence length which is probably a
3183 // few bytes long).
3184 D("_console_read: no buffer space to write one sequence; "
3185 "buffer: %ld, sequence: %ld\n", (long)len,
3186 (long)outlen);
3187 errno = ENOMEM;
3188 return -1;
3189 } else {
3190 // Stop trying to write to buf/len, just return whatever
3191 // we wrote so far.
3192 break;
3193 }
3194 }
3195 }
3196
3197 return bytesRead;
3198 }
3199}
3200
3201static DWORD _old_console_mode; // previous GetConsoleMode() result
3202static HANDLE _console_handle; // when set, console mode should be restored
3203
3204void stdin_raw_init(const int fd) {
3205 if (STDIN_FILENO == fd) {
3206 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3207 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3208 return;
3209 }
3210
3211 if (GetFileType(in) != FILE_TYPE_CHAR) {
3212 // stdin might be a file or pipe.
3213 return;
3214 }
3215
3216 if (!GetConsoleMode(in, &_old_console_mode)) {
3217 // If GetConsoleMode() fails, stdin is probably is not a console.
3218 return;
3219 }
3220
3221 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3222 // calling the process Ctrl-C routine (configured by
3223 // SetConsoleCtrlHandler()).
3224 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3225 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3226 // flag also seems necessary to have proper line-ending processing.
3227 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3228 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3229 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003230 D("stdin_raw_init: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003231 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003232 }
3233
3234 // Once this is set, it means that stdin has been configured for
3235 // reading from and that the old console mode should be restored later.
3236 _console_handle = in;
3237
3238 // Note that we don't need to configure C Runtime line-ending
3239 // translation because _console_read() does not call the C Runtime to
3240 // read from the console.
3241 }
3242}
3243
3244void stdin_raw_restore(const int fd) {
3245 if (STDIN_FILENO == fd) {
3246 if (_console_handle != NULL) {
3247 const HANDLE in = _console_handle;
3248 _console_handle = NULL; // clear state
3249
3250 if (!SetConsoleMode(in, _old_console_mode)) {
3251 // This really should not fail.
Yabin Cui815ad882015-09-02 17:44:28 -07003252 D("stdin_raw_restore: SetConsoleMode() failed: %s",
Spencer Low1711e012015-08-02 18:50:17 -07003253 SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08003254 }
3255 }
3256 }
3257}
3258
Spencer Low3a2421b2015-05-22 20:09:06 -07003259// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Lowbeb61982015-03-01 15:06:21 -08003260int unix_read(int fd, void* buf, size_t len) {
3261 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3262 // If it is a request to read from stdin, and stdin_raw_init() has been
3263 // called, and it successfully configured the console, then read from
3264 // the console using Win32 console APIs and partially emulate a unix
3265 // terminal.
3266 return _console_read(_console_handle, buf, len);
3267 } else {
3268 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07003269 // can do LF/CR translation (which is overridable with _setmode()).
3270 // Undefine the macro that is set in sysdeps.h which bans calls to
3271 // plain read() in favor of unix_read() or adb_read().
3272#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003273#undef read
3274 return read(fd, buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07003275#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08003276 }
3277}
Spencer Low6815c072015-05-11 01:08:48 -07003278
3279/**************************************************************************/
3280/**************************************************************************/
3281/***** *****/
3282/***** Unicode support *****/
3283/***** *****/
3284/**************************************************************************/
3285/**************************************************************************/
3286
3287// This implements support for using files with Unicode filenames and for
3288// outputting Unicode text to a Win32 console window. This is inspired from
3289// http://utf8everywhere.org/.
3290//
3291// Background
3292// ----------
3293//
3294// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
3295// filenames to APIs such as open(). This works because filenames are largely
3296// opaque 'cookies' (perhaps excluding path separators).
3297//
3298// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
3299// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
3300// strings, but the strings are in the ANSI codepage and not UTF-8. (The
3301// CreateFile() API is really just a macro that adds the W/A based on whether
3302// the UNICODE preprocessor symbol is defined).
3303//
3304// Options
3305// -------
3306//
3307// Thus, to write a portable program, there are a few options:
3308//
3309// 1. Write the program with wchar_t filenames (wchar_t path[256];).
3310// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
3311// that takes a wchar_t string, converts it to UTF-8 and then calls the real
3312// open() API.
3313//
3314// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
3315// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
3316// potentially touching a lot of code.
3317//
3318// 3. Write the program with a 1-byte char filenames (char path[256];) that are
3319// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
3320// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
3321// or C Runtime API.
3322//
3323// The Choice
3324// ----------
3325//
3326// The code below chooses option 3, the UTF-8 everywhere strategy. It
3327// introduces narrow() which converts UTF-16 to UTF-8. This is used by the
3328// NarrowArgs helper class that is used to convert wmain() args into UTF-8
3329// args that are passed to main() at the beginning of program startup. We also
3330// introduce widen() which converts from UTF-8 to UTF-16. This is used to
3331// implement wrappers below that call UTF-16 OS and C Runtime APIs.
3332//
3333// Unicode console output
3334// ----------------------
3335//
3336// The way to output Unicode to a Win32 console window is to call
3337// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07003338// such as Lucida Console or Consolas, and in the case of East Asian languages
3339// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
3340// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
3341// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07003342//
3343// The problem is getting the C Runtime to make fprintf and related APIs call
3344// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
3345// promising, but the various modes have issues:
3346//
3347// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
3348// UTF-16 do not display properly.
3349// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
3350// totally wrong.
3351// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
3352// handler to be called (upon a later I/O call), aborting the process.
3353// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
3354// to output nothing.
3355//
3356// So the only solution is to write our own adb_fprintf() that converts UTF-8
3357// to UTF-16 and then calls WriteConsoleW().
3358
3359
3360// Function prototype because attributes cannot be placed on func definitions.
3361static void _widen_fatal(const char *fmt, ...)
3362 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
3363
3364// A version of fatal() that does not call adb_(v)fprintf(), so it can be
3365// called from those functions.
3366static void _widen_fatal(const char *fmt, ...) {
3367 va_list ap;
3368 va_start(ap, fmt);
3369 // If (v)fprintf are macros that point to adb_(v)fprintf, when random adb
3370 // code calls (v)fprintf, it may end up calling adb_(v)fprintf, which then
3371 // calls _widen_fatal(). So then how does _widen_fatal() output a error?
3372 // By directly calling real C Runtime APIs that don't properly output
3373 // Unicode, but will be able to get a comprehendible message out. To do
3374 // this, make sure we don't call (v)fprintf macros by undefining them.
3375#pragma push_macro("fprintf")
3376#pragma push_macro("vfprintf")
3377#undef fprintf
3378#undef vfprintf
3379 fprintf(stderr, "error: ");
3380 vfprintf(stderr, fmt, ap);
3381 fprintf(stderr, "\n");
3382#pragma pop_macro("vfprintf")
3383#pragma pop_macro("fprintf")
3384 va_end(ap);
3385 exit(-1);
3386}
3387
3388// TODO: Consider implementing widen() and narrow() out of std::wstring_convert
3389// once libcxx is supported on Windows. Or, consider libutils/Unicode.cpp.
3390
3391// Convert from UTF-8 to UTF-16. A size of -1 specifies a NULL terminated
3392// string. Any other size specifies the number of chars to convert, excluding
3393// any NULL terminator (if you're passing an explicit size, you probably don't
3394// have a NULL terminated string in the first place).
3395std::wstring widen(const char* utf8, const int size) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003396 // Note: Do not call SystemErrorCodeToString() from widen() because
3397 // SystemErrorCodeToString() calls narrow() which may call fatal() which
3398 // calls adb_vfprintf() which calls widen(), potentially causing infinite
3399 // recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003400 const int chars_to_convert = MultiByteToWideChar(CP_UTF8, 0, utf8, size,
3401 NULL, 0);
3402 if (chars_to_convert <= 0) {
3403 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3404 _widen_fatal("MultiByteToWideChar failed counting: %d, "
3405 "GetLastError: %lu", chars_to_convert, GetLastError());
3406 }
3407
3408 std::wstring utf16;
3409 size_t chars_to_allocate = chars_to_convert;
3410 if (size == -1) {
3411 // chars_to_convert includes a NULL terminator, so subtract space
3412 // for that because resize() includes that itself.
3413 --chars_to_allocate;
3414 }
3415 utf16.resize(chars_to_allocate);
3416
3417 // This uses &string[0] to get write-access to the entire string buffer
3418 // which may be assuming that the chars are all contiguous, but it seems
3419 // to work and saves us the hassle of using a temporary
3420 // std::vector<wchar_t>.
3421 const int result = MultiByteToWideChar(CP_UTF8, 0, utf8, size, &utf16[0],
3422 chars_to_convert);
3423 if (result != chars_to_convert) {
3424 // UTF-8 to UTF-16 should be lossless, so we don't expect this to fail.
3425 _widen_fatal("MultiByteToWideChar failed conversion: %d, "
3426 "GetLastError: %lu", result, GetLastError());
3427 }
3428
3429 // If a size was passed in (size != -1), then the string is NULL terminated
3430 // by a NULL char that was written by std::string::resize(). If size == -1,
3431 // then MultiByteToWideChar() read a NULL terminator from the original
3432 // string and converted it to a NULL UTF-16 char in the output.
3433
3434 return utf16;
3435}
3436
3437// Convert a NULL terminated string from UTF-8 to UTF-16.
3438std::wstring widen(const char* utf8) {
3439 // Pass -1 to let widen() determine the string length.
3440 return widen(utf8, -1);
3441}
3442
3443// Convert from UTF-8 to UTF-16.
3444std::wstring widen(const std::string& utf8) {
3445 return widen(utf8.c_str(), utf8.length());
3446}
3447
3448// Convert from UTF-16 to UTF-8.
3449std::string narrow(const std::wstring& utf16) {
3450 return narrow(utf16.c_str());
3451}
3452
3453// Convert from UTF-16 to UTF-8.
3454std::string narrow(const wchar_t* utf16) {
Spencer Lowcc467f12015-08-02 18:13:54 -07003455 // Note: Do not call SystemErrorCodeToString() from narrow() because
Elliott Hughes1ba53092015-08-03 16:26:13 -07003456 // SystemErrorCodeToString() calls narrow() and we don't want potential
Spencer Lowcc467f12015-08-02 18:13:54 -07003457 // infinite recursion.
Spencer Low6815c072015-05-11 01:08:48 -07003458 const int chars_required = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, NULL,
3459 0, NULL, NULL);
3460 if (chars_required <= 0) {
3461 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003462 fatal("WideCharToMultiByte failed counting: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003463 chars_required, GetLastError());
3464 }
3465
3466 std::string utf8;
3467 // Subtract space for the NULL terminator because resize() includes
3468 // that itself. Note that this could potentially throw a std::bad_alloc
3469 // exception.
3470 utf8.resize(chars_required - 1);
3471
3472 // This uses &string[0] to get write-access to the entire string buffer
3473 // which may be assuming that the chars are all contiguous, but it seems
3474 // to work and saves us the hassle of using a temporary
3475 // std::vector<char>.
3476 const int result = WideCharToMultiByte(CP_UTF8, 0, utf16, -1, &utf8[0],
3477 chars_required, NULL, NULL);
3478 if (result != chars_required) {
3479 // UTF-16 to UTF-8 should be lossless, so we don't expect this to fail.
Spencer Lowcc467f12015-08-02 18:13:54 -07003480 fatal("WideCharToMultiByte failed conversion: %d, GetLastError: %lu",
Spencer Low6815c072015-05-11 01:08:48 -07003481 result, GetLastError());
3482 }
3483
3484 return utf8;
3485}
3486
3487// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
3488// be passed to main().
3489NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
3490 narrow_args = new char*[argc + 1];
3491
3492 for (int i = 0; i < argc; ++i) {
3493 narrow_args[i] = strdup(narrow(argv[i]).c_str());
3494 }
3495 narrow_args[argc] = nullptr; // terminate
3496}
3497
3498NarrowArgs::~NarrowArgs() {
3499 if (narrow_args != nullptr) {
3500 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
3501 free(*argp);
3502 }
3503 delete[] narrow_args;
3504 narrow_args = nullptr;
3505 }
3506}
3507
3508int unix_open(const char* path, int options, ...) {
3509 if ((options & O_CREAT) == 0) {
3510 return _wopen(widen(path).c_str(), options);
3511 } else {
3512 int mode;
3513 va_list args;
3514 va_start(args, options);
3515 mode = va_arg(args, int);
3516 va_end(args);
3517 return _wopen(widen(path).c_str(), options, mode);
3518 }
3519}
3520
3521// Version of stat() that takes a UTF-8 path.
3522int adb_stat(const char* f, struct adb_stat* s) {
3523#pragma push_macro("wstat")
3524// This definition of wstat seems to be missing from <sys/stat.h>.
3525#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)
3526#ifdef _USE_32BIT_TIME_T
3527#define wstat _wstat32i64
3528#else
3529#define wstat _wstat64
3530#endif
3531#else
3532// <sys/stat.h> has a function prototype for wstat() that should be available.
3533#endif
3534
3535 return wstat(widen(f).c_str(), s);
3536
3537#pragma pop_macro("wstat")
3538}
3539
3540// Version of opendir() that takes a UTF-8 path.
3541DIR* adb_opendir(const char* name) {
3542 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
3543 // the fields, but right now all the callers treat the structure as
3544 // opaque.
3545 return reinterpret_cast<DIR*>(_wopendir(widen(name).c_str()));
3546}
3547
3548// Version of readdir() that returns UTF-8 paths.
3549struct dirent* adb_readdir(DIR* dir) {
3550 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
3551 struct _wdirent* const went = _wreaddir(wdir);
3552 if (went == nullptr) {
3553 return nullptr;
3554 }
3555 // Convert from UTF-16 to UTF-8.
3556 const std::string name_utf8(narrow(went->d_name));
3557
3558 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
3559 // space for UTF-16 wchar_t's) with UTF-8 char's.
3560 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
3561
3562 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
3563 // Name too big to fit in existing buffer.
3564 errno = ENOMEM;
3565 return nullptr;
3566 }
3567
3568 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
3569 // because _wdirent contains wchar_t instead of char. So even if name_utf8
3570 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
3571 // bigger than the caller expects because they expect a dirent structure
3572 // which has a smaller d_name field. Ignore this since the caller should be
3573 // resilient.
3574
3575 // Rewrite the UTF-16 d_name field to UTF-8.
3576 strcpy(ent->d_name, name_utf8.c_str());
3577
3578 return ent;
3579}
3580
3581// Version of closedir() to go with our version of adb_opendir().
3582int adb_closedir(DIR* dir) {
3583 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
3584}
3585
3586// Version of unlink() that takes a UTF-8 path.
3587int adb_unlink(const char* path) {
3588 const std::wstring wpath(widen(path));
3589
3590 int rc = _wunlink(wpath.c_str());
3591
3592 if (rc == -1 && errno == EACCES) {
3593 /* unlink returns EACCES when the file is read-only, so we first */
3594 /* try to make it writable, then unlink again... */
3595 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
3596 if (rc == 0)
3597 rc = _wunlink(wpath.c_str());
3598 }
3599 return rc;
3600}
3601
3602// Version of mkdir() that takes a UTF-8 path.
3603int adb_mkdir(const std::string& path, int mode) {
3604 return _wmkdir(widen(path.c_str()).c_str());
3605}
3606
3607// Version of utime() that takes a UTF-8 path.
3608int adb_utime(const char* path, struct utimbuf* u) {
3609 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
3610 "utimbuf and _utimbuf should be the same size because they both "
3611 "contain the same types, namely time_t");
3612 return _wutime(widen(path).c_str(), reinterpret_cast<struct _utimbuf*>(u));
3613}
3614
3615// Version of chmod() that takes a UTF-8 path.
3616int adb_chmod(const char* path, int mode) {
3617 return _wchmod(widen(path).c_str(), mode);
3618}
3619
3620// Internal function to get a Win32 console HANDLE from a C Runtime FILE*.
3621static HANDLE _get_console_handle(FILE* const stream) {
3622 // Get a C Runtime file descriptor number from the FILE* structure.
3623 const int fd = fileno(stream);
3624 if (fd < 0) {
3625 return NULL;
3626 }
3627
3628 // If it is not a "character device", it is probably a file and not a
3629 // console. Do this check early because it is probably cheap. Still do more
3630 // checks after this since there are devices that pass this test, but are
3631 // not a console, such as NUL, the Windows /dev/null equivalent (I think).
3632 if (!isatty(fd)) {
3633 return NULL;
3634 }
3635
3636 // Given a C Runtime file descriptor number, get the underlying OS
3637 // file handle.
3638 const intptr_t osfh = _get_osfhandle(fd);
3639 if (osfh == -1) {
3640 return NULL;
3641 }
3642
3643 const HANDLE h = reinterpret_cast<const HANDLE>(osfh);
3644
3645 DWORD old_mode = 0;
3646 if (!GetConsoleMode(h, &old_mode)) {
3647 return NULL;
3648 }
3649
3650 // If GetConsoleMode() was successful, assume this is a console.
3651 return h;
3652}
3653
3654// Internal helper function to write UTF-8 bytes to a console. Returns -1
3655// on error.
3656static int _console_write_utf8(const char* buf, size_t size, FILE* stream,
3657 HANDLE console) {
3658 // Convert from UTF-8 to UTF-16.
3659 // This could throw std::bad_alloc.
3660 const std::wstring output(widen(buf, size));
3661
3662 // Note that this does not do \n => \r\n translation because that
3663 // doesn't seem necessary for the Windows console. For the Windows
3664 // console \r moves to the beginning of the line and \n moves to a new
3665 // line.
3666
3667 // Flush any stream buffering so that our output is afterwards which
3668 // makes sense because our call is afterwards.
3669 (void)fflush(stream);
3670
3671 // Write UTF-16 to the console.
3672 DWORD written = 0;
3673 if (!WriteConsoleW(console, output.c_str(), output.length(), &written,
3674 NULL)) {
3675 errno = EIO;
3676 return -1;
3677 }
3678
3679 // This is the number of UTF-16 chars written, which might be different
3680 // than the number of UTF-8 chars passed in. It doesn't seem practical to
3681 // get this count correct.
3682 return written;
3683}
3684
3685// Function prototype because attributes cannot be placed on func definitions.
3686static int _console_vfprintf(const HANDLE console, FILE* stream,
3687 const char *format, va_list ap)
3688 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
3689
3690// Internal function to format a UTF-8 string and write it to a Win32 console.
3691// Returns -1 on error.
3692static int _console_vfprintf(const HANDLE console, FILE* stream,
3693 const char *format, va_list ap) {
3694 std::string output_utf8;
3695
3696 // Format the string.
3697 // This could throw std::bad_alloc.
3698 android::base::StringAppendV(&output_utf8, format, ap);
3699
3700 return _console_write_utf8(output_utf8.c_str(), output_utf8.length(),
3701 stream, console);
3702}
3703
3704// Version of vfprintf() that takes UTF-8 and can write Unicode to a
3705// Windows console.
3706int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
3707 const HANDLE console = _get_console_handle(stream);
3708
3709 // If there is an associated Win32 console, write to it specially,
3710 // otherwise defer to the regular C Runtime, passing it UTF-8.
3711 if (console != NULL) {
3712 return _console_vfprintf(console, stream, format, ap);
3713 } else {
3714 // If vfprintf is a macro, undefine it, so we can call the real
3715 // C Runtime API.
3716#pragma push_macro("vfprintf")
3717#undef vfprintf
3718 return vfprintf(stream, format, ap);
3719#pragma pop_macro("vfprintf")
3720 }
3721}
3722
3723// Version of fprintf() that takes UTF-8 and can write Unicode to a
3724// Windows console.
3725int adb_fprintf(FILE *stream, const char *format, ...) {
3726 va_list ap;
3727 va_start(ap, format);
3728 const int result = adb_vfprintf(stream, format, ap);
3729 va_end(ap);
3730
3731 return result;
3732}
3733
3734// Version of printf() that takes UTF-8 and can write Unicode to a
3735// Windows console.
3736int adb_printf(const char *format, ...) {
3737 va_list ap;
3738 va_start(ap, format);
3739 const int result = adb_vfprintf(stdout, format, ap);
3740 va_end(ap);
3741
3742 return result;
3743}
3744
3745// Version of fputs() that takes UTF-8 and can write Unicode to a
3746// Windows console.
3747int adb_fputs(const char* buf, FILE* stream) {
3748 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
3749 // which fputs (and hence adb_fputs) should return on error.
3750 return adb_fprintf(stream, "%s", buf);
3751}
3752
3753// Version of fputc() that takes UTF-8 and can write Unicode to a
3754// Windows console.
3755int adb_fputc(int ch, FILE* stream) {
3756 const int result = adb_fprintf(stream, "%c", ch);
3757 if (result <= 0) {
3758 // If there was an error, or if nothing was printed (which should be an
3759 // error), return an error, which fprintf signifies with EOF.
3760 return EOF;
3761 }
3762 // For success, fputc returns the char, cast to unsigned char, then to int.
3763 return static_cast<unsigned char>(ch);
3764}
3765
3766// Internal function to write UTF-8 to a Win32 console. Returns the number of
3767// items (of length size) written. On error, returns a short item count or 0.
3768static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
3769 FILE* stream, HANDLE console) {
3770 // TODO: Note that a Unicode character could be several UTF-8 bytes. But
3771 // if we're passed only some of the bytes of a character (for example, from
3772 // the network socket for adb shell), we won't be able to convert the char
3773 // to a complete UTF-16 char (or surrogate pair), so the output won't look
3774 // right.
3775 //
3776 // To fix this, see libutils/Unicode.cpp for hints on decoding UTF-8.
3777 //
3778 // For now we ignore this problem because the alternative is that we'd have
3779 // to parse UTF-8 and buffer things up (doable). At least this is better
3780 // than what we had before -- always incorrect multi-byte UTF-8 output.
3781 int result = _console_write_utf8(reinterpret_cast<const char*>(ptr),
3782 size * nmemb, stream, console);
3783 if (result == -1) {
3784 return 0;
3785 }
3786 return result / size;
3787}
3788
3789// Version of fwrite() that takes UTF-8 and can write Unicode to a
3790// Windows console.
3791size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
3792 const HANDLE console = _get_console_handle(stream);
3793
3794 // If there is an associated Win32 console, write to it specially,
3795 // otherwise defer to the regular C Runtime, passing it UTF-8.
3796 if (console != NULL) {
3797 return _console_fwrite(ptr, size, nmemb, stream, console);
3798 } else {
3799 // If fwrite is a macro, undefine it, so we can call the real
3800 // C Runtime API.
3801#pragma push_macro("fwrite")
3802#undef fwrite
3803 return fwrite(ptr, size, nmemb, stream);
3804#pragma pop_macro("fwrite")
3805 }
3806}
3807
3808// Version of fopen() that takes a UTF-8 filename and can access a file with
3809// a Unicode filename.
3810FILE* adb_fopen(const char* f, const char* m) {
3811 return _wfopen(widen(f).c_str(), widen(m).c_str());
3812}
3813
Spencer Low50740f52015-09-08 17:13:04 -07003814// Return a lowercase version of the argument. Uses C Runtime tolower() on
3815// each byte which is not UTF-8 aware, and theoretically uses the current C
3816// Runtime locale (which in practice is not changed, so this becomes a ASCII
3817// conversion).
3818static std::string ToLower(const std::string& anycase) {
3819 // copy string
3820 std::string str(anycase);
3821 // transform the copy
3822 std::transform(str.begin(), str.end(), str.begin(), tolower);
3823 return str;
3824}
3825
3826extern "C" int main(int argc, char** argv);
3827
3828// Link with -municode to cause this wmain() to be used as the program
3829// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
3830// regular main() with UTF-8 args.
3831extern "C" int wmain(int argc, wchar_t **argv) {
3832 // Convert args from UTF-16 to UTF-8 and pass that to main().
3833 NarrowArgs narrow_args(argc, argv);
3834 return main(argc, narrow_args.data());
3835}
3836
Spencer Low6815c072015-05-11 01:08:48 -07003837// Shadow UTF-8 environment variable name/value pairs that are created from
3838// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowcc467f12015-08-02 18:13:54 -07003839// currently updated if putenv, setenv, unsetenv are called. Note that no
3840// thread synchronization is done, but we're called early enough in
3841// single-threaded startup that things work ok.
Spencer Low6815c072015-05-11 01:08:48 -07003842static std::unordered_map<std::string, char*> g_environ_utf8;
3843
3844// Make sure that shadow UTF-8 environment variables are setup.
3845static void _ensure_env_setup() {
3846 // If some name/value pairs exist, then we've already done the setup below.
3847 if (g_environ_utf8.size() != 0) {
3848 return;
3849 }
3850
Spencer Low50740f52015-09-08 17:13:04 -07003851 if (_wenviron == nullptr) {
3852 // If _wenviron is null, then -municode probably wasn't used. That
3853 // linker flag will cause the entry point to setup _wenviron. It will
3854 // also require an implementation of wmain() (which we provide above).
3855 fatal("_wenviron is not set, did you link with -municode?");
3856 }
3857
Spencer Low6815c072015-05-11 01:08:48 -07003858 // Read name/value pairs from UTF-16 _wenviron and write new name/value
3859 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
3860 // to use the D() macro here because that tracing only works if the
3861 // ADB_TRACE environment variable is setup, but that env var can't be read
3862 // until this code completes.
3863 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
3864 wchar_t* const equal = wcschr(*env, L'=');
3865 if (equal == nullptr) {
3866 // Malformed environment variable with no equal sign. Shouldn't
3867 // really happen, but we should be resilient to this.
3868 continue;
3869 }
3870
Spencer Low50740f52015-09-08 17:13:04 -07003871 // Store lowercase name so that we can do case-insensitive searches.
3872 const std::string name_utf8(ToLower(narrow(
3873 std::wstring(*env, equal - *env))));
Spencer Low6815c072015-05-11 01:08:48 -07003874 char* const value_utf8 = strdup(narrow(equal + 1).c_str());
3875
Spencer Low50740f52015-09-08 17:13:04 -07003876 // Don't overwrite a previus env var with the same name. In reality,
3877 // the system probably won't let two env vars with the same name exist
3878 // in _wenviron.
3879 g_environ_utf8.insert({name_utf8, value_utf8});
Spencer Low6815c072015-05-11 01:08:48 -07003880 }
3881}
3882
3883// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07003884// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07003885char* adb_getenv(const char* name) {
3886 _ensure_env_setup();
3887
Spencer Low50740f52015-09-08 17:13:04 -07003888 // Case-insensitive search by searching for lowercase name in a map of
3889 // lowercase names.
3890 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07003891 if (it == g_environ_utf8.end()) {
3892 return nullptr;
3893 }
3894
3895 return it->second;
3896}
3897
3898// Version of getcwd() that returns the current working directory in UTF-8.
3899char* adb_getcwd(char* buf, int size) {
3900 wchar_t* wbuf = _wgetcwd(nullptr, 0);
3901 if (wbuf == nullptr) {
3902 return nullptr;
3903 }
3904
3905 const std::string buf_utf8(narrow(wbuf));
3906 free(wbuf);
3907 wbuf = nullptr;
3908
3909 // If size was specified, make sure all the chars will fit.
3910 if (size != 0) {
3911 if (size < static_cast<int>(buf_utf8.length() + 1)) {
3912 errno = ERANGE;
3913 return nullptr;
3914 }
3915 }
3916
3917 // If buf was not specified, allocate storage.
3918 if (buf == nullptr) {
3919 if (size == 0) {
3920 size = buf_utf8.length() + 1;
3921 }
3922 buf = reinterpret_cast<char*>(malloc(size));
3923 if (buf == nullptr) {
3924 return nullptr;
3925 }
3926 }
3927
3928 // Destination buffer was allocated with enough space, or we've already
3929 // checked an existing buffer size for enough space.
3930 strcpy(buf, buf_utf8.c_str());
3931
3932 return buf;
3933}