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