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