blob: 433a59d8d43535b0137c659b9c5da8f6af13dbbb [file] [log] [blame]
Dan Albert33134262015-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 Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070030#include <mutex>
Spencer Low5200c662015-07-30 23:07:55 -070031#include <string>
Spencer Lowcf4ff642015-05-11 01:08:48 -070032#include <unordered_map>
Josh Gao3777d2e2016-02-16 17:34:53 -080033#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070034
Elliott Hughesd48dbd82015-07-24 11:35:40 -070035#include <cutils/sockets.h>
36
David Pursell5f787ed2016-01-27 08:52:53 -080037#include <android-base/errors.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080038#include <android-base/logging.h>
Josh Gao116aa0a2018-04-05 17:55:25 -070039#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080040#include <android-base/stringprintf.h>
41#include <android-base/strings.h>
42#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070043
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080044#include "adb.h"
Josh Gao3777d2e2016-02-16 17:34:53 -080045#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046
Josh Gao116aa0a2018-04-05 17:55:25 -070047#include "sysdeps/uio.h"
48
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080049extern void fatal(const char *fmt, ...);
50
Elliott Hughesa2f2e562015-04-16 16:47:02 -070051/* forward declarations */
52
53typedef const struct FHClassRec_* FHClass;
54typedef struct FHRec_* FH;
55typedef struct EventHookRec_* EventHook;
56
57typedef struct FHClassRec_ {
58 void (*_fh_init)(FH);
59 int (*_fh_close)(FH);
60 int (*_fh_lseek)(FH, int, int);
61 int (*_fh_read)(FH, void*, int);
62 int (*_fh_write)(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070063 int (*_fh_writev)(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070064} FHClassRec;
65
66static void _fh_file_init(FH);
67static int _fh_file_close(FH);
68static int _fh_file_lseek(FH, int, int);
69static int _fh_file_read(FH, void*, int);
70static int _fh_file_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070071static int _fh_file_writev(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070072
73static const FHClassRec _fh_file_class = {
74 _fh_file_init,
75 _fh_file_close,
76 _fh_file_lseek,
77 _fh_file_read,
78 _fh_file_write,
Josh Gao116aa0a2018-04-05 17:55:25 -070079 _fh_file_writev,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070080};
81
82static void _fh_socket_init(FH);
83static int _fh_socket_close(FH);
84static int _fh_socket_lseek(FH, int, int);
85static int _fh_socket_read(FH, void*, int);
86static int _fh_socket_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070087static int _fh_socket_writev(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070088
89static const FHClassRec _fh_socket_class = {
90 _fh_socket_init,
91 _fh_socket_close,
92 _fh_socket_lseek,
93 _fh_socket_read,
94 _fh_socket_write,
Josh Gao116aa0a2018-04-05 17:55:25 -070095 _fh_socket_writev,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070096};
97
Josh Gao56e9bb92016-01-15 15:17:37 -080098#define assert(cond) \
99 do { \
100 if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \
101 } while (0)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800102
Spencer Low2122c7a2015-08-26 18:46:09 -0700103void handle_deleter::operator()(HANDLE h) {
104 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
105 // implying that NULL is a valid handle, but this is probably impossible.
106 // Other APIs like CreateEvent() are documented to return NULL on error,
107 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
108 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
109 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
110 // only need to check for INVALID_HANDLE_VALUE.
111 if (h != INVALID_HANDLE_VALUE) {
112 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700113 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800114 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700115 }
116 }
117}
118
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800119/**************************************************************************/
120/**************************************************************************/
121/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800122/***** common file descriptor handling *****/
123/***** *****/
124/**************************************************************************/
125/**************************************************************************/
126
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800127typedef struct FHRec_
128{
129 FHClass clazz;
130 int used;
131 int eof;
132 union {
133 HANDLE handle;
134 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800135 } u;
136
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800137 char name[32];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800138} FHRec;
139
140#define fh_handle u.handle
141#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800142
Josh Gaob6232b92016-02-17 16:45:39 -0800143#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700144#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800145
Josh Gao0cd3ae12016-09-21 12:37:10 -0700146static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800147static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700148static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149
150static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700151_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800152{
153 FH f;
154
155 fd -= WIN32_FH_BASE;
156
Spencer Lowc3211552015-07-24 15:38:19 -0700157 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700158 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700159 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800160 errno = EBADF;
161 return NULL;
162 }
163
164 f = &_win32_fhs[fd];
165
166 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700167 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700168 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800169 errno = EBADF;
170 return NULL;
171 }
172
173 return f;
174}
175
176
177static int
178_fh_to_int( FH f )
179{
180 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
181 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
182
183 return -1;
184}
185
186static FH
187_fh_alloc( FHClass clazz )
188{
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189 FH f = NULL;
190
Josh Gao0cd3ae12016-09-21 12:37:10 -0700191 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192
Josh Gaob6232b92016-02-17 16:45:39 -0800193 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
194 if (_win32_fhs[i].clazz == NULL) {
195 f = &_win32_fhs[i];
196 _win32_fh_next = i + 1;
Josh Gao0cd3ae12016-09-21 12:37:10 -0700197 f->clazz = clazz;
198 f->used = 1;
199 f->eof = 0;
200 f->name[0] = '\0';
201 clazz->_fh_init(f);
202 return f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800203 }
204 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700205
206 D("_fh_alloc: no more free file descriptors");
207 errno = EMFILE; // Too many open files
208 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800209}
210
211
212static int
213_fh_close( FH f )
214{
Spencer Lowc3211552015-07-24 15:38:19 -0700215 // Use lock so that closing only happens once and so that _fh_alloc can't
216 // allocate a FH that we're in the middle of closing.
Josh Gao0cd3ae12016-09-21 12:37:10 -0700217 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800218
219 int offset = f - _win32_fhs;
220 if (_win32_fh_next > offset) {
221 _win32_fh_next = offset;
222 }
223
Spencer Lowc3211552015-07-24 15:38:19 -0700224 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800225 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700226 f->name[0] = '\0';
227 f->eof = 0;
228 f->used = 0;
229 f->clazz = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800230 }
231 return 0;
232}
233
Spencer Low5200c662015-07-30 23:07:55 -0700234// Deleter for unique_fh.
235class fh_deleter {
236 public:
237 void operator()(struct FHRec_* fh) {
238 // We're called from a destructor and destructors should not overwrite
239 // errno because callers may do:
240 // errno = EBLAH;
241 // return -1; // calls destructor, which should not overwrite errno
242 const int saved_errno = errno;
243 _fh_close(fh);
244 errno = saved_errno;
245 }
246};
247
248// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
249typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
250
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800251/**************************************************************************/
252/**************************************************************************/
253/***** *****/
254/***** file-based descriptor handling *****/
255/***** *****/
256/**************************************************************************/
257/**************************************************************************/
258
Josh Gao116aa0a2018-04-05 17:55:25 -0700259static void _fh_file_init(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800260 f->fh_handle = INVALID_HANDLE_VALUE;
261}
262
Josh Gao116aa0a2018-04-05 17:55:25 -0700263static int _fh_file_close(FH f) {
264 CloseHandle(f->fh_handle);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800265 f->fh_handle = INVALID_HANDLE_VALUE;
266 return 0;
267}
268
Josh Gao116aa0a2018-04-05 17:55:25 -0700269static int _fh_file_read(FH f, void* buf, int len) {
270 DWORD read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800271
Josh Gao116aa0a2018-04-05 17:55:25 -0700272 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, NULL)) {
273 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800274 errno = EIO;
275 return -1;
276 } else if (read_bytes < (DWORD)len) {
277 f->eof = 1;
278 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700279 return read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800280}
281
Josh Gao116aa0a2018-04-05 17:55:25 -0700282static int _fh_file_write(FH f, const void* buf, int len) {
283 DWORD wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800284
Josh Gao116aa0a2018-04-05 17:55:25 -0700285 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL)) {
286 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800287 errno = EIO;
288 return -1;
289 } else if (wrote_bytes < (DWORD)len) {
290 f->eof = 1;
291 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700292 return wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800293}
294
Josh Gao116aa0a2018-04-05 17:55:25 -0700295static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
296 if (iovcnt <= 0) {
297 errno = EINVAL;
298 return -1;
299 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800300
Josh Gao116aa0a2018-04-05 17:55:25 -0700301 DWORD wrote_bytes = 0;
302
303 for (int i = 0; i < iovcnt; ++i) {
304 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
305 if (rc == -1) {
306 return wrote_bytes > 0 ? wrote_bytes : -1;
307 } else if (rc == 0) {
308 return wrote_bytes;
309 }
310
311 wrote_bytes += rc;
312
313 if (static_cast<size_t>(rc) < iov[i].iov_len) {
314 return wrote_bytes;
315 }
316 }
317
318 return wrote_bytes;
319}
320
321static int _fh_file_lseek(FH f, int pos, int origin) {
322 DWORD method;
323 DWORD result;
324
325 switch (origin) {
326 case SEEK_SET:
327 method = FILE_BEGIN;
328 break;
329 case SEEK_CUR:
330 method = FILE_CURRENT;
331 break;
332 case SEEK_END:
333 method = FILE_END;
334 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800335 default:
336 errno = EINVAL;
337 return -1;
338 }
339
Josh Gao116aa0a2018-04-05 17:55:25 -0700340 result = SetFilePointer(f->fh_handle, pos, NULL, method);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800341 if (result == INVALID_SET_FILE_POINTER) {
342 errno = EIO;
343 return -1;
344 } else {
345 f->eof = 0;
346 }
347 return (int)result;
348}
349
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800350/**************************************************************************/
351/**************************************************************************/
352/***** *****/
353/***** file-based descriptor handling *****/
354/***** *****/
355/**************************************************************************/
356/**************************************************************************/
357
358int adb_open(const char* path, int options)
359{
360 FH f;
361
362 DWORD desiredAccess = 0;
363 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
364
365 switch (options) {
366 case O_RDONLY:
367 desiredAccess = GENERIC_READ;
368 break;
369 case O_WRONLY:
370 desiredAccess = GENERIC_WRITE;
371 break;
372 case O_RDWR:
373 desiredAccess = GENERIC_READ | GENERIC_WRITE;
374 break;
375 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700376 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800377 errno = EINVAL;
378 return -1;
379 }
380
381 f = _fh_alloc( &_fh_file_class );
382 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800383 return -1;
384 }
385
Spencer Lowd21dc822015-11-12 15:20:15 -0800386 std::wstring path_wide;
387 if (!android::base::UTF8ToWide(path, &path_wide)) {
388 return -1;
389 }
390 f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700391 NULL, OPEN_EXISTING, 0, NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800392
393 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700394 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800395 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700396 D( "adb_open: could not open '%s': ", path );
397 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800398 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700399 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800400 errno = ENOENT;
401 return -1;
402
403 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700404 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800405 errno = ENOTDIR;
406 return -1;
407
408 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800409 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800410 errno = ENOENT;
411 return -1;
412 }
413 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800414
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800415 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700416 D( "adb_open: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800417 return _fh_to_int(f);
418}
419
420/* ignore mode on Win32 */
421int adb_creat(const char* path, int mode)
422{
423 FH f;
424
425 f = _fh_alloc( &_fh_file_class );
426 if ( !f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800427 return -1;
428 }
429
Spencer Lowd21dc822015-11-12 15:20:15 -0800430 std::wstring path_wide;
431 if (!android::base::UTF8ToWide(path, &path_wide)) {
432 return -1;
433 }
434 f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE,
Spencer Lowcf4ff642015-05-11 01:08:48 -0700435 FILE_SHARE_READ | FILE_SHARE_WRITE,
436 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
437 NULL );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800438
439 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700440 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800441 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700442 D( "adb_creat: could not open '%s': ", path );
443 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800444 case ERROR_FILE_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700445 D( "file not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446 errno = ENOENT;
447 return -1;
448
449 case ERROR_PATH_NOT_FOUND:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700450 D( "path not found" );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800451 errno = ENOTDIR;
452 return -1;
453
454 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800455 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456 errno = ENOENT;
457 return -1;
458 }
459 }
460 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700461 D( "adb_creat: '%s' => fd %d", path, _fh_to_int(f) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800462 return _fh_to_int(f);
463}
464
Josh Gao116aa0a2018-04-05 17:55:25 -0700465int adb_read(int fd, void* buf, int len) {
466 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800467
468 if (f == NULL) {
469 return -1;
470 }
471
Josh Gao116aa0a2018-04-05 17:55:25 -0700472 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473}
474
Josh Gao116aa0a2018-04-05 17:55:25 -0700475int adb_write(int fd, const void* buf, int len) {
476 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800477
478 if (f == NULL) {
479 return -1;
480 }
481
482 return f->clazz->_fh_write(f, buf, len);
483}
484
Josh Gao116aa0a2018-04-05 17:55:25 -0700485ssize_t adb_writev(int fd, const adb_iovec* iov, int iovcnt) {
486 FH f = _fh_from_int(fd, __func__);
487
488 if (f == NULL) {
489 errno = EBADF;
490 return -1;
491 }
492
493 return f->clazz->_fh_writev(f, iov, iovcnt);
494}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800495
496int adb_lseek(int fd, int pos, int where)
497{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700498 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499
500 if (!f) {
501 return -1;
502 }
503
504 return f->clazz->_fh_lseek(f, pos, where);
505}
506
507
508int adb_close(int fd)
509{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700510 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800511
512 if (!f) {
513 return -1;
514 }
515
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700516 D( "adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800517 _fh_close(f);
518 return 0;
519}
520
521/**************************************************************************/
522/**************************************************************************/
523/***** *****/
524/***** socket-based file descriptors *****/
525/***** *****/
526/**************************************************************************/
527/**************************************************************************/
528
Spencer Lowf055c192015-01-25 14:40:16 -0800529#undef setsockopt
530
Spencer Low5200c662015-07-30 23:07:55 -0700531static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700532 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
533 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gaoa3577e12016-12-05 13:24:48 -0800534 // are mapped to strings by adb_strerror().
Spencer Low5200c662015-07-30 23:07:55 -0700535 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800536 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700537 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
538 // case WSAEINTR: errno = EINTR; break;
539 case WSAEFAULT: errno = EFAULT; break;
540 case WSAEINVAL: errno = EINVAL; break;
541 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700542 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
543 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
544 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800545 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700546 case WSAENOTSOCK: errno = ENOTSOCK; break;
547 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
548 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
549 case WSAENETDOWN: errno = ENETDOWN; break;
550 case WSAENETRESET: errno = ENETRESET; break;
551 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
552 // to use EPIPE for these situations and there are some callers that look
553 // for EPIPE.
554 case WSAECONNABORTED: errno = EPIPE; break;
555 case WSAECONNRESET: errno = ECONNRESET; break;
556 case WSAENOBUFS: errno = ENOBUFS; break;
557 case WSAENOTCONN: errno = ENOTCONN; break;
558 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
559 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
560 // considerations: Reportedly send() can return zero on timeout, and POSIX
561 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
562 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
563 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800564 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800565 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700566 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700567 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800568 }
569}
570
Josh Gao3777d2e2016-02-16 17:34:53 -0800571extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
572 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
573 int skipped = 0;
574 std::vector<WSAPOLLFD> sockets;
575 std::vector<adb_pollfd*> original;
Josh Gao05fb45b2018-03-29 12:34:28 -0700576
Josh Gao3777d2e2016-02-16 17:34:53 -0800577 for (size_t i = 0; i < nfds; ++i) {
578 FH fh = _fh_from_int(fds[i].fd, __func__);
579 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
580 D("adb_poll received bad FD %d", fds[i].fd);
581 fds[i].revents = POLLNVAL;
582 ++skipped;
583 } else {
584 WSAPOLLFD wsapollfd = {
585 .fd = fh->u.socket,
586 .events = static_cast<short>(fds[i].events)
587 };
588 sockets.push_back(wsapollfd);
589 original.push_back(&fds[i]);
590 }
Spencer Low5200c662015-07-30 23:07:55 -0700591 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800592
593 if (sockets.empty()) {
594 return skipped;
595 }
596
Josh Gao05fb45b2018-03-29 12:34:28 -0700597 // If we have any invalid FDs in our FD set, make sure to return immediately.
598 if (skipped > 0) {
599 timeout = 0;
600 }
601
Josh Gao3777d2e2016-02-16 17:34:53 -0800602 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
603 if (result == SOCKET_ERROR) {
604 _socket_set_errno(WSAGetLastError());
605 return -1;
606 }
607
608 // Map the results back onto the original set.
609 for (size_t i = 0; i < sockets.size(); ++i) {
610 original[i]->revents = sockets[i].revents;
611 }
612
Josh Gao05fb45b2018-03-29 12:34:28 -0700613 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gao3777d2e2016-02-16 17:34:53 -0800614 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
615 // to do. Ignore its result and calculate the proper return value.
616 result = 0;
617 for (size_t i = 0; i < nfds; ++i) {
618 if (fds[i].revents != 0) {
619 ++result;
620 }
621 }
622 return result;
623}
624
625static void _fh_socket_init(FH f) {
626 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800627}
628
Josh Gao116aa0a2018-04-05 17:55:25 -0700629static int _fh_socket_close(FH f) {
Spencer Low5200c662015-07-30 23:07:55 -0700630 if (f->fh_socket != INVALID_SOCKET) {
631 /* gently tell any peer that we're closing the socket */
632 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
633 // If the socket is not connected, this returns an error. We want to
634 // minimize logging spam, so don't log these errors for now.
635#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700636 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800637 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700638#endif
639 }
640 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800641 // Don't set errno here, since adb_close will ignore it.
642 const DWORD err = WSAGetLastError();
643 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700644 }
645 f->fh_socket = INVALID_SOCKET;
646 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800647 return 0;
648}
649
Josh Gao116aa0a2018-04-05 17:55:25 -0700650static int _fh_socket_lseek(FH f, int pos, int origin) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800651 errno = EPIPE;
652 return -1;
653}
654
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700655static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700656 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800657 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700658 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700659 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
660 // that to reduce spam and confusion.
661 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700662 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800663 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700664 }
Spencer Low5200c662015-07-30 23:07:55 -0700665 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800666 result = -1;
667 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700668 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800669}
670
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700671static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700672 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800673 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700674 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700675 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
676 // that to reduce spam and confusion.
677 if (err != WSAEWOULDBLOCK) {
678 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800679 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700680 }
Spencer Low5200c662015-07-30 23:07:55 -0700681 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800682 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700683 } else {
684 // According to https://code.google.com/p/chromium/issues/detail?id=27870
685 // Winsock Layered Service Providers may cause this.
Josh Gao116aa0a2018-04-05 17:55:25 -0700686 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
687 << result << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800688 }
689 return result;
690}
691
Josh Gao116aa0a2018-04-05 17:55:25 -0700692// Make sure that adb_iovec is compatible with WSABUF.
693static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
694static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
695static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
696
697static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
698static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
699
700static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
701 if (iovcnt <= 0) {
702 errno = EINVAL;
703 return -1;
704 }
705
706 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
707 DWORD bytes_written = 0;
708 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
709 if (result == SOCKET_ERROR) {
710 const DWORD err = WSAGetLastError();
711 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
712 // that to reduce spam and confusion.
713 if (err != WSAEWOULDBLOCK) {
714 D("send fd %d failed: %s", _fh_to_int(f),
715 android::base::SystemErrorCodeToString(err).c_str());
716 }
717 _socket_set_errno(err);
718 result = -1;
719 }
720 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
721 return static_cast<int>(bytes_written);
722}
723
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800724/**************************************************************************/
725/**************************************************************************/
726/***** *****/
727/***** replacement for libs/cutils/socket_xxxx.c *****/
728/***** *****/
729/**************************************************************************/
730/**************************************************************************/
731
732#include <winsock2.h>
733
734static int _winsock_init;
735
736static void
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800737_init_winsock( void )
738{
Spencer Low5200c662015-07-30 23:07:55 -0700739 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Low87e97ee2015-08-12 18:19:16 -0700740 // to WSAStartup() which offers no real benefit.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800741 if (!_winsock_init) {
742 WSADATA wsaData;
743 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
744 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800745 fatal("adb: could not initialize Winsock: %s",
746 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800747 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800748 _winsock_init = 1;
Spencer Low87e97ee2015-08-12 18:19:16 -0700749
750 // Note that we do not call atexit() to register WSACleanup to be called
751 // at normal process termination because:
752 // 1) When exit() is called, there are still threads actively using
753 // Winsock because we don't cleanly shutdown all threads, so it
754 // doesn't make sense to call WSACleanup() and may cause problems
755 // with those threads.
756 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
757 // calls WSACleanup() which tries to unload a DLL, which tries to
758 // grab the LoaderLock. This conflicts with the device_poll_thread
759 // which holds the LoaderLock because AdbWinApi.dll calls
760 // setupapi.dll which tries to load wintrust.dll which tries to load
761 // crypt32.dll which calls atexit() which tries to acquire the C
762 // Runtime lock that the other thread holds.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800763 }
764}
765
Spencer Low677fb432015-09-29 15:05:29 -0700766// Map a socket type to an explicit socket protocol instead of using the socket
767// protocol of 0. Explicit socket protocols are used by most apps and we should
768// do the same to reduce the chance of exercising uncommon code-paths that might
769// have problems or that might load different Winsock service providers that
770// have problems.
771static int GetSocketProtocolFromSocketType(int type) {
772 switch (type) {
773 case SOCK_STREAM:
774 return IPPROTO_TCP;
775 case SOCK_DGRAM:
776 return IPPROTO_UDP;
777 default:
778 LOG(FATAL) << "Unknown socket type: " << type;
779 return 0;
780 }
781}
782
Spencer Low5200c662015-07-30 23:07:55 -0700783int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800784 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800785 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786
Josh Gao6487e742016-02-18 13:43:55 -0800787 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700788 if (!f) {
789 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800790 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700791 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800792
Josh Gao6487e742016-02-18 13:43:55 -0800793 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800794
795 memset(&addr, 0, sizeof(addr));
796 addr.sin_family = AF_INET;
797 addr.sin_port = htons(port);
798 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
799
Spencer Low677fb432015-09-29 15:05:29 -0700800 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800801 if (s == INVALID_SOCKET) {
802 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700803 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800804 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700805 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800806 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700807 return -1;
808 }
809 f->fh_socket = s;
810
Josh Gao6487e742016-02-18 13:43:55 -0800811 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700812 // Save err just in case inet_ntoa() or ntohs() changes the last error.
813 const DWORD err = WSAGetLastError();
814 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800815 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
816 android::base::SystemErrorCodeToString(err).c_str());
817 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
818 error->c_str());
819 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820 return -1;
821 }
822
Spencer Low5200c662015-07-30 23:07:55 -0700823 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800824 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
825 port);
826 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700827 f.release();
828 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800829}
830
Spencer Low5200c662015-07-30 23:07:55 -0700831// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800832static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800833 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800834 SOCKET s;
835 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800836
Josh Gao6487e742016-02-18 13:43:55 -0800837 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800838 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700839 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800840 return -1;
841 }
842
Josh Gao6487e742016-02-18 13:43:55 -0800843 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844
845 memset(&addr, 0, sizeof(addr));
846 addr.sin_family = AF_INET;
847 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700848 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849
Spencer Low5200c662015-07-30 23:07:55 -0700850 // TODO: Consider using dual-stack socket that can simultaneously listen on
851 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700852 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700853 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800854 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700855 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800856 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700857 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800858 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700859 return -1;
860 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800861
862 f->fh_socket = s;
863
Spencer Lowbf7c6052015-08-11 16:45:32 -0700864 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
865 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800867 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
868 const DWORD err = WSAGetLastError();
869 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
870 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700871 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800872 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700873 return -1;
874 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800875
Josh Gao6487e742016-02-18 13:43:55 -0800876 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700877 // Save err just in case inet_ntoa() or ntohs() changes the last error.
878 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800879 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
880 ntohs(addr.sin_port),
881 android::base::SystemErrorCodeToString(err).c_str());
882 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
883 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800884 return -1;
885 }
886 if (type == SOCK_STREAM) {
Josh Gaobf243a62018-03-20 14:25:03 -0700887 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800888 const DWORD err = WSAGetLastError();
889 *error = android::base::StringPrintf(
890 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
891 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
892 error->c_str());
893 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800894 return -1;
895 }
896 }
Spencer Low5200c662015-07-30 23:07:55 -0700897 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800898 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
899 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
900 port);
901 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700902 f.release();
903 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800904}
905
Spencer Low5200c662015-07-30 23:07:55 -0700906int network_loopback_server(int port, int type, std::string* error) {
907 return _network_server(port, type, INADDR_LOOPBACK, error);
908}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800909
Spencer Low5200c662015-07-30 23:07:55 -0700910int network_inaddr_any_server(int port, int type, std::string* error) {
911 return _network_server(port, type, INADDR_ANY, error);
912}
913
914int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
915 unique_fh f(_fh_alloc(&_fh_socket_class));
916 if (!f) {
917 *error = strerror(errno);
918 return -1;
919 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800920
Elliott Hughes381cfa92015-07-23 17:12:58 -0700921 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800922
Spencer Low5200c662015-07-30 23:07:55 -0700923 struct addrinfo hints;
924 memset(&hints, 0, sizeof(hints));
925 hints.ai_family = AF_UNSPEC;
926 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700927 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700928
929 char port_str[16];
930 snprintf(port_str, sizeof(port_str), "%d", port);
931
932 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700933
934#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800935// TODO: When the Android SDK tools increases the Windows system
936// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700937#else
Josh Gao6487e742016-02-18 13:43:55 -0800938// Otherwise, keep using getaddrinfo(), or do runtime API detection
939// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700940#endif
Spencer Low5200c662015-07-30 23:07:55 -0700941 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800942 const DWORD err = WSAGetLastError();
943 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
944 host.c_str(), port_str,
945 android::base::SystemErrorCodeToString(err).c_str());
946
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700947 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800948 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800949 return -1;
950 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700951 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700952 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800953
Spencer Low5200c662015-07-30 23:07:55 -0700954 // TODO: Try all the addresses if there's more than one? This just uses
955 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
956 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800957 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
958 if (s == INVALID_SOCKET) {
959 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700960 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800961 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700962 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800963 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800964 return -1;
965 }
966 f->fh_socket = s;
967
Spencer Low5200c662015-07-30 23:07:55 -0700968 // TODO: Implement timeouts for Windows. Seems like the default in theory
969 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800970 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700971 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800972 const DWORD err = WSAGetLastError();
973 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
974 android::base::SystemErrorCodeToString(err).c_str());
975 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
976 port_str, error->c_str());
977 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800978 return -1;
979 }
980
Spencer Low5200c662015-07-30 23:07:55 -0700981 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800982 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
983 port);
984 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
985 fd);
Spencer Low5200c662015-07-30 23:07:55 -0700986 f.release();
987 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800988}
989
Casey Dahlin2fe9b602016-09-21 14:03:39 -0700990int adb_register_socket(SOCKET s) {
991 FH f = _fh_alloc( &_fh_socket_class );
992 f->fh_socket = s;
993 return _fh_to_int(f);
994}
995
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800996#undef accept
997int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
998{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700999 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001000
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001001 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001002 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -07001003 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001004 return -1;
1005 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001006
Spencer Low5200c662015-07-30 23:07:55 -07001007 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001008 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001009 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1010 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001011 return -1;
1012 }
1013
1014 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
1015 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001016 const DWORD err = WSAGetLastError();
Spencer Low5200c662015-07-30 23:07:55 -07001017 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
David Pursell5f787ed2016-01-27 08:52:53 -08001018 " failed: " + android::base::SystemErrorCodeToString(err);
Spencer Low5200c662015-07-30 23:07:55 -07001019 _socket_set_errno( err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001020 return -1;
1021 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001022
Spencer Low5200c662015-07-30 23:07:55 -07001023 const int fd = _fh_to_int(fh.get());
1024 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001025 D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd );
Spencer Low5200c662015-07-30 23:07:55 -07001026 fh.release();
1027 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001028}
1029
1030
Spencer Lowf055c192015-01-25 14:40:16 -08001031int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001032{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001033 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001034
Spencer Lowf055c192015-01-25 14:40:16 -08001035 if ( !fh || fh->clazz != &_fh_socket_class ) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001036 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001037 errno = EBADF;
1038 return -1;
1039 }
Spencer Low677fb432015-09-29 15:05:29 -07001040
1041 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1042 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1043 // auto-tuning.
1044
Spencer Low5200c662015-07-30 23:07:55 -07001045 int result = setsockopt( fh->fh_socket, level, optname,
1046 reinterpret_cast<const char*>(optval), optlen );
1047 if ( result == SOCKET_ERROR ) {
1048 const DWORD err = WSAGetLastError();
David Pursell5f787ed2016-01-27 08:52:53 -08001049 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n",
1050 fd, level, optname, android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001051 _socket_set_errno( err );
1052 result = -1;
1053 }
1054 return result;
1055}
1056
Josh Gao3777d2e2016-02-16 17:34:53 -08001057int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1058 FH fh = _fh_from_int(fd, __func__);
1059
1060 if (!fh || fh->clazz != &_fh_socket_class) {
1061 D("adb_getsockname: invalid fd %d", fd);
1062 errno = EBADF;
1063 return -1;
1064 }
1065
Josh Gao3726a012017-03-30 13:04:35 -07001066 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001067 if (result == SOCKET_ERROR) {
1068 const DWORD err = WSAGetLastError();
1069 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1070 android::base::SystemErrorCodeToString(err).c_str());
1071 _socket_set_errno(err);
1072 result = -1;
1073 }
1074 return result;
1075}
Spencer Low5200c662015-07-30 23:07:55 -07001076
David Purselleaae97e2016-04-07 11:25:48 -07001077int adb_socket_get_local_port(int fd) {
1078 sockaddr_storage addr_storage;
1079 socklen_t addr_len = sizeof(addr_storage);
1080
1081 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1082 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1083 return -1;
1084 }
1085
1086 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1087 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1088 errno = ECONNABORTED;
1089 return -1;
1090 }
1091
1092 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1093}
1094
Josh Gao2e1e7892018-03-23 13:03:28 -07001095int adb_shutdown(int fd, int direction) {
1096 FH f = _fh_from_int(fd, __func__);
Spencer Low5200c662015-07-30 23:07:55 -07001097
1098 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001099 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001100 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001101 return -1;
1102 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001103
Josh Gao2e1e7892018-03-23 13:03:28 -07001104 D("adb_shutdown: %s", f->name);
1105 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001106 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001107 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001108 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001109 _socket_set_errno(err);
1110 return -1;
1111 }
1112 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001113}
1114
Josh Gao3777d2e2016-02-16 17:34:53 -08001115// Emulate socketpair(2) by binding and connecting to a socket.
1116int adb_socketpair(int sv[2]) {
1117 int server = -1;
1118 int client = -1;
1119 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001120 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001121 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001122
Josh Gao3777d2e2016-02-16 17:34:53 -08001123 server = network_loopback_server(0, SOCK_STREAM, &error);
1124 if (server < 0) {
1125 D("adb_socketpair: failed to create server: %s", error.c_str());
1126 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001127 }
1128
David Purselleaae97e2016-04-07 11:25:48 -07001129 local_port = adb_socket_get_local_port(server);
1130 if (local_port < 0) {
1131 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001132 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001133 }
David Purselleaae97e2016-04-07 11:25:48 -07001134 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001135
David Purselleaae97e2016-04-07 11:25:48 -07001136 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001137 if (client < 0) {
1138 D("adb_socketpair: failed to connect client: %s", error.c_str());
1139 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001140 }
1141
Josh Gao3726a012017-03-30 13:04:35 -07001142 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gao3777d2e2016-02-16 17:34:53 -08001143 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001144 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001145 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001146 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001147 adb_close(server);
1148 sv[0] = client;
1149 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001150 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001151
Josh Gao3777d2e2016-02-16 17:34:53 -08001152fail:
1153 if (server >= 0) {
1154 adb_close(server);
1155 }
1156 if (client >= 0) {
1157 adb_close(client);
1158 }
1159 if (accepted >= 0) {
1160 adb_close(accepted);
1161 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001162 return -1;
1163}
1164
Josh Gao3777d2e2016-02-16 17:34:53 -08001165bool set_file_block_mode(int fd, bool block) {
1166 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001167
Josh Gao3777d2e2016-02-16 17:34:53 -08001168 if (!fh || !fh->used) {
1169 errno = EBADF;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001170 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001171 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001172 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001173
Josh Gao3777d2e2016-02-16 17:34:53 -08001174 if (fh->clazz == &_fh_socket_class) {
1175 u_long x = !block;
1176 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001177 int error = WSAGetLastError();
1178 _socket_set_errno(error);
1179 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001180 return false;
1181 }
1182 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001183 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001184 errno = ENOTSOCK;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001185 D("Setting nonblocking on non-socket %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001186 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187 }
1188}
1189
David Pursellbfd95032016-02-22 14:27:23 -08001190bool set_tcp_keepalive(int fd, int interval_sec) {
1191 FH fh = _fh_from_int(fd, __func__);
1192
1193 if (!fh || fh->clazz != &_fh_socket_class) {
1194 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1195 errno = EBADF;
1196 return false;
1197 }
1198
1199 tcp_keepalive keepalive;
1200 keepalive.onoff = (interval_sec > 0);
1201 keepalive.keepalivetime = interval_sec * 1000;
1202 keepalive.keepaliveinterval = interval_sec * 1000;
1203
1204 DWORD bytes_returned = 0;
1205 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1206 &bytes_returned, nullptr, nullptr) != 0) {
1207 const DWORD err = WSAGetLastError();
1208 D("set_tcp_keepalive(%d) failed: %s", fd,
1209 android::base::SystemErrorCodeToString(err).c_str());
1210 _socket_set_errno(err);
1211 return false;
1212 }
1213
1214 return true;
1215}
1216
Spencer Low50184062015-03-01 15:06:21 -08001217/**************************************************************************/
1218/**************************************************************************/
1219/***** *****/
1220/***** Console Window Terminal Emulation *****/
1221/***** *****/
1222/**************************************************************************/
1223/**************************************************************************/
1224
1225// This reads input from a Win32 console window and translates it into Unix
1226// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1227// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1228// is emulated instead of xterm because it is probably more popular than xterm:
1229// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1230// supports modern fonts, etc. It seems best to emulate the terminal that most
1231// Android developers use because they'll fix apps (the shell, etc.) to keep
1232// working with that terminal's emulation.
1233//
1234// The point of this emulation is not to be perfect or to solve all issues with
1235// console windows on Windows, but to be better than the original code which
1236// just called read() (which called ReadFile(), which called ReadConsoleA())
1237// which did not support Ctrl-C, tab completion, shell input line editing
1238// keys, server echo, and more.
1239//
1240// This implementation reconfigures the console with SetConsoleMode(), then
1241// calls ReadConsoleInput() to get raw input which it remaps to Unix
1242// terminal-style sequences which is returned via unix_read() which is used
1243// by the 'adb shell' command.
1244//
1245// Code organization:
1246//
David Pursellc5b8ad82015-10-28 14:29:51 -07001247// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001248// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1249// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1250// * _console_read() is the main code of the emulation.
1251
David Pursellc5b8ad82015-10-28 14:29:51 -07001252// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1253// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1254// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1255static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1256 // First check isatty(); this is very fast and eliminates most non-console
1257 // FDs, but returns 1 for both consoles and character devices like NUL.
1258#pragma push_macro("isatty")
1259#undef isatty
1260 if (!isatty(fd)) {
1261 return nullptr;
1262 }
1263#pragma pop_macro("isatty")
1264
1265 // To differentiate between character devices and consoles we need to get
1266 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1267 // GENERIC_READ permissions.
1268 const intptr_t intptr_handle = _get_osfhandle(fd);
1269 if (intptr_handle == -1) {
1270 return nullptr;
1271 }
1272 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1273 DWORD temp_mode = 0;
1274 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1275 return nullptr;
1276 }
1277
1278 return handle;
1279}
1280
1281// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1282static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001283 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1284 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001285 const int fd = fileno(stream);
1286 if (fd < 0) {
1287 return nullptr;
1288 }
1289 return _get_console_handle(fd);
1290}
1291
1292int unix_isatty(int fd) {
1293 return _get_console_handle(fd) ? 1 : 0;
1294}
Spencer Low50184062015-03-01 15:06:21 -08001295
Spencer Low32762f42015-11-10 19:17:16 -08001296// Get the next KEY_EVENT_RECORD that should be processed.
1297static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001298 for (;;) {
1299 DWORD read_count = 0;
1300 memset(input_record, 0, sizeof(*input_record));
1301 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001302 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001303 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001304 errno = EIO;
1305 return false;
1306 }
1307
1308 if (read_count == 0) { // should be impossible
1309 fatal("ReadConsoleInputA returned 0");
1310 }
1311
1312 if (read_count != 1) { // should be impossible
1313 fatal("ReadConsoleInputA did not return one input record");
1314 }
1315
Spencer Low2e02dc62015-11-07 17:34:39 -08001316 // If the console window is resized, emulate SIGWINCH by breaking out
1317 // of read() with errno == EINTR. Note that there is no event on
1318 // vertical resize because we don't give the console our own custom
1319 // screen buffer (with CreateConsoleScreenBuffer() +
1320 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1321 // supports scrollback, but doesn't seem to raise an event for vertical
1322 // window resize.
1323 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1324 errno = EINTR;
1325 return false;
1326 }
1327
Spencer Low50184062015-03-01 15:06:21 -08001328 if ((input_record->EventType == KEY_EVENT) &&
1329 (input_record->Event.KeyEvent.bKeyDown)) {
1330 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1331 fatal("ReadConsoleInputA returned a key event with zero repeat"
1332 " count");
1333 }
1334
1335 // Got an interesting INPUT_RECORD, so return
1336 return true;
1337 }
1338 }
1339}
1340
Spencer Low50184062015-03-01 15:06:21 -08001341static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1342 return (control_key_state & SHIFT_PRESSED) != 0;
1343}
1344
1345static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1346 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1347}
1348
1349static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1350 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1351}
1352
1353static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1354 return (control_key_state & NUMLOCK_ON) != 0;
1355}
1356
1357static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1358 return (control_key_state & CAPSLOCK_ON) != 0;
1359}
1360
1361static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1362 return (control_key_state & ENHANCED_KEY) != 0;
1363}
1364
1365// Constants from MSDN for ToAscii().
1366static const BYTE TOASCII_KEY_OFF = 0x00;
1367static const BYTE TOASCII_KEY_DOWN = 0x80;
1368static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1369
1370// Given a key event, ignore a modifier key and return the character that was
1371// entered without the modifier. Writes to *ch and returns the number of bytes
1372// written.
1373static size_t _get_char_ignoring_modifier(char* const ch,
1374 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1375 const WORD modifier) {
1376 // If there is no character from Windows, try ignoring the specified
1377 // modifier and look for a character. Note that if AltGr is being used,
1378 // there will be a character from Windows.
1379 if (key_event->uChar.AsciiChar == '\0') {
1380 // Note that we read the control key state from the passed in argument
1381 // instead of from key_event since the argument has been normalized.
1382 if (((modifier == VK_SHIFT) &&
1383 _is_shift_pressed(control_key_state)) ||
1384 ((modifier == VK_CONTROL) &&
1385 _is_ctrl_pressed(control_key_state)) ||
1386 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1387
1388 BYTE key_state[256] = {0};
1389 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1390 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1391 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1392 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1393 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1394 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1395 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1396 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1397
1398 // cause this modifier to be ignored
1399 key_state[modifier] = TOASCII_KEY_OFF;
1400
1401 WORD translated = 0;
1402 if (ToAscii(key_event->wVirtualKeyCode,
1403 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1404 // Ignoring the modifier, we found a character.
1405 *ch = (CHAR)translated;
1406 return 1;
1407 }
1408 }
1409 }
1410
1411 // Just use whatever Windows told us originally.
1412 *ch = key_event->uChar.AsciiChar;
1413
1414 // If the character from Windows is NULL, return a size of zero.
1415 return (*ch == '\0') ? 0 : 1;
1416}
1417
1418// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1419// but taking into account the shift key. This is because for a sequence like
1420// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1421// we want to find the character ')'.
1422//
1423// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1424// because it is the default key-sequence to switch the input language.
1425// This is configurable in the Region and Language control panel.
1426static __inline__ size_t _get_non_control_char(char* const ch,
1427 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1428 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1429 VK_CONTROL);
1430}
1431
1432// Get without Alt.
1433static __inline__ size_t _get_non_alt_char(char* const ch,
1434 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1435 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1436 VK_MENU);
1437}
1438
1439// Ignore the control key, find the character from Windows, and apply any
1440// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1441// *pch and returns number of bytes written.
1442static size_t _get_control_character(char* const pch,
1443 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1444 const size_t len = _get_non_control_char(pch, key_event,
1445 control_key_state);
1446
1447 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1448 char ch = *pch;
1449 switch (ch) {
1450 case '2':
1451 case '@':
1452 case '`':
1453 ch = '\0';
1454 break;
1455 case '3':
1456 case '[':
1457 case '{':
1458 ch = '\x1b';
1459 break;
1460 case '4':
1461 case '\\':
1462 case '|':
1463 ch = '\x1c';
1464 break;
1465 case '5':
1466 case ']':
1467 case '}':
1468 ch = '\x1d';
1469 break;
1470 case '6':
1471 case '^':
1472 case '~':
1473 ch = '\x1e';
1474 break;
1475 case '7':
1476 case '-':
1477 case '_':
1478 ch = '\x1f';
1479 break;
1480 case '8':
1481 ch = '\x7f';
1482 break;
1483 case '/':
1484 if (!_is_alt_pressed(control_key_state)) {
1485 ch = '\x1f';
1486 }
1487 break;
1488 case '?':
1489 if (!_is_alt_pressed(control_key_state)) {
1490 ch = '\x7f';
1491 }
1492 break;
1493 }
1494 *pch = ch;
1495 }
1496
1497 return len;
1498}
1499
1500static DWORD _normalize_altgr_control_key_state(
1501 const KEY_EVENT_RECORD* const key_event) {
1502 DWORD control_key_state = key_event->dwControlKeyState;
1503
1504 // If we're in an AltGr situation where the AltGr key is down (depending on
1505 // the keyboard layout, that might be the physical right alt key which
1506 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1507 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1508 // a character (which indicates that there was an AltGr mapping), then act
1509 // as if alt and control are not really down for the purposes of modifiers.
1510 // This makes it so that if the user with, say, a German keyboard layout
1511 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1512 // output the key and we don't see the Alt and Ctrl keys.
1513 if (_is_ctrl_pressed(control_key_state) &&
1514 _is_alt_pressed(control_key_state)
1515 && (key_event->uChar.AsciiChar != '\0')) {
1516 // Try to remove as few bits as possible to improve our chances of
1517 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1518 // Left-Alt + Right-Ctrl + AltGr.
1519 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1520 // Remove Right-Alt.
1521 control_key_state &= ~RIGHT_ALT_PRESSED;
1522 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1523 // pressed, Left-Ctrl is almost always set, except if the user
1524 // presses Right-Ctrl, then AltGr (in that specific order) for
1525 // whatever reason. At any rate, make sure the bit is not set.
1526 control_key_state &= ~LEFT_CTRL_PRESSED;
1527 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1528 // Remove Left-Alt.
1529 control_key_state &= ~LEFT_ALT_PRESSED;
1530 // Whichever Ctrl key is down, remove it from the state. We only
1531 // remove one key, to improve our chances of detecting the
1532 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1533 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1534 // Remove Left-Ctrl.
1535 control_key_state &= ~LEFT_CTRL_PRESSED;
1536 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1537 // Remove Right-Ctrl.
1538 control_key_state &= ~RIGHT_CTRL_PRESSED;
1539 }
1540 }
1541
1542 // Note that this logic isn't 100% perfect because Windows doesn't
1543 // allow us to detect all combinations because a physical AltGr key
1544 // press shows up as two bits, plus some combinations are ambiguous
1545 // about what is actually physically pressed.
1546 }
1547
1548 return control_key_state;
1549}
1550
1551// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1552// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1553// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1554// appropriately.
1555static DWORD _normalize_keypad_control_key_state(const WORD vk,
1556 const DWORD control_key_state) {
1557 if (!_is_numlock_on(control_key_state)) {
1558 return control_key_state;
1559 }
1560 if (!_is_enhanced_key(control_key_state)) {
1561 switch (vk) {
1562 case VK_INSERT: // 0
1563 case VK_DELETE: // .
1564 case VK_END: // 1
1565 case VK_DOWN: // 2
1566 case VK_NEXT: // 3
1567 case VK_LEFT: // 4
1568 case VK_CLEAR: // 5
1569 case VK_RIGHT: // 6
1570 case VK_HOME: // 7
1571 case VK_UP: // 8
1572 case VK_PRIOR: // 9
1573 return control_key_state | SHIFT_PRESSED;
1574 }
1575 }
1576
1577 return control_key_state;
1578}
1579
1580static const char* _get_keypad_sequence(const DWORD control_key_state,
1581 const char* const normal, const char* const shifted) {
1582 if (_is_shift_pressed(control_key_state)) {
1583 // Shift is pressed and NumLock is off
1584 return shifted;
1585 } else {
1586 // Shift is not pressed and NumLock is off, or,
1587 // Shift is pressed and NumLock is on, in which case we want the
1588 // NumLock and Shift to neutralize each other, thus, we want the normal
1589 // sequence.
1590 return normal;
1591 }
1592 // If Shift is not pressed and NumLock is on, a different virtual key code
1593 // is returned by Windows, which can be taken care of by a different case
1594 // statement in _console_read().
1595}
1596
1597// Write sequence to buf and return the number of bytes written.
1598static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1599 DWORD control_key_state, const char* const normal) {
1600 // Copy the base sequence into buf.
1601 const size_t len = strlen(normal);
1602 memcpy(buf, normal, len);
1603
1604 int code = 0;
1605
1606 control_key_state = _normalize_keypad_control_key_state(vk,
1607 control_key_state);
1608
1609 if (_is_shift_pressed(control_key_state)) {
1610 code |= 0x1;
1611 }
1612 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1613 code |= 0x2;
1614 }
1615 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1616 code |= 0x4;
1617 }
1618 // If some modifier was held down, then we need to insert the modifier code
1619 if (code != 0) {
1620 if (len == 0) {
1621 // Should be impossible because caller should pass a string of
1622 // non-zero length.
1623 return 0;
1624 }
1625 size_t index = len - 1;
1626 const char lastChar = buf[index];
1627 if (lastChar != '~') {
1628 buf[index++] = '1';
1629 }
1630 buf[index++] = ';'; // modifier separator
1631 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1632 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1633 buf[index++] = '1' + code;
1634 buf[index++] = lastChar; // move ~ (or other last char) to the end
1635 return index;
1636 }
1637 return len;
1638}
1639
1640// Write sequence to buf and return the number of bytes written.
1641static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1642 const DWORD control_key_state, const char* const normal,
1643 const char shifted) {
1644 if (_is_shift_pressed(control_key_state)) {
1645 // Shift is pressed and NumLock is off
1646 if (shifted != '\0') {
1647 buf[0] = shifted;
1648 return sizeof(buf[0]);
1649 } else {
1650 return 0;
1651 }
1652 } else {
1653 // Shift is not pressed and NumLock is off, or,
1654 // Shift is pressed and NumLock is on, in which case we want the
1655 // NumLock and Shift to neutralize each other, thus, we want the normal
1656 // sequence.
1657 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1658 }
1659 // If Shift is not pressed and NumLock is on, a different virtual key code
1660 // is returned by Windows, which can be taken care of by a different case
1661 // statement in _console_read().
1662}
1663
1664// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1665// Standard German. Figure this out at runtime so we know what to output for
1666// Shift-VK_DELETE.
1667static char _get_decimal_char() {
1668 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1669}
1670
1671// Prefix the len bytes in buf with the escape character, and then return the
1672// new buffer length.
1673size_t _escape_prefix(char* const buf, const size_t len) {
1674 // If nothing to prefix, don't do anything. We might be called with
1675 // len == 0, if alt was held down with a dead key which produced nothing.
1676 if (len == 0) {
1677 return 0;
1678 }
1679
1680 memmove(&buf[1], buf, len);
1681 buf[0] = '\x1b';
1682 return len + 1;
1683}
1684
Spencer Low32762f42015-11-10 19:17:16 -08001685// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001686static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001687
1688// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1689// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001690static int _console_read(const HANDLE console, void* buf, size_t len) {
1691 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001692 // Read of zero bytes should not block waiting for something from the console.
1693 if (len == 0) {
1694 return 0;
1695 }
1696
1697 // Flush as much as possible from input buffer.
1698 if (!g_console_input_buffer.empty()) {
1699 const int bytes_read = std::min(len, g_console_input_buffer.size());
1700 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1701 const auto begin = g_console_input_buffer.begin();
1702 g_console_input_buffer.erase(begin, begin + bytes_read);
1703 return bytes_read;
1704 }
1705
1706 // Read from the actual console. This may block until input.
1707 INPUT_RECORD input_record;
1708 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001709 return -1;
1710 }
1711
Spencer Low32762f42015-11-10 19:17:16 -08001712 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001713 const WORD vk = key_event->wVirtualKeyCode;
1714 const CHAR ch = key_event->uChar.AsciiChar;
1715 const DWORD control_key_state = _normalize_altgr_control_key_state(
1716 key_event);
1717
1718 // The following emulation code should write the output sequence to
1719 // either seqstr or to seqbuf and seqbuflen.
1720 const char* seqstr = NULL; // NULL terminated C-string
1721 // Enough space for max sequence string below, plus modifiers and/or
1722 // escape prefix.
1723 char seqbuf[16];
1724 size_t seqbuflen = 0; // Space used in seqbuf.
1725
1726#define MATCH(vk, normal) \
1727 case (vk): \
1728 { \
1729 seqstr = (normal); \
1730 } \
1731 break;
1732
1733 // Modifier keys should affect the output sequence.
1734#define MATCH_MODIFIER(vk, normal) \
1735 case (vk): \
1736 { \
1737 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1738 control_key_state, (normal)); \
1739 } \
1740 break;
1741
1742 // The shift key should affect the output sequence.
1743#define MATCH_KEYPAD(vk, normal, shifted) \
1744 case (vk): \
1745 { \
1746 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1747 (shifted)); \
1748 } \
1749 break;
1750
1751 // The shift key and other modifier keys should affect the output
1752 // sequence.
1753#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1754 case (vk): \
1755 { \
1756 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1757 control_key_state, (normal), (shifted)); \
1758 } \
1759 break;
1760
1761#define ESC "\x1b"
1762#define CSI ESC "["
1763#define SS3 ESC "O"
1764
1765 // Only support normal mode, not application mode.
1766
1767 // Enhanced keys:
1768 // * 6-pack: insert, delete, home, end, page up, page down
1769 // * cursor keys: up, down, right, left
1770 // * keypad: divide, enter
1771 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1772 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1773 if (_is_enhanced_key(control_key_state)) {
1774 switch (vk) {
1775 case VK_RETURN: // Enter key on keypad
1776 if (_is_ctrl_pressed(control_key_state)) {
1777 seqstr = "\n";
1778 } else {
1779 seqstr = "\r";
1780 }
1781 break;
1782
1783 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1784 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1785
1786 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1787 // will be fixed soon to match xterm which sends CSI "F" and
1788 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1789 MATCH(VK_END, CSI "F");
1790 MATCH(VK_HOME, CSI "H");
1791
1792 MATCH_MODIFIER(VK_LEFT, CSI "D");
1793 MATCH_MODIFIER(VK_UP, CSI "A");
1794 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1795 MATCH_MODIFIER(VK_DOWN, CSI "B");
1796
1797 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1798 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1799
1800 MATCH(VK_DIVIDE, "/");
1801 }
1802 } else { // Non-enhanced keys:
1803 switch (vk) {
1804 case VK_BACK: // backspace
1805 if (_is_alt_pressed(control_key_state)) {
1806 seqstr = ESC "\x7f";
1807 } else {
1808 seqstr = "\x7f";
1809 }
1810 break;
1811
1812 case VK_TAB:
1813 if (_is_shift_pressed(control_key_state)) {
1814 seqstr = CSI "Z";
1815 } else {
1816 seqstr = "\t";
1817 }
1818 break;
1819
1820 // Number 5 key in keypad when NumLock is off, or if NumLock is
1821 // on and Shift is down.
1822 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1823
1824 case VK_RETURN: // Enter key on main keyboard
1825 if (_is_alt_pressed(control_key_state)) {
1826 seqstr = ESC "\n";
1827 } else if (_is_ctrl_pressed(control_key_state)) {
1828 seqstr = "\n";
1829 } else {
1830 seqstr = "\r";
1831 }
1832 break;
1833
1834 // VK_ESCAPE: Don't do any special handling. The OS uses many
1835 // of the sequences with Escape and many of the remaining
1836 // sequences don't produce bKeyDown messages, only !bKeyDown
1837 // for whatever reason.
1838
1839 case VK_SPACE:
1840 if (_is_alt_pressed(control_key_state)) {
1841 seqstr = ESC " ";
1842 } else if (_is_ctrl_pressed(control_key_state)) {
1843 seqbuf[0] = '\0'; // NULL char
1844 seqbuflen = 1;
1845 } else {
1846 seqstr = " ";
1847 }
1848 break;
1849
1850 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1851 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1852
1853 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1854 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1855
1856 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1857 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1858 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1859 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1860
1861 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1862 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1863 _get_decimal_char());
1864
1865 case 0x30: // 0
1866 case 0x31: // 1
1867 case 0x39: // 9
1868 case VK_OEM_1: // ;:
1869 case VK_OEM_PLUS: // =+
1870 case VK_OEM_COMMA: // ,<
1871 case VK_OEM_PERIOD: // .>
1872 case VK_OEM_7: // '"
1873 case VK_OEM_102: // depends on keyboard, could be <> or \|
1874 case VK_OEM_2: // /?
1875 case VK_OEM_3: // `~
1876 case VK_OEM_4: // [{
1877 case VK_OEM_5: // \|
1878 case VK_OEM_6: // ]}
1879 {
1880 seqbuflen = _get_control_character(seqbuf, key_event,
1881 control_key_state);
1882
1883 if (_is_alt_pressed(control_key_state)) {
1884 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1885 }
1886 }
1887 break;
1888
1889 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001890 case 0x33: // 3
1891 case 0x34: // 4
1892 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001893 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001894 case 0x37: // 7
1895 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001896 case VK_OEM_MINUS: // -_
1897 {
1898 seqbuflen = _get_control_character(seqbuf, key_event,
1899 control_key_state);
1900
1901 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1902 // prefix with escape.
1903 if (_is_alt_pressed(control_key_state) &&
1904 !(_is_ctrl_pressed(control_key_state) &&
1905 !_is_shift_pressed(control_key_state))) {
1906 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1907 }
1908 }
1909 break;
1910
Spencer Low50184062015-03-01 15:06:21 -08001911 case 0x41: // a
1912 case 0x42: // b
1913 case 0x43: // c
1914 case 0x44: // d
1915 case 0x45: // e
1916 case 0x46: // f
1917 case 0x47: // g
1918 case 0x48: // h
1919 case 0x49: // i
1920 case 0x4a: // j
1921 case 0x4b: // k
1922 case 0x4c: // l
1923 case 0x4d: // m
1924 case 0x4e: // n
1925 case 0x4f: // o
1926 case 0x50: // p
1927 case 0x51: // q
1928 case 0x52: // r
1929 case 0x53: // s
1930 case 0x54: // t
1931 case 0x55: // u
1932 case 0x56: // v
1933 case 0x57: // w
1934 case 0x58: // x
1935 case 0x59: // y
1936 case 0x5a: // z
1937 {
1938 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1939 control_key_state);
1940
1941 // If Alt is pressed, then prefix with escape.
1942 if (_is_alt_pressed(control_key_state)) {
1943 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1944 }
1945 }
1946 break;
1947
1948 // These virtual key codes are generated by the keys on the
1949 // keypad *when NumLock is on* and *Shift is up*.
1950 MATCH(VK_NUMPAD0, "0");
1951 MATCH(VK_NUMPAD1, "1");
1952 MATCH(VK_NUMPAD2, "2");
1953 MATCH(VK_NUMPAD3, "3");
1954 MATCH(VK_NUMPAD4, "4");
1955 MATCH(VK_NUMPAD5, "5");
1956 MATCH(VK_NUMPAD6, "6");
1957 MATCH(VK_NUMPAD7, "7");
1958 MATCH(VK_NUMPAD8, "8");
1959 MATCH(VK_NUMPAD9, "9");
1960
1961 MATCH(VK_MULTIPLY, "*");
1962 MATCH(VK_ADD, "+");
1963 MATCH(VK_SUBTRACT, "-");
1964 // VK_DECIMAL is generated by the . key on the keypad *when
1965 // NumLock is on* and *Shift is up* and the sequence is not
1966 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1967 // Windows Security screen to come up).
1968 case VK_DECIMAL:
1969 // U.S. English uses '.', Germany German uses ','.
1970 seqbuflen = _get_non_control_char(seqbuf, key_event,
1971 control_key_state);
1972 break;
1973
1974 MATCH_MODIFIER(VK_F1, SS3 "P");
1975 MATCH_MODIFIER(VK_F2, SS3 "Q");
1976 MATCH_MODIFIER(VK_F3, SS3 "R");
1977 MATCH_MODIFIER(VK_F4, SS3 "S");
1978 MATCH_MODIFIER(VK_F5, CSI "15~");
1979 MATCH_MODIFIER(VK_F6, CSI "17~");
1980 MATCH_MODIFIER(VK_F7, CSI "18~");
1981 MATCH_MODIFIER(VK_F8, CSI "19~");
1982 MATCH_MODIFIER(VK_F9, CSI "20~");
1983 MATCH_MODIFIER(VK_F10, CSI "21~");
1984 MATCH_MODIFIER(VK_F11, CSI "23~");
1985 MATCH_MODIFIER(VK_F12, CSI "24~");
1986
1987 MATCH_MODIFIER(VK_F13, CSI "25~");
1988 MATCH_MODIFIER(VK_F14, CSI "26~");
1989 MATCH_MODIFIER(VK_F15, CSI "28~");
1990 MATCH_MODIFIER(VK_F16, CSI "29~");
1991 MATCH_MODIFIER(VK_F17, CSI "31~");
1992 MATCH_MODIFIER(VK_F18, CSI "32~");
1993 MATCH_MODIFIER(VK_F19, CSI "33~");
1994 MATCH_MODIFIER(VK_F20, CSI "34~");
1995
1996 // MATCH_MODIFIER(VK_F21, ???);
1997 // MATCH_MODIFIER(VK_F22, ???);
1998 // MATCH_MODIFIER(VK_F23, ???);
1999 // MATCH_MODIFIER(VK_F24, ???);
2000 }
2001 }
2002
2003#undef MATCH
2004#undef MATCH_MODIFIER
2005#undef MATCH_KEYPAD
2006#undef MATCH_MODIFIER_KEYPAD
2007#undef ESC
2008#undef CSI
2009#undef SS3
2010
2011 const char* out;
2012 size_t outlen;
2013
2014 // Check for output in any of:
2015 // * seqstr is set (and strlen can be used to determine the length).
2016 // * seqbuf and seqbuflen are set
2017 // Fallback to ch from Windows.
2018 if (seqstr != NULL) {
2019 out = seqstr;
2020 outlen = strlen(seqstr);
2021 } else if (seqbuflen > 0) {
2022 out = seqbuf;
2023 outlen = seqbuflen;
2024 } else if (ch != '\0') {
2025 // Use whatever Windows told us it is.
2026 seqbuf[0] = ch;
2027 seqbuflen = 1;
2028 out = seqbuf;
2029 outlen = seqbuflen;
2030 } else {
2031 // No special handling for the virtual key code and Windows isn't
2032 // telling us a character code, then we don't know how to translate
2033 // the key press.
2034 //
2035 // Consume the input and 'continue' to cause us to get a new key
2036 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002037 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002038 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002039 continue;
2040 }
2041
Spencer Low32762f42015-11-10 19:17:16 -08002042 // put output wRepeatCount times into g_console_input_buffer
2043 while (key_event->wRepeatCount-- > 0) {
2044 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002045 }
2046
Spencer Low32762f42015-11-10 19:17:16 -08002047 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002048 }
2049}
2050
2051static DWORD _old_console_mode; // previous GetConsoleMode() result
2052static HANDLE _console_handle; // when set, console mode should be restored
2053
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002054void stdin_raw_init() {
2055 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002056 if (in == nullptr) {
2057 return;
2058 }
Spencer Low50184062015-03-01 15:06:21 -08002059
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002060 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2061 // calling the process Ctrl-C routine (configured by
2062 // SetConsoleCtrlHandler()).
2063 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2064 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2065 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002066 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2067 ENABLE_LINE_INPUT |
2068 ENABLE_ECHO_INPUT);
2069 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2070 new_console_mode |= ENABLE_WINDOW_INPUT;
2071
2072 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002073 // This really should not fail.
2074 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002075 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002076 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002077
2078 // Once this is set, it means that stdin has been configured for
2079 // reading from and that the old console mode should be restored later.
2080 _console_handle = in;
2081
2082 // Note that we don't need to configure C Runtime line-ending
2083 // translation because _console_read() does not call the C Runtime to
2084 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002085}
2086
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002087void stdin_raw_restore() {
2088 if (_console_handle != NULL) {
2089 const HANDLE in = _console_handle;
2090 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002091
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002092 if (!SetConsoleMode(in, _old_console_mode)) {
2093 // This really should not fail.
2094 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002095 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002096 }
2097 }
2098}
2099
Spencer Low2e02dc62015-11-07 17:34:39 -08002100// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2101int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08002102 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2103 // If it is a request to read from stdin, and stdin_raw_init() has been
2104 // called, and it successfully configured the console, then read from
2105 // the console using Win32 console APIs and partially emulate a unix
2106 // terminal.
2107 return _console_read(_console_handle, buf, len);
2108 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002109 // On older versions of Windows (definitely 7, definitely not 10),
2110 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002111 // we need to limit the read size.
2112 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002113 len = 4096;
2114 }
Spencer Low50184062015-03-01 15:06:21 -08002115 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002116 // can do LF/CR translation (which is overridable with _setmode()).
2117 // Undefine the macro that is set in sysdeps.h which bans calls to
2118 // plain read() in favor of unix_read() or adb_read().
2119#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002120#undef read
2121 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002122#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002123 }
2124}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002125
2126/**************************************************************************/
2127/**************************************************************************/
2128/***** *****/
2129/***** Unicode support *****/
2130/***** *****/
2131/**************************************************************************/
2132/**************************************************************************/
2133
2134// This implements support for using files with Unicode filenames and for
2135// outputting Unicode text to a Win32 console window. This is inspired from
2136// http://utf8everywhere.org/.
2137//
2138// Background
2139// ----------
2140//
2141// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2142// filenames to APIs such as open(). This works because filenames are largely
2143// opaque 'cookies' (perhaps excluding path separators).
2144//
2145// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2146// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2147// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2148// CreateFile() API is really just a macro that adds the W/A based on whether
2149// the UNICODE preprocessor symbol is defined).
2150//
2151// Options
2152// -------
2153//
2154// Thus, to write a portable program, there are a few options:
2155//
2156// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2157// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2158// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2159// open() API.
2160//
2161// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2162// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2163// potentially touching a lot of code.
2164//
2165// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2166// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2167// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2168// or C Runtime API.
2169//
2170// The Choice
2171// ----------
2172//
Spencer Lowd21dc822015-11-12 15:20:15 -08002173// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2174// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002175// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002176// args that are passed to main() at the beginning of program startup. We also use
2177// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002178// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2179//
2180// Unicode console output
2181// ----------------------
2182//
2183// The way to output Unicode to a Win32 console window is to call
2184// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002185// such as Lucida Console or Consolas, and in the case of East Asian languages
2186// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2187// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2188// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002189//
2190// The problem is getting the C Runtime to make fprintf and related APIs call
2191// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2192// promising, but the various modes have issues:
2193//
2194// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2195// UTF-16 do not display properly.
2196// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2197// totally wrong.
2198// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2199// handler to be called (upon a later I/O call), aborting the process.
2200// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2201// to output nothing.
2202//
2203// So the only solution is to write our own adb_fprintf() that converts UTF-8
2204// to UTF-16 and then calls WriteConsoleW().
2205
2206
Spencer Lowcf4ff642015-05-11 01:08:48 -07002207// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2208// be passed to main().
2209NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2210 narrow_args = new char*[argc + 1];
2211
2212 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002213 std::string arg_narrow;
2214 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2215 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2216 }
2217 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002218 }
2219 narrow_args[argc] = nullptr; // terminate
2220}
2221
2222NarrowArgs::~NarrowArgs() {
2223 if (narrow_args != nullptr) {
2224 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2225 free(*argp);
2226 }
2227 delete[] narrow_args;
2228 narrow_args = nullptr;
2229 }
2230}
2231
2232int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002233 std::wstring path_wide;
2234 if (!android::base::UTF8ToWide(path, &path_wide)) {
2235 return -1;
2236 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002237 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002238 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002239 } else {
2240 int mode;
2241 va_list args;
2242 va_start(args, options);
2243 mode = va_arg(args, int);
2244 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002245 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002246 }
2247}
2248
Spencer Lowcf4ff642015-05-11 01:08:48 -07002249// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002250DIR* adb_opendir(const char* path) {
2251 std::wstring path_wide;
2252 if (!android::base::UTF8ToWide(path, &path_wide)) {
2253 return nullptr;
2254 }
2255
Spencer Lowcf4ff642015-05-11 01:08:48 -07002256 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2257 // the fields, but right now all the callers treat the structure as
2258 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002259 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002260}
2261
2262// Version of readdir() that returns UTF-8 paths.
2263struct dirent* adb_readdir(DIR* dir) {
2264 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2265 struct _wdirent* const went = _wreaddir(wdir);
2266 if (went == nullptr) {
2267 return nullptr;
2268 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002269
Spencer Lowcf4ff642015-05-11 01:08:48 -07002270 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002271 std::string name_utf8;
2272 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2273 return nullptr;
2274 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002275
2276 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2277 // space for UTF-16 wchar_t's) with UTF-8 char's.
2278 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2279
2280 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2281 // Name too big to fit in existing buffer.
2282 errno = ENOMEM;
2283 return nullptr;
2284 }
2285
2286 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2287 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2288 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2289 // bigger than the caller expects because they expect a dirent structure
2290 // which has a smaller d_name field. Ignore this since the caller should be
2291 // resilient.
2292
2293 // Rewrite the UTF-16 d_name field to UTF-8.
2294 strcpy(ent->d_name, name_utf8.c_str());
2295
2296 return ent;
2297}
2298
2299// Version of closedir() to go with our version of adb_opendir().
2300int adb_closedir(DIR* dir) {
2301 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2302}
2303
2304// Version of unlink() that takes a UTF-8 path.
2305int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002306 std::wstring wpath;
2307 if (!android::base::UTF8ToWide(path, &wpath)) {
2308 return -1;
2309 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002310
2311 int rc = _wunlink(wpath.c_str());
2312
2313 if (rc == -1 && errno == EACCES) {
2314 /* unlink returns EACCES when the file is read-only, so we first */
2315 /* try to make it writable, then unlink again... */
2316 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2317 if (rc == 0)
2318 rc = _wunlink(wpath.c_str());
2319 }
2320 return rc;
2321}
2322
2323// Version of mkdir() that takes a UTF-8 path.
2324int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002325 std::wstring path_wide;
2326 if (!android::base::UTF8ToWide(path, &path_wide)) {
2327 return -1;
2328 }
2329
2330 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002331}
2332
2333// Version of utime() that takes a UTF-8 path.
2334int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002335 std::wstring path_wide;
2336 if (!android::base::UTF8ToWide(path, &path_wide)) {
2337 return -1;
2338 }
2339
Spencer Lowcf4ff642015-05-11 01:08:48 -07002340 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2341 "utimbuf and _utimbuf should be the same size because they both "
2342 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002343 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002344}
2345
2346// Version of chmod() that takes a UTF-8 path.
2347int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002348 std::wstring path_wide;
2349 if (!android::base::UTF8ToWide(path, &path_wide)) {
2350 return -1;
2351 }
2352
2353 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002354}
2355
Spencer Lowa30b79a2015-11-15 16:29:36 -08002356// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2357static inline size_t utf8_codepoint_len(uint8_t ch) {
2358 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2359}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002360
Spencer Lowa30b79a2015-11-15 16:29:36 -08002361namespace internal {
2362
2363// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2364// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2365// remaining_bytes.
2366size_t ParseCompleteUTF8(const char* const first, const char* const last,
2367 std::vector<char>* const remaining_bytes) {
2368 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2369 // Current_after points one byte past the current byte to be examined.
2370 for (const char* current_after = last; current_after != first; --current_after) {
2371 const char* const current = current_after - 1;
2372 const char ch = *current;
2373 const char kHighBit = 0x80u;
2374 const char kTwoHighestBits = 0xC0u;
2375 if ((ch & kHighBit) == 0) { // high bit not set
2376 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2377 // bytes with no leading byte, so return the entire buffer.
2378 break;
2379 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2380 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2381 const size_t bytes_available = last - current;
2382 if (bytes_available < utf8_codepoint_len(ch)) {
2383 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2384 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2385 // to remaining_bytes.
2386 remaining_bytes->insert(remaining_bytes->end(), current, last);
2387 return current - first;
2388 } else {
2389 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2390 // trailing bytes with no lead byte, so return the entire buffer.
2391 break;
2392 }
2393 } else {
2394 // Trailing byte, so keep going backwards looking for the lead byte.
2395 }
2396 }
2397
2398 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2399 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2400 // so that they can be processed.
2401 return last - first;
2402}
2403
2404}
2405
2406// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2407// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2408// This matches the behavior of Linux.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002409
2410// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2411static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2412 HANDLE console) {
Josh Gao0cd3ae12016-09-21 12:37:10 -07002413 static std::mutex& console_output_buffer_lock = *new std::mutex();
2414 static auto& console_output_buffer = *new std::vector<char>();
2415
Spencer Lowa30b79a2015-11-15 16:29:36 -08002416 const int saved_errno = errno;
2417 std::vector<char> combined_buffer;
2418
2419 // Complete UTF-8 sequences that should be immediately written to the console.
2420 const char* utf8;
2421 size_t utf8_size;
2422
Josh Gao0cd3ae12016-09-21 12:37:10 -07002423 {
2424 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2425 if (console_output_buffer.empty()) {
2426 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2427 // common case with plain ASCII), parse buf directly.
2428 utf8 = buf;
2429 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2430 } else {
2431 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2432 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2433 // combined_buffer, then parse it all together.
2434 combined_buffer.swap(console_output_buffer);
2435 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002436
Josh Gao0cd3ae12016-09-21 12:37:10 -07002437 utf8 = combined_buffer.data();
2438 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2439 &console_output_buffer);
2440 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002441 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002442
2443 std::wstring utf16;
2444
2445 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2446 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2447 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002448 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002449 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002450
2451 // Note that this does not do \n => \r\n translation because that
2452 // doesn't seem necessary for the Windows console. For the Windows
2453 // console \r moves to the beginning of the line and \n moves to a new
2454 // line.
2455
2456 // Flush any stream buffering so that our output is afterwards which
2457 // makes sense because our call is afterwards.
2458 (void)fflush(stream);
2459
2460 // Write UTF-16 to the console.
2461 DWORD written = 0;
Spencer Lowa30b79a2015-11-15 16:29:36 -08002462 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002463 errno = EIO;
2464 return -1;
2465 }
2466
Spencer Lowa30b79a2015-11-15 16:29:36 -08002467 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2468 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2469 // matches the Linux behavior.
2470 errno = saved_errno;
2471 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002472}
2473
2474// Function prototype because attributes cannot be placed on func definitions.
2475static int _console_vfprintf(const HANDLE console, FILE* stream,
2476 const char *format, va_list ap)
2477 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2478
2479// Internal function to format a UTF-8 string and write it to a Win32 console.
2480// Returns -1 on error.
2481static int _console_vfprintf(const HANDLE console, FILE* stream,
2482 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002483 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002484 std::string output_utf8;
2485
2486 // Format the string.
2487 // This could throw std::bad_alloc.
2488 android::base::StringAppendV(&output_utf8, format, ap);
2489
Spencer Lowa30b79a2015-11-15 16:29:36 -08002490 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2491 console);
2492 if (result != -1) {
2493 errno = saved_errno;
2494 } else {
2495 // If -1 was returned, errno has been set.
2496 }
2497 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002498}
2499
2500// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2501// Windows console.
2502int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2503 const HANDLE console = _get_console_handle(stream);
2504
2505 // If there is an associated Win32 console, write to it specially,
2506 // otherwise defer to the regular C Runtime, passing it UTF-8.
2507 if (console != NULL) {
2508 return _console_vfprintf(console, stream, format, ap);
2509 } else {
2510 // If vfprintf is a macro, undefine it, so we can call the real
2511 // C Runtime API.
2512#pragma push_macro("vfprintf")
2513#undef vfprintf
2514 return vfprintf(stream, format, ap);
2515#pragma pop_macro("vfprintf")
2516 }
2517}
2518
Spencer Lowa30b79a2015-11-15 16:29:36 -08002519// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2520int adb_vprintf(const char *format, va_list ap) {
2521 return adb_vfprintf(stdout, format, ap);
2522}
2523
Spencer Lowcf4ff642015-05-11 01:08:48 -07002524// Version of fprintf() that takes UTF-8 and can write Unicode to a
2525// Windows console.
2526int adb_fprintf(FILE *stream, const char *format, ...) {
2527 va_list ap;
2528 va_start(ap, format);
2529 const int result = adb_vfprintf(stream, format, ap);
2530 va_end(ap);
2531
2532 return result;
2533}
2534
2535// Version of printf() that takes UTF-8 and can write Unicode to a
2536// Windows console.
2537int adb_printf(const char *format, ...) {
2538 va_list ap;
2539 va_start(ap, format);
2540 const int result = adb_vfprintf(stdout, format, ap);
2541 va_end(ap);
2542
2543 return result;
2544}
2545
2546// Version of fputs() that takes UTF-8 and can write Unicode to a
2547// Windows console.
2548int adb_fputs(const char* buf, FILE* stream) {
2549 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2550 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002551 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002552 return adb_fprintf(stream, "%s", buf);
2553}
2554
2555// Version of fputc() that takes UTF-8 and can write Unicode to a
2556// Windows console.
2557int adb_fputc(int ch, FILE* stream) {
2558 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002559 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002560 return EOF;
2561 }
2562 // For success, fputc returns the char, cast to unsigned char, then to int.
2563 return static_cast<unsigned char>(ch);
2564}
2565
Spencer Lowa30b79a2015-11-15 16:29:36 -08002566// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2567int adb_putchar(int ch) {
2568 return adb_fputc(ch, stdout);
2569}
2570
2571// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2572int adb_puts(const char* buf) {
2573 // adb_printf returns -1 on error, which is conveniently the same as EOF
2574 // which puts (and hence adb_puts) should return on error.
2575 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2576 return adb_printf("%s\n", buf);
2577}
2578
Spencer Lowcf4ff642015-05-11 01:08:48 -07002579// Internal function to write UTF-8 to a Win32 console. Returns the number of
2580// items (of length size) written. On error, returns a short item count or 0.
2581static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2582 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002583 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2584 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002585 if (result == -1) {
2586 return 0;
2587 }
2588 return result / size;
2589}
2590
2591// Version of fwrite() that takes UTF-8 and can write Unicode to a
2592// Windows console.
2593size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2594 const HANDLE console = _get_console_handle(stream);
2595
2596 // If there is an associated Win32 console, write to it specially,
2597 // otherwise defer to the regular C Runtime, passing it UTF-8.
2598 if (console != NULL) {
2599 return _console_fwrite(ptr, size, nmemb, stream, console);
2600 } else {
2601 // If fwrite is a macro, undefine it, so we can call the real
2602 // C Runtime API.
2603#pragma push_macro("fwrite")
2604#undef fwrite
2605 return fwrite(ptr, size, nmemb, stream);
2606#pragma pop_macro("fwrite")
2607 }
2608}
2609
2610// Version of fopen() that takes a UTF-8 filename and can access a file with
2611// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002612FILE* adb_fopen(const char* path, const char* mode) {
2613 std::wstring path_wide;
2614 if (!android::base::UTF8ToWide(path, &path_wide)) {
2615 return nullptr;
2616 }
2617
2618 std::wstring mode_wide;
2619 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2620 return nullptr;
2621 }
2622
2623 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002624}
2625
Spencer Lowe6ae5732015-09-08 17:13:04 -07002626// Return a lowercase version of the argument. Uses C Runtime tolower() on
2627// each byte which is not UTF-8 aware, and theoretically uses the current C
2628// Runtime locale (which in practice is not changed, so this becomes a ASCII
2629// conversion).
2630static std::string ToLower(const std::string& anycase) {
2631 // copy string
2632 std::string str(anycase);
2633 // transform the copy
2634 std::transform(str.begin(), str.end(), str.begin(), tolower);
2635 return str;
2636}
2637
2638extern "C" int main(int argc, char** argv);
2639
2640// Link with -municode to cause this wmain() to be used as the program
2641// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2642// regular main() with UTF-8 args.
2643extern "C" int wmain(int argc, wchar_t **argv) {
2644 // Convert args from UTF-16 to UTF-8 and pass that to main().
2645 NarrowArgs narrow_args(argc, argv);
2646 return main(argc, narrow_args.data());
2647}
2648
Spencer Lowcf4ff642015-05-11 01:08:48 -07002649// Shadow UTF-8 environment variable name/value pairs that are created from
2650// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002651// currently updated if putenv, setenv, unsetenv are called. Note that no
2652// thread synchronization is done, but we're called early enough in
2653// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002654static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002655
2656// Make sure that shadow UTF-8 environment variables are setup.
2657static void _ensure_env_setup() {
2658 // If some name/value pairs exist, then we've already done the setup below.
2659 if (g_environ_utf8.size() != 0) {
2660 return;
2661 }
2662
Spencer Lowe6ae5732015-09-08 17:13:04 -07002663 if (_wenviron == nullptr) {
2664 // If _wenviron is null, then -municode probably wasn't used. That
2665 // linker flag will cause the entry point to setup _wenviron. It will
2666 // also require an implementation of wmain() (which we provide above).
2667 fatal("_wenviron is not set, did you link with -municode?");
2668 }
2669
Spencer Lowcf4ff642015-05-11 01:08:48 -07002670 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2671 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2672 // to use the D() macro here because that tracing only works if the
2673 // ADB_TRACE environment variable is setup, but that env var can't be read
2674 // until this code completes.
2675 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2676 wchar_t* const equal = wcschr(*env, L'=');
2677 if (equal == nullptr) {
2678 // Malformed environment variable with no equal sign. Shouldn't
2679 // really happen, but we should be resilient to this.
2680 continue;
2681 }
2682
Spencer Lowd21dc822015-11-12 15:20:15 -08002683 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2684 // var because the program might never even read this particular variable.
2685 std::string name_utf8;
2686 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2687 continue;
2688 }
2689
Spencer Lowe6ae5732015-09-08 17:13:04 -07002690 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002691 name_utf8 = ToLower(name_utf8);
2692
2693 std::string value_utf8;
2694 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2695 continue;
2696 }
2697
2698 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002699
Spencer Lowe6ae5732015-09-08 17:13:04 -07002700 // Don't overwrite a previus env var with the same name. In reality,
2701 // the system probably won't let two env vars with the same name exist
2702 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002703 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002704 }
2705}
2706
2707// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002708// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002709char* adb_getenv(const char* name) {
2710 _ensure_env_setup();
2711
Spencer Lowe6ae5732015-09-08 17:13:04 -07002712 // Case-insensitive search by searching for lowercase name in a map of
2713 // lowercase names.
2714 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002715 if (it == g_environ_utf8.end()) {
2716 return nullptr;
2717 }
2718
2719 return it->second;
2720}
2721
2722// Version of getcwd() that returns the current working directory in UTF-8.
2723char* adb_getcwd(char* buf, int size) {
2724 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2725 if (wbuf == nullptr) {
2726 return nullptr;
2727 }
2728
Spencer Lowd21dc822015-11-12 15:20:15 -08002729 std::string buf_utf8;
2730 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002731 free(wbuf);
2732 wbuf = nullptr;
2733
Spencer Lowd21dc822015-11-12 15:20:15 -08002734 if (!narrow_result) {
2735 return nullptr;
2736 }
2737
Spencer Lowcf4ff642015-05-11 01:08:48 -07002738 // If size was specified, make sure all the chars will fit.
2739 if (size != 0) {
2740 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2741 errno = ERANGE;
2742 return nullptr;
2743 }
2744 }
2745
2746 // If buf was not specified, allocate storage.
2747 if (buf == nullptr) {
2748 if (size == 0) {
2749 size = buf_utf8.length() + 1;
2750 }
2751 buf = reinterpret_cast<char*>(malloc(size));
2752 if (buf == nullptr) {
2753 return nullptr;
2754 }
2755 }
2756
2757 // Destination buffer was allocated with enough space, or we've already
2758 // checked an existing buffer size for enough space.
2759 strcpy(buf, buf_utf8.c_str());
2760
2761 return buf;
2762}