blob: b5334b14133a15228accb2d282752f738301a2e7 [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
Josh Gao64a63ac2018-04-05 18:09:02 -0700358int adb_open(const char* path, int options) {
359 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800360
Josh Gao64a63ac2018-04-05 18:09:02 -0700361 DWORD desiredAccess = 0;
362 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363
364 switch (options) {
365 case O_RDONLY:
366 desiredAccess = GENERIC_READ;
367 break;
368 case O_WRONLY:
369 desiredAccess = GENERIC_WRITE;
370 break;
371 case O_RDWR:
372 desiredAccess = GENERIC_READ | GENERIC_WRITE;
373 break;
374 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700375 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800376 errno = EINVAL;
377 return -1;
378 }
379
Josh Gao64a63ac2018-04-05 18:09:02 -0700380 f = _fh_alloc(&_fh_file_class);
381 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800382 return -1;
383 }
384
Spencer Lowd21dc822015-11-12 15:20:15 -0800385 std::wstring path_wide;
386 if (!android::base::UTF8ToWide(path, &path_wide)) {
387 return -1;
388 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700389 f->fh_handle =
390 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, NULL, OPEN_EXISTING, 0, NULL);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391
Josh Gao64a63ac2018-04-05 18:09:02 -0700392 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700393 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800394 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700395 D("adb_open: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700396 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800397 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700398 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800399 errno = ENOENT;
400 return -1;
401
402 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700403 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800404 errno = ENOTDIR;
405 return -1;
406
407 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800408 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 errno = ENOENT;
410 return -1;
411 }
412 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800413
Josh Gao64a63ac2018-04-05 18:09:02 -0700414 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
415 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800416 return _fh_to_int(f);
417}
418
419/* ignore mode on Win32 */
Josh Gao64a63ac2018-04-05 18:09:02 -0700420int adb_creat(const char* path, int mode) {
421 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422
Josh Gao64a63ac2018-04-05 18:09:02 -0700423 f = _fh_alloc(&_fh_file_class);
424 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800425 return -1;
426 }
427
Spencer Lowd21dc822015-11-12 15:20:15 -0800428 std::wstring path_wide;
429 if (!android::base::UTF8ToWide(path, &path_wide)) {
430 return -1;
431 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700432 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
433 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434
Josh Gao64a63ac2018-04-05 18:09:02 -0700435 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700436 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800437 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700438 D("adb_creat: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700439 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800440 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700441 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800442 errno = ENOENT;
443 return -1;
444
445 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700446 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800447 errno = ENOTDIR;
448 return -1;
449
450 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800451 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452 errno = ENOENT;
453 return -1;
454 }
455 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700456 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
457 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800458 return _fh_to_int(f);
459}
460
Josh Gao116aa0a2018-04-05 17:55:25 -0700461int adb_read(int fd, void* buf, int len) {
462 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800463
464 if (f == NULL) {
465 return -1;
466 }
467
Josh Gao116aa0a2018-04-05 17:55:25 -0700468 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800469}
470
Josh Gao116aa0a2018-04-05 17:55:25 -0700471int adb_write(int fd, const void* buf, int len) {
472 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800473
474 if (f == NULL) {
475 return -1;
476 }
477
478 return f->clazz->_fh_write(f, buf, len);
479}
480
Josh Gao116aa0a2018-04-05 17:55:25 -0700481ssize_t adb_writev(int fd, const adb_iovec* iov, int iovcnt) {
482 FH f = _fh_from_int(fd, __func__);
483
484 if (f == NULL) {
485 errno = EBADF;
486 return -1;
487 }
488
489 return f->clazz->_fh_writev(f, iov, iovcnt);
490}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491
Josh Gao64a63ac2018-04-05 18:09:02 -0700492int adb_lseek(int fd, int pos, int where) {
493 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800494
495 if (!f) {
496 return -1;
497 }
498
499 return f->clazz->_fh_lseek(f, pos, where);
500}
501
Josh Gao64a63ac2018-04-05 18:09:02 -0700502int adb_close(int fd) {
503 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800504
505 if (!f) {
506 return -1;
507 }
508
Josh Gao64a63ac2018-04-05 18:09:02 -0700509 D("adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800510 _fh_close(f);
511 return 0;
512}
513
514/**************************************************************************/
515/**************************************************************************/
516/***** *****/
517/***** socket-based file descriptors *****/
518/***** *****/
519/**************************************************************************/
520/**************************************************************************/
521
Spencer Lowf055c192015-01-25 14:40:16 -0800522#undef setsockopt
523
Spencer Low5200c662015-07-30 23:07:55 -0700524static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700525 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
526 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gaoa3577e12016-12-05 13:24:48 -0800527 // are mapped to strings by adb_strerror().
Spencer Low5200c662015-07-30 23:07:55 -0700528 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800529 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700530 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
531 // case WSAEINTR: errno = EINTR; break;
532 case WSAEFAULT: errno = EFAULT; break;
533 case WSAEINVAL: errno = EINVAL; break;
534 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700535 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
536 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
537 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800538 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700539 case WSAENOTSOCK: errno = ENOTSOCK; break;
540 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
541 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
542 case WSAENETDOWN: errno = ENETDOWN; break;
543 case WSAENETRESET: errno = ENETRESET; break;
544 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
545 // to use EPIPE for these situations and there are some callers that look
546 // for EPIPE.
547 case WSAECONNABORTED: errno = EPIPE; break;
548 case WSAECONNRESET: errno = ECONNRESET; break;
549 case WSAENOBUFS: errno = ENOBUFS; break;
550 case WSAENOTCONN: errno = ENOTCONN; break;
551 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
552 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
553 // considerations: Reportedly send() can return zero on timeout, and POSIX
554 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
555 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
556 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700559 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700560 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561 }
562}
563
Josh Gao3777d2e2016-02-16 17:34:53 -0800564extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
565 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
566 int skipped = 0;
567 std::vector<WSAPOLLFD> sockets;
568 std::vector<adb_pollfd*> original;
Josh Gao05fb45b2018-03-29 12:34:28 -0700569
Josh Gao3777d2e2016-02-16 17:34:53 -0800570 for (size_t i = 0; i < nfds; ++i) {
571 FH fh = _fh_from_int(fds[i].fd, __func__);
572 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
573 D("adb_poll received bad FD %d", fds[i].fd);
574 fds[i].revents = POLLNVAL;
575 ++skipped;
576 } else {
577 WSAPOLLFD wsapollfd = {
578 .fd = fh->u.socket,
579 .events = static_cast<short>(fds[i].events)
580 };
581 sockets.push_back(wsapollfd);
582 original.push_back(&fds[i]);
583 }
Spencer Low5200c662015-07-30 23:07:55 -0700584 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800585
586 if (sockets.empty()) {
587 return skipped;
588 }
589
Josh Gao05fb45b2018-03-29 12:34:28 -0700590 // If we have any invalid FDs in our FD set, make sure to return immediately.
591 if (skipped > 0) {
592 timeout = 0;
593 }
594
Josh Gao3777d2e2016-02-16 17:34:53 -0800595 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
596 if (result == SOCKET_ERROR) {
597 _socket_set_errno(WSAGetLastError());
598 return -1;
599 }
600
601 // Map the results back onto the original set.
602 for (size_t i = 0; i < sockets.size(); ++i) {
603 original[i]->revents = sockets[i].revents;
604 }
605
Josh Gao05fb45b2018-03-29 12:34:28 -0700606 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gao3777d2e2016-02-16 17:34:53 -0800607 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
608 // to do. Ignore its result and calculate the proper return value.
609 result = 0;
610 for (size_t i = 0; i < nfds; ++i) {
611 if (fds[i].revents != 0) {
612 ++result;
613 }
614 }
615 return result;
616}
617
618static void _fh_socket_init(FH f) {
619 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620}
621
Josh Gao116aa0a2018-04-05 17:55:25 -0700622static int _fh_socket_close(FH f) {
Spencer Low5200c662015-07-30 23:07:55 -0700623 if (f->fh_socket != INVALID_SOCKET) {
624 /* gently tell any peer that we're closing the socket */
625 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
626 // If the socket is not connected, this returns an error. We want to
627 // minimize logging spam, so don't log these errors for now.
628#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700629 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800630 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700631#endif
632 }
633 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800634 // Don't set errno here, since adb_close will ignore it.
635 const DWORD err = WSAGetLastError();
636 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700637 }
638 f->fh_socket = INVALID_SOCKET;
639 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640 return 0;
641}
642
Josh Gao116aa0a2018-04-05 17:55:25 -0700643static int _fh_socket_lseek(FH f, int pos, int origin) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800644 errno = EPIPE;
645 return -1;
646}
647
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700648static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700649 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800650 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700651 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700652 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
653 // that to reduce spam and confusion.
654 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700655 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800656 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700657 }
Spencer Low5200c662015-07-30 23:07:55 -0700658 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800659 result = -1;
660 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700661 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800662}
663
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700664static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700665 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800666 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700667 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700668 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
669 // that to reduce spam and confusion.
670 if (err != WSAEWOULDBLOCK) {
671 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800672 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700673 }
Spencer Low5200c662015-07-30 23:07:55 -0700674 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800675 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700676 } else {
677 // According to https://code.google.com/p/chromium/issues/detail?id=27870
678 // Winsock Layered Service Providers may cause this.
Josh Gao116aa0a2018-04-05 17:55:25 -0700679 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
680 << result << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800681 }
682 return result;
683}
684
Josh Gao116aa0a2018-04-05 17:55:25 -0700685// Make sure that adb_iovec is compatible with WSABUF.
686static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
687static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
688static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
689
690static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
691static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
692
693static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
694 if (iovcnt <= 0) {
695 errno = EINVAL;
696 return -1;
697 }
698
699 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
700 DWORD bytes_written = 0;
701 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
702 if (result == SOCKET_ERROR) {
703 const DWORD err = WSAGetLastError();
704 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
705 // that to reduce spam and confusion.
706 if (err != WSAEWOULDBLOCK) {
707 D("send fd %d failed: %s", _fh_to_int(f),
708 android::base::SystemErrorCodeToString(err).c_str());
709 }
710 _socket_set_errno(err);
711 result = -1;
712 }
713 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
714 return static_cast<int>(bytes_written);
715}
716
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800717/**************************************************************************/
718/**************************************************************************/
719/***** *****/
720/***** replacement for libs/cutils/socket_xxxx.c *****/
721/***** *****/
722/**************************************************************************/
723/**************************************************************************/
724
725#include <winsock2.h>
726
727static int _winsock_init;
728
729static void
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800730_init_winsock( void )
731{
Spencer Low5200c662015-07-30 23:07:55 -0700732 // TODO: Multiple threads calling this may potentially cause multiple calls
Spencer Low87e97ee2015-08-12 18:19:16 -0700733 // to WSAStartup() which offers no real benefit.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734 if (!_winsock_init) {
735 WSADATA wsaData;
736 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
737 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800738 fatal("adb: could not initialize Winsock: %s",
739 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800740 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800741 _winsock_init = 1;
Spencer Low87e97ee2015-08-12 18:19:16 -0700742
743 // Note that we do not call atexit() to register WSACleanup to be called
744 // at normal process termination because:
745 // 1) When exit() is called, there are still threads actively using
746 // Winsock because we don't cleanly shutdown all threads, so it
747 // doesn't make sense to call WSACleanup() and may cause problems
748 // with those threads.
749 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
750 // calls WSACleanup() which tries to unload a DLL, which tries to
751 // grab the LoaderLock. This conflicts with the device_poll_thread
752 // which holds the LoaderLock because AdbWinApi.dll calls
753 // setupapi.dll which tries to load wintrust.dll which tries to load
754 // crypt32.dll which calls atexit() which tries to acquire the C
755 // Runtime lock that the other thread holds.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800756 }
757}
758
Spencer Low677fb432015-09-29 15:05:29 -0700759// Map a socket type to an explicit socket protocol instead of using the socket
760// protocol of 0. Explicit socket protocols are used by most apps and we should
761// do the same to reduce the chance of exercising uncommon code-paths that might
762// have problems or that might load different Winsock service providers that
763// have problems.
764static int GetSocketProtocolFromSocketType(int type) {
765 switch (type) {
766 case SOCK_STREAM:
767 return IPPROTO_TCP;
768 case SOCK_DGRAM:
769 return IPPROTO_UDP;
770 default:
771 LOG(FATAL) << "Unknown socket type: " << type;
772 return 0;
773 }
774}
775
Spencer Low5200c662015-07-30 23:07:55 -0700776int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800777 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800778 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800779
Josh Gao6487e742016-02-18 13:43:55 -0800780 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700781 if (!f) {
782 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800783 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700784 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800785
Josh Gao6487e742016-02-18 13:43:55 -0800786 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800787
788 memset(&addr, 0, sizeof(addr));
789 addr.sin_family = AF_INET;
790 addr.sin_port = htons(port);
791 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
792
Spencer Low677fb432015-09-29 15:05:29 -0700793 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800794 if (s == INVALID_SOCKET) {
795 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700796 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800797 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700798 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800799 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700800 return -1;
801 }
802 f->fh_socket = s;
803
Josh Gao6487e742016-02-18 13:43:55 -0800804 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700805 // Save err just in case inet_ntoa() or ntohs() changes the last error.
806 const DWORD err = WSAGetLastError();
807 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800808 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
809 android::base::SystemErrorCodeToString(err).c_str());
810 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
811 error->c_str());
812 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800813 return -1;
814 }
815
Spencer Low5200c662015-07-30 23:07:55 -0700816 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800817 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
818 port);
819 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700820 f.release();
821 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822}
823
Spencer Low5200c662015-07-30 23:07:55 -0700824// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800825static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800826 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800827 SOCKET s;
828 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800829
Josh Gao6487e742016-02-18 13:43:55 -0800830 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800831 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700832 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800833 return -1;
834 }
835
Josh Gao6487e742016-02-18 13:43:55 -0800836 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800837
838 memset(&addr, 0, sizeof(addr));
839 addr.sin_family = AF_INET;
840 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700841 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800842
Spencer Low5200c662015-07-30 23:07:55 -0700843 // TODO: Consider using dual-stack socket that can simultaneously listen on
844 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700845 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700846 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800847 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700848 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800849 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700850 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800851 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700852 return -1;
853 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800854
855 f->fh_socket = s;
856
Spencer Lowbf7c6052015-08-11 16:45:32 -0700857 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
858 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800860 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
861 const DWORD err = WSAGetLastError();
862 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
863 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700864 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800865 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700866 return -1;
867 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800868
Josh Gao6487e742016-02-18 13:43:55 -0800869 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700870 // Save err just in case inet_ntoa() or ntohs() changes the last error.
871 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800872 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
873 ntohs(addr.sin_port),
874 android::base::SystemErrorCodeToString(err).c_str());
875 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
876 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800877 return -1;
878 }
879 if (type == SOCK_STREAM) {
Josh Gaobf243a62018-03-20 14:25:03 -0700880 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800881 const DWORD err = WSAGetLastError();
882 *error = android::base::StringPrintf(
883 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
884 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
885 error->c_str());
886 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800887 return -1;
888 }
889 }
Spencer Low5200c662015-07-30 23:07:55 -0700890 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800891 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
892 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
893 port);
894 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700895 f.release();
896 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800897}
898
Spencer Low5200c662015-07-30 23:07:55 -0700899int network_loopback_server(int port, int type, std::string* error) {
900 return _network_server(port, type, INADDR_LOOPBACK, error);
901}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800902
Spencer Low5200c662015-07-30 23:07:55 -0700903int network_inaddr_any_server(int port, int type, std::string* error) {
904 return _network_server(port, type, INADDR_ANY, error);
905}
906
907int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
908 unique_fh f(_fh_alloc(&_fh_socket_class));
909 if (!f) {
910 *error = strerror(errno);
911 return -1;
912 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800913
Elliott Hughes381cfa92015-07-23 17:12:58 -0700914 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800915
Spencer Low5200c662015-07-30 23:07:55 -0700916 struct addrinfo hints;
917 memset(&hints, 0, sizeof(hints));
918 hints.ai_family = AF_UNSPEC;
919 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700920 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700921
922 char port_str[16];
923 snprintf(port_str, sizeof(port_str), "%d", port);
924
925 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700926
927#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800928// TODO: When the Android SDK tools increases the Windows system
929// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700930#else
Josh Gao6487e742016-02-18 13:43:55 -0800931// Otherwise, keep using getaddrinfo(), or do runtime API detection
932// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700933#endif
Spencer Low5200c662015-07-30 23:07:55 -0700934 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800935 const DWORD err = WSAGetLastError();
936 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
937 host.c_str(), port_str,
938 android::base::SystemErrorCodeToString(err).c_str());
939
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700940 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800941 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800942 return -1;
943 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700944 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700945 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800946
Spencer Low5200c662015-07-30 23:07:55 -0700947 // TODO: Try all the addresses if there's more than one? This just uses
948 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
949 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800950 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
951 if (s == INVALID_SOCKET) {
952 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700953 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800954 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700955 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800956 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800957 return -1;
958 }
959 f->fh_socket = s;
960
Spencer Low5200c662015-07-30 23:07:55 -0700961 // TODO: Implement timeouts for Windows. Seems like the default in theory
962 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800963 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700964 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800965 const DWORD err = WSAGetLastError();
966 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
967 android::base::SystemErrorCodeToString(err).c_str());
968 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
969 port_str, error->c_str());
970 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800971 return -1;
972 }
973
Spencer Low5200c662015-07-30 23:07:55 -0700974 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800975 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
976 port);
977 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
978 fd);
Spencer Low5200c662015-07-30 23:07:55 -0700979 f.release();
980 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800981}
982
Josh Gao64a63ac2018-04-05 18:09:02 -0700983int adb_register_socket(SOCKET s) {
984 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin2fe9b602016-09-21 14:03:39 -0700985 f->fh_socket = s;
986 return _fh_to_int(f);
987}
988
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800989#undef accept
Josh Gao64a63ac2018-04-05 18:09:02 -0700990int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t* addrlen) {
991 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200992
Josh Gao64a63ac2018-04-05 18:09:02 -0700993 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700994 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -0700995 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800996 return -1;
997 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200998
Josh Gao64a63ac2018-04-05 18:09:02 -0700999 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001000 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001001 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1002 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001003 return -1;
1004 }
1005
Josh Gao64a63ac2018-04-05 18:09:02 -07001006 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001008 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -07001009 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd
1010 << " failed: " + android::base::SystemErrorCodeToString(err);
1011 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001012 return -1;
1013 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001014
Spencer Low5200c662015-07-30 23:07:55 -07001015 const int fd = _fh_to_int(fh.get());
Josh Gao64a63ac2018-04-05 18:09:02 -07001016 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
1017 D("adb_socket_accept on fd %d returns fd %d", serverfd, fd);
Spencer Low5200c662015-07-30 23:07:55 -07001018 fh.release();
Josh Gao64a63ac2018-04-05 18:09:02 -07001019 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001020}
1021
Josh Gao64a63ac2018-04-05 18:09:02 -07001022int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) {
1023 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001024
Josh Gao64a63ac2018-04-05 18:09:02 -07001025 if (!fh || fh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001026 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001027 errno = EBADF;
1028 return -1;
1029 }
Spencer Low677fb432015-09-29 15:05:29 -07001030
1031 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1032 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1033 // auto-tuning.
1034
Josh Gao64a63ac2018-04-05 18:09:02 -07001035 int result =
1036 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1037 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001038 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -07001039 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd, level,
1040 optname, android::base::SystemErrorCodeToString(err).c_str());
1041 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -07001042 result = -1;
1043 }
1044 return result;
1045}
1046
Josh Gao3777d2e2016-02-16 17:34:53 -08001047int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1048 FH fh = _fh_from_int(fd, __func__);
1049
1050 if (!fh || fh->clazz != &_fh_socket_class) {
1051 D("adb_getsockname: invalid fd %d", fd);
1052 errno = EBADF;
1053 return -1;
1054 }
1055
Josh Gao3726a012017-03-30 13:04:35 -07001056 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001057 if (result == SOCKET_ERROR) {
1058 const DWORD err = WSAGetLastError();
1059 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1060 android::base::SystemErrorCodeToString(err).c_str());
1061 _socket_set_errno(err);
1062 result = -1;
1063 }
1064 return result;
1065}
Spencer Low5200c662015-07-30 23:07:55 -07001066
David Purselleaae97e2016-04-07 11:25:48 -07001067int adb_socket_get_local_port(int fd) {
1068 sockaddr_storage addr_storage;
1069 socklen_t addr_len = sizeof(addr_storage);
1070
1071 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1072 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1073 return -1;
1074 }
1075
1076 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1077 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1078 errno = ECONNABORTED;
1079 return -1;
1080 }
1081
1082 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1083}
1084
Josh Gao2e1e7892018-03-23 13:03:28 -07001085int adb_shutdown(int fd, int direction) {
1086 FH f = _fh_from_int(fd, __func__);
Spencer Low5200c662015-07-30 23:07:55 -07001087
1088 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001089 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001090 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001091 return -1;
1092 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001093
Josh Gao2e1e7892018-03-23 13:03:28 -07001094 D("adb_shutdown: %s", f->name);
1095 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001096 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001097 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001098 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001099 _socket_set_errno(err);
1100 return -1;
1101 }
1102 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001103}
1104
Josh Gao3777d2e2016-02-16 17:34:53 -08001105// Emulate socketpair(2) by binding and connecting to a socket.
1106int adb_socketpair(int sv[2]) {
1107 int server = -1;
1108 int client = -1;
1109 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001110 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001111 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001112
Josh Gao3777d2e2016-02-16 17:34:53 -08001113 server = network_loopback_server(0, SOCK_STREAM, &error);
1114 if (server < 0) {
1115 D("adb_socketpair: failed to create server: %s", error.c_str());
1116 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001117 }
1118
David Purselleaae97e2016-04-07 11:25:48 -07001119 local_port = adb_socket_get_local_port(server);
1120 if (local_port < 0) {
1121 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001122 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001123 }
David Purselleaae97e2016-04-07 11:25:48 -07001124 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001125
David Purselleaae97e2016-04-07 11:25:48 -07001126 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001127 if (client < 0) {
1128 D("adb_socketpair: failed to connect client: %s", error.c_str());
1129 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001130 }
1131
Josh Gao3726a012017-03-30 13:04:35 -07001132 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gao3777d2e2016-02-16 17:34:53 -08001133 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001134 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001135 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001136 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001137 adb_close(server);
1138 sv[0] = client;
1139 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001140 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001141
Josh Gao3777d2e2016-02-16 17:34:53 -08001142fail:
1143 if (server >= 0) {
1144 adb_close(server);
1145 }
1146 if (client >= 0) {
1147 adb_close(client);
1148 }
1149 if (accepted >= 0) {
1150 adb_close(accepted);
1151 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152 return -1;
1153}
1154
Josh Gao3777d2e2016-02-16 17:34:53 -08001155bool set_file_block_mode(int fd, bool block) {
1156 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001157
Josh Gao3777d2e2016-02-16 17:34:53 -08001158 if (!fh || !fh->used) {
1159 errno = EBADF;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001160 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001161 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001162 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001163
Josh Gao3777d2e2016-02-16 17:34:53 -08001164 if (fh->clazz == &_fh_socket_class) {
1165 u_long x = !block;
1166 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001167 int error = WSAGetLastError();
1168 _socket_set_errno(error);
1169 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001170 return false;
1171 }
1172 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001173 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001174 errno = ENOTSOCK;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001175 D("Setting nonblocking on non-socket %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001176 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001177 }
1178}
1179
David Pursellbfd95032016-02-22 14:27:23 -08001180bool set_tcp_keepalive(int fd, int interval_sec) {
1181 FH fh = _fh_from_int(fd, __func__);
1182
1183 if (!fh || fh->clazz != &_fh_socket_class) {
1184 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1185 errno = EBADF;
1186 return false;
1187 }
1188
1189 tcp_keepalive keepalive;
1190 keepalive.onoff = (interval_sec > 0);
1191 keepalive.keepalivetime = interval_sec * 1000;
1192 keepalive.keepaliveinterval = interval_sec * 1000;
1193
1194 DWORD bytes_returned = 0;
1195 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1196 &bytes_returned, nullptr, nullptr) != 0) {
1197 const DWORD err = WSAGetLastError();
1198 D("set_tcp_keepalive(%d) failed: %s", fd,
1199 android::base::SystemErrorCodeToString(err).c_str());
1200 _socket_set_errno(err);
1201 return false;
1202 }
1203
1204 return true;
1205}
1206
Spencer Low50184062015-03-01 15:06:21 -08001207/**************************************************************************/
1208/**************************************************************************/
1209/***** *****/
1210/***** Console Window Terminal Emulation *****/
1211/***** *****/
1212/**************************************************************************/
1213/**************************************************************************/
1214
1215// This reads input from a Win32 console window and translates it into Unix
1216// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1217// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1218// is emulated instead of xterm because it is probably more popular than xterm:
1219// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1220// supports modern fonts, etc. It seems best to emulate the terminal that most
1221// Android developers use because they'll fix apps (the shell, etc.) to keep
1222// working with that terminal's emulation.
1223//
1224// The point of this emulation is not to be perfect or to solve all issues with
1225// console windows on Windows, but to be better than the original code which
1226// just called read() (which called ReadFile(), which called ReadConsoleA())
1227// which did not support Ctrl-C, tab completion, shell input line editing
1228// keys, server echo, and more.
1229//
1230// This implementation reconfigures the console with SetConsoleMode(), then
1231// calls ReadConsoleInput() to get raw input which it remaps to Unix
1232// terminal-style sequences which is returned via unix_read() which is used
1233// by the 'adb shell' command.
1234//
1235// Code organization:
1236//
David Pursellc5b8ad82015-10-28 14:29:51 -07001237// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001238// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1239// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1240// * _console_read() is the main code of the emulation.
1241
David Pursellc5b8ad82015-10-28 14:29:51 -07001242// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1243// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1244// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1245static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1246 // First check isatty(); this is very fast and eliminates most non-console
1247 // FDs, but returns 1 for both consoles and character devices like NUL.
1248#pragma push_macro("isatty")
1249#undef isatty
1250 if (!isatty(fd)) {
1251 return nullptr;
1252 }
1253#pragma pop_macro("isatty")
1254
1255 // To differentiate between character devices and consoles we need to get
1256 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1257 // GENERIC_READ permissions.
1258 const intptr_t intptr_handle = _get_osfhandle(fd);
1259 if (intptr_handle == -1) {
1260 return nullptr;
1261 }
1262 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1263 DWORD temp_mode = 0;
1264 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1265 return nullptr;
1266 }
1267
1268 return handle;
1269}
1270
1271// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1272static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001273 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1274 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001275 const int fd = fileno(stream);
1276 if (fd < 0) {
1277 return nullptr;
1278 }
1279 return _get_console_handle(fd);
1280}
1281
1282int unix_isatty(int fd) {
1283 return _get_console_handle(fd) ? 1 : 0;
1284}
Spencer Low50184062015-03-01 15:06:21 -08001285
Spencer Low32762f42015-11-10 19:17:16 -08001286// Get the next KEY_EVENT_RECORD that should be processed.
1287static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001288 for (;;) {
1289 DWORD read_count = 0;
1290 memset(input_record, 0, sizeof(*input_record));
1291 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001292 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001293 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001294 errno = EIO;
1295 return false;
1296 }
1297
1298 if (read_count == 0) { // should be impossible
1299 fatal("ReadConsoleInputA returned 0");
1300 }
1301
1302 if (read_count != 1) { // should be impossible
1303 fatal("ReadConsoleInputA did not return one input record");
1304 }
1305
Spencer Low2e02dc62015-11-07 17:34:39 -08001306 // If the console window is resized, emulate SIGWINCH by breaking out
1307 // of read() with errno == EINTR. Note that there is no event on
1308 // vertical resize because we don't give the console our own custom
1309 // screen buffer (with CreateConsoleScreenBuffer() +
1310 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1311 // supports scrollback, but doesn't seem to raise an event for vertical
1312 // window resize.
1313 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1314 errno = EINTR;
1315 return false;
1316 }
1317
Spencer Low50184062015-03-01 15:06:21 -08001318 if ((input_record->EventType == KEY_EVENT) &&
1319 (input_record->Event.KeyEvent.bKeyDown)) {
1320 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1321 fatal("ReadConsoleInputA returned a key event with zero repeat"
1322 " count");
1323 }
1324
1325 // Got an interesting INPUT_RECORD, so return
1326 return true;
1327 }
1328 }
1329}
1330
Spencer Low50184062015-03-01 15:06:21 -08001331static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1332 return (control_key_state & SHIFT_PRESSED) != 0;
1333}
1334
1335static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1336 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1337}
1338
1339static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1340 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1341}
1342
1343static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1344 return (control_key_state & NUMLOCK_ON) != 0;
1345}
1346
1347static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1348 return (control_key_state & CAPSLOCK_ON) != 0;
1349}
1350
1351static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1352 return (control_key_state & ENHANCED_KEY) != 0;
1353}
1354
1355// Constants from MSDN for ToAscii().
1356static const BYTE TOASCII_KEY_OFF = 0x00;
1357static const BYTE TOASCII_KEY_DOWN = 0x80;
1358static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1359
1360// Given a key event, ignore a modifier key and return the character that was
1361// entered without the modifier. Writes to *ch and returns the number of bytes
1362// written.
1363static size_t _get_char_ignoring_modifier(char* const ch,
1364 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1365 const WORD modifier) {
1366 // If there is no character from Windows, try ignoring the specified
1367 // modifier and look for a character. Note that if AltGr is being used,
1368 // there will be a character from Windows.
1369 if (key_event->uChar.AsciiChar == '\0') {
1370 // Note that we read the control key state from the passed in argument
1371 // instead of from key_event since the argument has been normalized.
1372 if (((modifier == VK_SHIFT) &&
1373 _is_shift_pressed(control_key_state)) ||
1374 ((modifier == VK_CONTROL) &&
1375 _is_ctrl_pressed(control_key_state)) ||
1376 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1377
1378 BYTE key_state[256] = {0};
1379 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1380 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1381 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1382 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1383 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1384 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1385 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1386 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1387
1388 // cause this modifier to be ignored
1389 key_state[modifier] = TOASCII_KEY_OFF;
1390
1391 WORD translated = 0;
1392 if (ToAscii(key_event->wVirtualKeyCode,
1393 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1394 // Ignoring the modifier, we found a character.
1395 *ch = (CHAR)translated;
1396 return 1;
1397 }
1398 }
1399 }
1400
1401 // Just use whatever Windows told us originally.
1402 *ch = key_event->uChar.AsciiChar;
1403
1404 // If the character from Windows is NULL, return a size of zero.
1405 return (*ch == '\0') ? 0 : 1;
1406}
1407
1408// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1409// but taking into account the shift key. This is because for a sequence like
1410// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1411// we want to find the character ')'.
1412//
1413// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1414// because it is the default key-sequence to switch the input language.
1415// This is configurable in the Region and Language control panel.
1416static __inline__ size_t _get_non_control_char(char* const ch,
1417 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1418 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1419 VK_CONTROL);
1420}
1421
1422// Get without Alt.
1423static __inline__ size_t _get_non_alt_char(char* const ch,
1424 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1425 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1426 VK_MENU);
1427}
1428
1429// Ignore the control key, find the character from Windows, and apply any
1430// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1431// *pch and returns number of bytes written.
1432static size_t _get_control_character(char* const pch,
1433 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1434 const size_t len = _get_non_control_char(pch, key_event,
1435 control_key_state);
1436
1437 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1438 char ch = *pch;
1439 switch (ch) {
1440 case '2':
1441 case '@':
1442 case '`':
1443 ch = '\0';
1444 break;
1445 case '3':
1446 case '[':
1447 case '{':
1448 ch = '\x1b';
1449 break;
1450 case '4':
1451 case '\\':
1452 case '|':
1453 ch = '\x1c';
1454 break;
1455 case '5':
1456 case ']':
1457 case '}':
1458 ch = '\x1d';
1459 break;
1460 case '6':
1461 case '^':
1462 case '~':
1463 ch = '\x1e';
1464 break;
1465 case '7':
1466 case '-':
1467 case '_':
1468 ch = '\x1f';
1469 break;
1470 case '8':
1471 ch = '\x7f';
1472 break;
1473 case '/':
1474 if (!_is_alt_pressed(control_key_state)) {
1475 ch = '\x1f';
1476 }
1477 break;
1478 case '?':
1479 if (!_is_alt_pressed(control_key_state)) {
1480 ch = '\x7f';
1481 }
1482 break;
1483 }
1484 *pch = ch;
1485 }
1486
1487 return len;
1488}
1489
1490static DWORD _normalize_altgr_control_key_state(
1491 const KEY_EVENT_RECORD* const key_event) {
1492 DWORD control_key_state = key_event->dwControlKeyState;
1493
1494 // If we're in an AltGr situation where the AltGr key is down (depending on
1495 // the keyboard layout, that might be the physical right alt key which
1496 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1497 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1498 // a character (which indicates that there was an AltGr mapping), then act
1499 // as if alt and control are not really down for the purposes of modifiers.
1500 // This makes it so that if the user with, say, a German keyboard layout
1501 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1502 // output the key and we don't see the Alt and Ctrl keys.
1503 if (_is_ctrl_pressed(control_key_state) &&
1504 _is_alt_pressed(control_key_state)
1505 && (key_event->uChar.AsciiChar != '\0')) {
1506 // Try to remove as few bits as possible to improve our chances of
1507 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1508 // Left-Alt + Right-Ctrl + AltGr.
1509 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1510 // Remove Right-Alt.
1511 control_key_state &= ~RIGHT_ALT_PRESSED;
1512 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1513 // pressed, Left-Ctrl is almost always set, except if the user
1514 // presses Right-Ctrl, then AltGr (in that specific order) for
1515 // whatever reason. At any rate, make sure the bit is not set.
1516 control_key_state &= ~LEFT_CTRL_PRESSED;
1517 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1518 // Remove Left-Alt.
1519 control_key_state &= ~LEFT_ALT_PRESSED;
1520 // Whichever Ctrl key is down, remove it from the state. We only
1521 // remove one key, to improve our chances of detecting the
1522 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1523 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1524 // Remove Left-Ctrl.
1525 control_key_state &= ~LEFT_CTRL_PRESSED;
1526 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1527 // Remove Right-Ctrl.
1528 control_key_state &= ~RIGHT_CTRL_PRESSED;
1529 }
1530 }
1531
1532 // Note that this logic isn't 100% perfect because Windows doesn't
1533 // allow us to detect all combinations because a physical AltGr key
1534 // press shows up as two bits, plus some combinations are ambiguous
1535 // about what is actually physically pressed.
1536 }
1537
1538 return control_key_state;
1539}
1540
1541// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1542// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1543// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1544// appropriately.
1545static DWORD _normalize_keypad_control_key_state(const WORD vk,
1546 const DWORD control_key_state) {
1547 if (!_is_numlock_on(control_key_state)) {
1548 return control_key_state;
1549 }
1550 if (!_is_enhanced_key(control_key_state)) {
1551 switch (vk) {
1552 case VK_INSERT: // 0
1553 case VK_DELETE: // .
1554 case VK_END: // 1
1555 case VK_DOWN: // 2
1556 case VK_NEXT: // 3
1557 case VK_LEFT: // 4
1558 case VK_CLEAR: // 5
1559 case VK_RIGHT: // 6
1560 case VK_HOME: // 7
1561 case VK_UP: // 8
1562 case VK_PRIOR: // 9
1563 return control_key_state | SHIFT_PRESSED;
1564 }
1565 }
1566
1567 return control_key_state;
1568}
1569
1570static const char* _get_keypad_sequence(const DWORD control_key_state,
1571 const char* const normal, const char* const shifted) {
1572 if (_is_shift_pressed(control_key_state)) {
1573 // Shift is pressed and NumLock is off
1574 return shifted;
1575 } else {
1576 // Shift is not pressed and NumLock is off, or,
1577 // Shift is pressed and NumLock is on, in which case we want the
1578 // NumLock and Shift to neutralize each other, thus, we want the normal
1579 // sequence.
1580 return normal;
1581 }
1582 // If Shift is not pressed and NumLock is on, a different virtual key code
1583 // is returned by Windows, which can be taken care of by a different case
1584 // statement in _console_read().
1585}
1586
1587// Write sequence to buf and return the number of bytes written.
1588static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1589 DWORD control_key_state, const char* const normal) {
1590 // Copy the base sequence into buf.
1591 const size_t len = strlen(normal);
1592 memcpy(buf, normal, len);
1593
1594 int code = 0;
1595
1596 control_key_state = _normalize_keypad_control_key_state(vk,
1597 control_key_state);
1598
1599 if (_is_shift_pressed(control_key_state)) {
1600 code |= 0x1;
1601 }
1602 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1603 code |= 0x2;
1604 }
1605 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1606 code |= 0x4;
1607 }
1608 // If some modifier was held down, then we need to insert the modifier code
1609 if (code != 0) {
1610 if (len == 0) {
1611 // Should be impossible because caller should pass a string of
1612 // non-zero length.
1613 return 0;
1614 }
1615 size_t index = len - 1;
1616 const char lastChar = buf[index];
1617 if (lastChar != '~') {
1618 buf[index++] = '1';
1619 }
1620 buf[index++] = ';'; // modifier separator
1621 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1622 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1623 buf[index++] = '1' + code;
1624 buf[index++] = lastChar; // move ~ (or other last char) to the end
1625 return index;
1626 }
1627 return len;
1628}
1629
1630// Write sequence to buf and return the number of bytes written.
1631static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1632 const DWORD control_key_state, const char* const normal,
1633 const char shifted) {
1634 if (_is_shift_pressed(control_key_state)) {
1635 // Shift is pressed and NumLock is off
1636 if (shifted != '\0') {
1637 buf[0] = shifted;
1638 return sizeof(buf[0]);
1639 } else {
1640 return 0;
1641 }
1642 } else {
1643 // Shift is not pressed and NumLock is off, or,
1644 // Shift is pressed and NumLock is on, in which case we want the
1645 // NumLock and Shift to neutralize each other, thus, we want the normal
1646 // sequence.
1647 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1648 }
1649 // If Shift is not pressed and NumLock is on, a different virtual key code
1650 // is returned by Windows, which can be taken care of by a different case
1651 // statement in _console_read().
1652}
1653
1654// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1655// Standard German. Figure this out at runtime so we know what to output for
1656// Shift-VK_DELETE.
1657static char _get_decimal_char() {
1658 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1659}
1660
1661// Prefix the len bytes in buf with the escape character, and then return the
1662// new buffer length.
1663size_t _escape_prefix(char* const buf, const size_t len) {
1664 // If nothing to prefix, don't do anything. We might be called with
1665 // len == 0, if alt was held down with a dead key which produced nothing.
1666 if (len == 0) {
1667 return 0;
1668 }
1669
1670 memmove(&buf[1], buf, len);
1671 buf[0] = '\x1b';
1672 return len + 1;
1673}
1674
Spencer Low32762f42015-11-10 19:17:16 -08001675// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001676static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001677
1678// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1679// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001680static int _console_read(const HANDLE console, void* buf, size_t len) {
1681 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001682 // Read of zero bytes should not block waiting for something from the console.
1683 if (len == 0) {
1684 return 0;
1685 }
1686
1687 // Flush as much as possible from input buffer.
1688 if (!g_console_input_buffer.empty()) {
1689 const int bytes_read = std::min(len, g_console_input_buffer.size());
1690 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1691 const auto begin = g_console_input_buffer.begin();
1692 g_console_input_buffer.erase(begin, begin + bytes_read);
1693 return bytes_read;
1694 }
1695
1696 // Read from the actual console. This may block until input.
1697 INPUT_RECORD input_record;
1698 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001699 return -1;
1700 }
1701
Spencer Low32762f42015-11-10 19:17:16 -08001702 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001703 const WORD vk = key_event->wVirtualKeyCode;
1704 const CHAR ch = key_event->uChar.AsciiChar;
1705 const DWORD control_key_state = _normalize_altgr_control_key_state(
1706 key_event);
1707
1708 // The following emulation code should write the output sequence to
1709 // either seqstr or to seqbuf and seqbuflen.
1710 const char* seqstr = NULL; // NULL terminated C-string
1711 // Enough space for max sequence string below, plus modifiers and/or
1712 // escape prefix.
1713 char seqbuf[16];
1714 size_t seqbuflen = 0; // Space used in seqbuf.
1715
1716#define MATCH(vk, normal) \
1717 case (vk): \
1718 { \
1719 seqstr = (normal); \
1720 } \
1721 break;
1722
1723 // Modifier keys should affect the output sequence.
1724#define MATCH_MODIFIER(vk, normal) \
1725 case (vk): \
1726 { \
1727 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1728 control_key_state, (normal)); \
1729 } \
1730 break;
1731
1732 // The shift key should affect the output sequence.
1733#define MATCH_KEYPAD(vk, normal, shifted) \
1734 case (vk): \
1735 { \
1736 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1737 (shifted)); \
1738 } \
1739 break;
1740
1741 // The shift key and other modifier keys should affect the output
1742 // sequence.
1743#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1744 case (vk): \
1745 { \
1746 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1747 control_key_state, (normal), (shifted)); \
1748 } \
1749 break;
1750
1751#define ESC "\x1b"
1752#define CSI ESC "["
1753#define SS3 ESC "O"
1754
1755 // Only support normal mode, not application mode.
1756
1757 // Enhanced keys:
1758 // * 6-pack: insert, delete, home, end, page up, page down
1759 // * cursor keys: up, down, right, left
1760 // * keypad: divide, enter
1761 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1762 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1763 if (_is_enhanced_key(control_key_state)) {
1764 switch (vk) {
1765 case VK_RETURN: // Enter key on keypad
1766 if (_is_ctrl_pressed(control_key_state)) {
1767 seqstr = "\n";
1768 } else {
1769 seqstr = "\r";
1770 }
1771 break;
1772
1773 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1774 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1775
1776 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1777 // will be fixed soon to match xterm which sends CSI "F" and
1778 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1779 MATCH(VK_END, CSI "F");
1780 MATCH(VK_HOME, CSI "H");
1781
1782 MATCH_MODIFIER(VK_LEFT, CSI "D");
1783 MATCH_MODIFIER(VK_UP, CSI "A");
1784 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1785 MATCH_MODIFIER(VK_DOWN, CSI "B");
1786
1787 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1788 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1789
1790 MATCH(VK_DIVIDE, "/");
1791 }
1792 } else { // Non-enhanced keys:
1793 switch (vk) {
1794 case VK_BACK: // backspace
1795 if (_is_alt_pressed(control_key_state)) {
1796 seqstr = ESC "\x7f";
1797 } else {
1798 seqstr = "\x7f";
1799 }
1800 break;
1801
1802 case VK_TAB:
1803 if (_is_shift_pressed(control_key_state)) {
1804 seqstr = CSI "Z";
1805 } else {
1806 seqstr = "\t";
1807 }
1808 break;
1809
1810 // Number 5 key in keypad when NumLock is off, or if NumLock is
1811 // on and Shift is down.
1812 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1813
1814 case VK_RETURN: // Enter key on main keyboard
1815 if (_is_alt_pressed(control_key_state)) {
1816 seqstr = ESC "\n";
1817 } else if (_is_ctrl_pressed(control_key_state)) {
1818 seqstr = "\n";
1819 } else {
1820 seqstr = "\r";
1821 }
1822 break;
1823
1824 // VK_ESCAPE: Don't do any special handling. The OS uses many
1825 // of the sequences with Escape and many of the remaining
1826 // sequences don't produce bKeyDown messages, only !bKeyDown
1827 // for whatever reason.
1828
1829 case VK_SPACE:
1830 if (_is_alt_pressed(control_key_state)) {
1831 seqstr = ESC " ";
1832 } else if (_is_ctrl_pressed(control_key_state)) {
1833 seqbuf[0] = '\0'; // NULL char
1834 seqbuflen = 1;
1835 } else {
1836 seqstr = " ";
1837 }
1838 break;
1839
1840 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1841 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1842
1843 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1844 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1845
1846 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1847 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1848 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1849 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1850
1851 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1852 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1853 _get_decimal_char());
1854
1855 case 0x30: // 0
1856 case 0x31: // 1
1857 case 0x39: // 9
1858 case VK_OEM_1: // ;:
1859 case VK_OEM_PLUS: // =+
1860 case VK_OEM_COMMA: // ,<
1861 case VK_OEM_PERIOD: // .>
1862 case VK_OEM_7: // '"
1863 case VK_OEM_102: // depends on keyboard, could be <> or \|
1864 case VK_OEM_2: // /?
1865 case VK_OEM_3: // `~
1866 case VK_OEM_4: // [{
1867 case VK_OEM_5: // \|
1868 case VK_OEM_6: // ]}
1869 {
1870 seqbuflen = _get_control_character(seqbuf, key_event,
1871 control_key_state);
1872
1873 if (_is_alt_pressed(control_key_state)) {
1874 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1875 }
1876 }
1877 break;
1878
1879 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001880 case 0x33: // 3
1881 case 0x34: // 4
1882 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001883 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001884 case 0x37: // 7
1885 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001886 case VK_OEM_MINUS: // -_
1887 {
1888 seqbuflen = _get_control_character(seqbuf, key_event,
1889 control_key_state);
1890
1891 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1892 // prefix with escape.
1893 if (_is_alt_pressed(control_key_state) &&
1894 !(_is_ctrl_pressed(control_key_state) &&
1895 !_is_shift_pressed(control_key_state))) {
1896 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1897 }
1898 }
1899 break;
1900
Spencer Low50184062015-03-01 15:06:21 -08001901 case 0x41: // a
1902 case 0x42: // b
1903 case 0x43: // c
1904 case 0x44: // d
1905 case 0x45: // e
1906 case 0x46: // f
1907 case 0x47: // g
1908 case 0x48: // h
1909 case 0x49: // i
1910 case 0x4a: // j
1911 case 0x4b: // k
1912 case 0x4c: // l
1913 case 0x4d: // m
1914 case 0x4e: // n
1915 case 0x4f: // o
1916 case 0x50: // p
1917 case 0x51: // q
1918 case 0x52: // r
1919 case 0x53: // s
1920 case 0x54: // t
1921 case 0x55: // u
1922 case 0x56: // v
1923 case 0x57: // w
1924 case 0x58: // x
1925 case 0x59: // y
1926 case 0x5a: // z
1927 {
1928 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1929 control_key_state);
1930
1931 // If Alt is pressed, then prefix with escape.
1932 if (_is_alt_pressed(control_key_state)) {
1933 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1934 }
1935 }
1936 break;
1937
1938 // These virtual key codes are generated by the keys on the
1939 // keypad *when NumLock is on* and *Shift is up*.
1940 MATCH(VK_NUMPAD0, "0");
1941 MATCH(VK_NUMPAD1, "1");
1942 MATCH(VK_NUMPAD2, "2");
1943 MATCH(VK_NUMPAD3, "3");
1944 MATCH(VK_NUMPAD4, "4");
1945 MATCH(VK_NUMPAD5, "5");
1946 MATCH(VK_NUMPAD6, "6");
1947 MATCH(VK_NUMPAD7, "7");
1948 MATCH(VK_NUMPAD8, "8");
1949 MATCH(VK_NUMPAD9, "9");
1950
1951 MATCH(VK_MULTIPLY, "*");
1952 MATCH(VK_ADD, "+");
1953 MATCH(VK_SUBTRACT, "-");
1954 // VK_DECIMAL is generated by the . key on the keypad *when
1955 // NumLock is on* and *Shift is up* and the sequence is not
1956 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1957 // Windows Security screen to come up).
1958 case VK_DECIMAL:
1959 // U.S. English uses '.', Germany German uses ','.
1960 seqbuflen = _get_non_control_char(seqbuf, key_event,
1961 control_key_state);
1962 break;
1963
1964 MATCH_MODIFIER(VK_F1, SS3 "P");
1965 MATCH_MODIFIER(VK_F2, SS3 "Q");
1966 MATCH_MODIFIER(VK_F3, SS3 "R");
1967 MATCH_MODIFIER(VK_F4, SS3 "S");
1968 MATCH_MODIFIER(VK_F5, CSI "15~");
1969 MATCH_MODIFIER(VK_F6, CSI "17~");
1970 MATCH_MODIFIER(VK_F7, CSI "18~");
1971 MATCH_MODIFIER(VK_F8, CSI "19~");
1972 MATCH_MODIFIER(VK_F9, CSI "20~");
1973 MATCH_MODIFIER(VK_F10, CSI "21~");
1974 MATCH_MODIFIER(VK_F11, CSI "23~");
1975 MATCH_MODIFIER(VK_F12, CSI "24~");
1976
1977 MATCH_MODIFIER(VK_F13, CSI "25~");
1978 MATCH_MODIFIER(VK_F14, CSI "26~");
1979 MATCH_MODIFIER(VK_F15, CSI "28~");
1980 MATCH_MODIFIER(VK_F16, CSI "29~");
1981 MATCH_MODIFIER(VK_F17, CSI "31~");
1982 MATCH_MODIFIER(VK_F18, CSI "32~");
1983 MATCH_MODIFIER(VK_F19, CSI "33~");
1984 MATCH_MODIFIER(VK_F20, CSI "34~");
1985
1986 // MATCH_MODIFIER(VK_F21, ???);
1987 // MATCH_MODIFIER(VK_F22, ???);
1988 // MATCH_MODIFIER(VK_F23, ???);
1989 // MATCH_MODIFIER(VK_F24, ???);
1990 }
1991 }
1992
1993#undef MATCH
1994#undef MATCH_MODIFIER
1995#undef MATCH_KEYPAD
1996#undef MATCH_MODIFIER_KEYPAD
1997#undef ESC
1998#undef CSI
1999#undef SS3
2000
2001 const char* out;
2002 size_t outlen;
2003
2004 // Check for output in any of:
2005 // * seqstr is set (and strlen can be used to determine the length).
2006 // * seqbuf and seqbuflen are set
2007 // Fallback to ch from Windows.
2008 if (seqstr != NULL) {
2009 out = seqstr;
2010 outlen = strlen(seqstr);
2011 } else if (seqbuflen > 0) {
2012 out = seqbuf;
2013 outlen = seqbuflen;
2014 } else if (ch != '\0') {
2015 // Use whatever Windows told us it is.
2016 seqbuf[0] = ch;
2017 seqbuflen = 1;
2018 out = seqbuf;
2019 outlen = seqbuflen;
2020 } else {
2021 // No special handling for the virtual key code and Windows isn't
2022 // telling us a character code, then we don't know how to translate
2023 // the key press.
2024 //
2025 // Consume the input and 'continue' to cause us to get a new key
2026 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002027 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002028 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002029 continue;
2030 }
2031
Spencer Low32762f42015-11-10 19:17:16 -08002032 // put output wRepeatCount times into g_console_input_buffer
2033 while (key_event->wRepeatCount-- > 0) {
2034 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002035 }
2036
Spencer Low32762f42015-11-10 19:17:16 -08002037 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002038 }
2039}
2040
2041static DWORD _old_console_mode; // previous GetConsoleMode() result
2042static HANDLE _console_handle; // when set, console mode should be restored
2043
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002044void stdin_raw_init() {
2045 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002046 if (in == nullptr) {
2047 return;
2048 }
Spencer Low50184062015-03-01 15:06:21 -08002049
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002050 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2051 // calling the process Ctrl-C routine (configured by
2052 // SetConsoleCtrlHandler()).
2053 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2054 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2055 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002056 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2057 ENABLE_LINE_INPUT |
2058 ENABLE_ECHO_INPUT);
2059 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2060 new_console_mode |= ENABLE_WINDOW_INPUT;
2061
2062 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002063 // This really should not fail.
2064 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002065 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002066 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002067
2068 // Once this is set, it means that stdin has been configured for
2069 // reading from and that the old console mode should be restored later.
2070 _console_handle = in;
2071
2072 // Note that we don't need to configure C Runtime line-ending
2073 // translation because _console_read() does not call the C Runtime to
2074 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002075}
2076
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002077void stdin_raw_restore() {
2078 if (_console_handle != NULL) {
2079 const HANDLE in = _console_handle;
2080 _console_handle = NULL; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002081
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002082 if (!SetConsoleMode(in, _old_console_mode)) {
2083 // This really should not fail.
2084 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002085 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002086 }
2087 }
2088}
2089
Spencer Low2e02dc62015-11-07 17:34:39 -08002090// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2091int unix_read_interruptible(int fd, void* buf, size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08002092 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
2093 // If it is a request to read from stdin, and stdin_raw_init() has been
2094 // called, and it successfully configured the console, then read from
2095 // the console using Win32 console APIs and partially emulate a unix
2096 // terminal.
2097 return _console_read(_console_handle, buf, len);
2098 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002099 // On older versions of Windows (definitely 7, definitely not 10),
2100 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002101 // we need to limit the read size.
2102 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002103 len = 4096;
2104 }
Spencer Low50184062015-03-01 15:06:21 -08002105 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002106 // can do LF/CR translation (which is overridable with _setmode()).
2107 // Undefine the macro that is set in sysdeps.h which bans calls to
2108 // plain read() in favor of unix_read() or adb_read().
2109#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002110#undef read
2111 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002112#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002113 }
2114}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002115
2116/**************************************************************************/
2117/**************************************************************************/
2118/***** *****/
2119/***** Unicode support *****/
2120/***** *****/
2121/**************************************************************************/
2122/**************************************************************************/
2123
2124// This implements support for using files with Unicode filenames and for
2125// outputting Unicode text to a Win32 console window. This is inspired from
2126// http://utf8everywhere.org/.
2127//
2128// Background
2129// ----------
2130//
2131// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2132// filenames to APIs such as open(). This works because filenames are largely
2133// opaque 'cookies' (perhaps excluding path separators).
2134//
2135// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2136// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2137// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2138// CreateFile() API is really just a macro that adds the W/A based on whether
2139// the UNICODE preprocessor symbol is defined).
2140//
2141// Options
2142// -------
2143//
2144// Thus, to write a portable program, there are a few options:
2145//
2146// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2147// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2148// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2149// open() API.
2150//
2151// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2152// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2153// potentially touching a lot of code.
2154//
2155// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2156// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2157// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2158// or C Runtime API.
2159//
2160// The Choice
2161// ----------
2162//
Spencer Lowd21dc822015-11-12 15:20:15 -08002163// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2164// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002165// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002166// args that are passed to main() at the beginning of program startup. We also use
2167// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002168// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2169//
2170// Unicode console output
2171// ----------------------
2172//
2173// The way to output Unicode to a Win32 console window is to call
2174// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002175// such as Lucida Console or Consolas, and in the case of East Asian languages
2176// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2177// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2178// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002179//
2180// The problem is getting the C Runtime to make fprintf and related APIs call
2181// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2182// promising, but the various modes have issues:
2183//
2184// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2185// UTF-16 do not display properly.
2186// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2187// totally wrong.
2188// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2189// handler to be called (upon a later I/O call), aborting the process.
2190// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2191// to output nothing.
2192//
2193// So the only solution is to write our own adb_fprintf() that converts UTF-8
2194// to UTF-16 and then calls WriteConsoleW().
2195
2196
Spencer Lowcf4ff642015-05-11 01:08:48 -07002197// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2198// be passed to main().
2199NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2200 narrow_args = new char*[argc + 1];
2201
2202 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002203 std::string arg_narrow;
2204 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2205 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2206 }
2207 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002208 }
2209 narrow_args[argc] = nullptr; // terminate
2210}
2211
2212NarrowArgs::~NarrowArgs() {
2213 if (narrow_args != nullptr) {
2214 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2215 free(*argp);
2216 }
2217 delete[] narrow_args;
2218 narrow_args = nullptr;
2219 }
2220}
2221
2222int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002223 std::wstring path_wide;
2224 if (!android::base::UTF8ToWide(path, &path_wide)) {
2225 return -1;
2226 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002227 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002228 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002229 } else {
2230 int mode;
2231 va_list args;
2232 va_start(args, options);
2233 mode = va_arg(args, int);
2234 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002235 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002236 }
2237}
2238
Spencer Lowcf4ff642015-05-11 01:08:48 -07002239// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002240DIR* adb_opendir(const char* path) {
2241 std::wstring path_wide;
2242 if (!android::base::UTF8ToWide(path, &path_wide)) {
2243 return nullptr;
2244 }
2245
Spencer Lowcf4ff642015-05-11 01:08:48 -07002246 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2247 // the fields, but right now all the callers treat the structure as
2248 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002249 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002250}
2251
2252// Version of readdir() that returns UTF-8 paths.
2253struct dirent* adb_readdir(DIR* dir) {
2254 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2255 struct _wdirent* const went = _wreaddir(wdir);
2256 if (went == nullptr) {
2257 return nullptr;
2258 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002259
Spencer Lowcf4ff642015-05-11 01:08:48 -07002260 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002261 std::string name_utf8;
2262 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2263 return nullptr;
2264 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002265
2266 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2267 // space for UTF-16 wchar_t's) with UTF-8 char's.
2268 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2269
2270 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2271 // Name too big to fit in existing buffer.
2272 errno = ENOMEM;
2273 return nullptr;
2274 }
2275
2276 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2277 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2278 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2279 // bigger than the caller expects because they expect a dirent structure
2280 // which has a smaller d_name field. Ignore this since the caller should be
2281 // resilient.
2282
2283 // Rewrite the UTF-16 d_name field to UTF-8.
2284 strcpy(ent->d_name, name_utf8.c_str());
2285
2286 return ent;
2287}
2288
2289// Version of closedir() to go with our version of adb_opendir().
2290int adb_closedir(DIR* dir) {
2291 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2292}
2293
2294// Version of unlink() that takes a UTF-8 path.
2295int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002296 std::wstring wpath;
2297 if (!android::base::UTF8ToWide(path, &wpath)) {
2298 return -1;
2299 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002300
2301 int rc = _wunlink(wpath.c_str());
2302
2303 if (rc == -1 && errno == EACCES) {
2304 /* unlink returns EACCES when the file is read-only, so we first */
2305 /* try to make it writable, then unlink again... */
2306 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2307 if (rc == 0)
2308 rc = _wunlink(wpath.c_str());
2309 }
2310 return rc;
2311}
2312
2313// Version of mkdir() that takes a UTF-8 path.
2314int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002315 std::wstring path_wide;
2316 if (!android::base::UTF8ToWide(path, &path_wide)) {
2317 return -1;
2318 }
2319
2320 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002321}
2322
2323// Version of utime() that takes a UTF-8 path.
2324int adb_utime(const char* path, struct utimbuf* u) {
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
Spencer Lowcf4ff642015-05-11 01:08:48 -07002330 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2331 "utimbuf and _utimbuf should be the same size because they both "
2332 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002333 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002334}
2335
2336// Version of chmod() that takes a UTF-8 path.
2337int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002338 std::wstring path_wide;
2339 if (!android::base::UTF8ToWide(path, &path_wide)) {
2340 return -1;
2341 }
2342
2343 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002344}
2345
Spencer Lowa30b79a2015-11-15 16:29:36 -08002346// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2347static inline size_t utf8_codepoint_len(uint8_t ch) {
2348 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2349}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002350
Spencer Lowa30b79a2015-11-15 16:29:36 -08002351namespace internal {
2352
2353// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2354// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2355// remaining_bytes.
2356size_t ParseCompleteUTF8(const char* const first, const char* const last,
2357 std::vector<char>* const remaining_bytes) {
2358 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2359 // Current_after points one byte past the current byte to be examined.
2360 for (const char* current_after = last; current_after != first; --current_after) {
2361 const char* const current = current_after - 1;
2362 const char ch = *current;
2363 const char kHighBit = 0x80u;
2364 const char kTwoHighestBits = 0xC0u;
2365 if ((ch & kHighBit) == 0) { // high bit not set
2366 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2367 // bytes with no leading byte, so return the entire buffer.
2368 break;
2369 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2370 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2371 const size_t bytes_available = last - current;
2372 if (bytes_available < utf8_codepoint_len(ch)) {
2373 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2374 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2375 // to remaining_bytes.
2376 remaining_bytes->insert(remaining_bytes->end(), current, last);
2377 return current - first;
2378 } else {
2379 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2380 // trailing bytes with no lead byte, so return the entire buffer.
2381 break;
2382 }
2383 } else {
2384 // Trailing byte, so keep going backwards looking for the lead byte.
2385 }
2386 }
2387
2388 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2389 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2390 // so that they can be processed.
2391 return last - first;
2392}
2393
2394}
2395
2396// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2397// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2398// This matches the behavior of Linux.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002399
2400// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2401static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2402 HANDLE console) {
Josh Gao0cd3ae12016-09-21 12:37:10 -07002403 static std::mutex& console_output_buffer_lock = *new std::mutex();
2404 static auto& console_output_buffer = *new std::vector<char>();
2405
Spencer Lowa30b79a2015-11-15 16:29:36 -08002406 const int saved_errno = errno;
2407 std::vector<char> combined_buffer;
2408
2409 // Complete UTF-8 sequences that should be immediately written to the console.
2410 const char* utf8;
2411 size_t utf8_size;
2412
Josh Gao0cd3ae12016-09-21 12:37:10 -07002413 {
2414 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2415 if (console_output_buffer.empty()) {
2416 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2417 // common case with plain ASCII), parse buf directly.
2418 utf8 = buf;
2419 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2420 } else {
2421 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2422 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2423 // combined_buffer, then parse it all together.
2424 combined_buffer.swap(console_output_buffer);
2425 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002426
Josh Gao0cd3ae12016-09-21 12:37:10 -07002427 utf8 = combined_buffer.data();
2428 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2429 &console_output_buffer);
2430 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002431 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002432
2433 std::wstring utf16;
2434
2435 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2436 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2437 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002438 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002439 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002440
2441 // Note that this does not do \n => \r\n translation because that
2442 // doesn't seem necessary for the Windows console. For the Windows
2443 // console \r moves to the beginning of the line and \n moves to a new
2444 // line.
2445
2446 // Flush any stream buffering so that our output is afterwards which
2447 // makes sense because our call is afterwards.
2448 (void)fflush(stream);
2449
2450 // Write UTF-16 to the console.
2451 DWORD written = 0;
Spencer Lowa30b79a2015-11-15 16:29:36 -08002452 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002453 errno = EIO;
2454 return -1;
2455 }
2456
Spencer Lowa30b79a2015-11-15 16:29:36 -08002457 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2458 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2459 // matches the Linux behavior.
2460 errno = saved_errno;
2461 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002462}
2463
2464// Function prototype because attributes cannot be placed on func definitions.
2465static int _console_vfprintf(const HANDLE console, FILE* stream,
2466 const char *format, va_list ap)
2467 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0)));
2468
2469// Internal function to format a UTF-8 string and write it to a Win32 console.
2470// Returns -1 on error.
2471static int _console_vfprintf(const HANDLE console, FILE* stream,
2472 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002473 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002474 std::string output_utf8;
2475
2476 // Format the string.
2477 // This could throw std::bad_alloc.
2478 android::base::StringAppendV(&output_utf8, format, ap);
2479
Spencer Lowa30b79a2015-11-15 16:29:36 -08002480 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2481 console);
2482 if (result != -1) {
2483 errno = saved_errno;
2484 } else {
2485 // If -1 was returned, errno has been set.
2486 }
2487 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002488}
2489
2490// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2491// Windows console.
2492int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2493 const HANDLE console = _get_console_handle(stream);
2494
2495 // If there is an associated Win32 console, write to it specially,
2496 // otherwise defer to the regular C Runtime, passing it UTF-8.
2497 if (console != NULL) {
2498 return _console_vfprintf(console, stream, format, ap);
2499 } else {
2500 // If vfprintf is a macro, undefine it, so we can call the real
2501 // C Runtime API.
2502#pragma push_macro("vfprintf")
2503#undef vfprintf
2504 return vfprintf(stream, format, ap);
2505#pragma pop_macro("vfprintf")
2506 }
2507}
2508
Spencer Lowa30b79a2015-11-15 16:29:36 -08002509// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2510int adb_vprintf(const char *format, va_list ap) {
2511 return adb_vfprintf(stdout, format, ap);
2512}
2513
Spencer Lowcf4ff642015-05-11 01:08:48 -07002514// Version of fprintf() that takes UTF-8 and can write Unicode to a
2515// Windows console.
2516int adb_fprintf(FILE *stream, const char *format, ...) {
2517 va_list ap;
2518 va_start(ap, format);
2519 const int result = adb_vfprintf(stream, format, ap);
2520 va_end(ap);
2521
2522 return result;
2523}
2524
2525// Version of printf() that takes UTF-8 and can write Unicode to a
2526// Windows console.
2527int adb_printf(const char *format, ...) {
2528 va_list ap;
2529 va_start(ap, format);
2530 const int result = adb_vfprintf(stdout, format, ap);
2531 va_end(ap);
2532
2533 return result;
2534}
2535
2536// Version of fputs() that takes UTF-8 and can write Unicode to a
2537// Windows console.
2538int adb_fputs(const char* buf, FILE* stream) {
2539 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2540 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002541 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002542 return adb_fprintf(stream, "%s", buf);
2543}
2544
2545// Version of fputc() that takes UTF-8 and can write Unicode to a
2546// Windows console.
2547int adb_fputc(int ch, FILE* stream) {
2548 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002549 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002550 return EOF;
2551 }
2552 // For success, fputc returns the char, cast to unsigned char, then to int.
2553 return static_cast<unsigned char>(ch);
2554}
2555
Spencer Lowa30b79a2015-11-15 16:29:36 -08002556// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2557int adb_putchar(int ch) {
2558 return adb_fputc(ch, stdout);
2559}
2560
2561// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2562int adb_puts(const char* buf) {
2563 // adb_printf returns -1 on error, which is conveniently the same as EOF
2564 // which puts (and hence adb_puts) should return on error.
2565 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2566 return adb_printf("%s\n", buf);
2567}
2568
Spencer Lowcf4ff642015-05-11 01:08:48 -07002569// Internal function to write UTF-8 to a Win32 console. Returns the number of
2570// items (of length size) written. On error, returns a short item count or 0.
2571static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2572 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002573 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2574 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002575 if (result == -1) {
2576 return 0;
2577 }
2578 return result / size;
2579}
2580
2581// Version of fwrite() that takes UTF-8 and can write Unicode to a
2582// Windows console.
2583size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2584 const HANDLE console = _get_console_handle(stream);
2585
2586 // If there is an associated Win32 console, write to it specially,
2587 // otherwise defer to the regular C Runtime, passing it UTF-8.
2588 if (console != NULL) {
2589 return _console_fwrite(ptr, size, nmemb, stream, console);
2590 } else {
2591 // If fwrite is a macro, undefine it, so we can call the real
2592 // C Runtime API.
2593#pragma push_macro("fwrite")
2594#undef fwrite
2595 return fwrite(ptr, size, nmemb, stream);
2596#pragma pop_macro("fwrite")
2597 }
2598}
2599
2600// Version of fopen() that takes a UTF-8 filename and can access a file with
2601// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002602FILE* adb_fopen(const char* path, const char* mode) {
2603 std::wstring path_wide;
2604 if (!android::base::UTF8ToWide(path, &path_wide)) {
2605 return nullptr;
2606 }
2607
2608 std::wstring mode_wide;
2609 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2610 return nullptr;
2611 }
2612
2613 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002614}
2615
Spencer Lowe6ae5732015-09-08 17:13:04 -07002616// Return a lowercase version of the argument. Uses C Runtime tolower() on
2617// each byte which is not UTF-8 aware, and theoretically uses the current C
2618// Runtime locale (which in practice is not changed, so this becomes a ASCII
2619// conversion).
2620static std::string ToLower(const std::string& anycase) {
2621 // copy string
2622 std::string str(anycase);
2623 // transform the copy
2624 std::transform(str.begin(), str.end(), str.begin(), tolower);
2625 return str;
2626}
2627
2628extern "C" int main(int argc, char** argv);
2629
2630// Link with -municode to cause this wmain() to be used as the program
2631// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2632// regular main() with UTF-8 args.
2633extern "C" int wmain(int argc, wchar_t **argv) {
2634 // Convert args from UTF-16 to UTF-8 and pass that to main().
2635 NarrowArgs narrow_args(argc, argv);
2636 return main(argc, narrow_args.data());
2637}
2638
Spencer Lowcf4ff642015-05-11 01:08:48 -07002639// Shadow UTF-8 environment variable name/value pairs that are created from
2640// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002641// currently updated if putenv, setenv, unsetenv are called. Note that no
2642// thread synchronization is done, but we're called early enough in
2643// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002644static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002645
2646// Make sure that shadow UTF-8 environment variables are setup.
2647static void _ensure_env_setup() {
2648 // If some name/value pairs exist, then we've already done the setup below.
2649 if (g_environ_utf8.size() != 0) {
2650 return;
2651 }
2652
Spencer Lowe6ae5732015-09-08 17:13:04 -07002653 if (_wenviron == nullptr) {
2654 // If _wenviron is null, then -municode probably wasn't used. That
2655 // linker flag will cause the entry point to setup _wenviron. It will
2656 // also require an implementation of wmain() (which we provide above).
2657 fatal("_wenviron is not set, did you link with -municode?");
2658 }
2659
Spencer Lowcf4ff642015-05-11 01:08:48 -07002660 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2661 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2662 // to use the D() macro here because that tracing only works if the
2663 // ADB_TRACE environment variable is setup, but that env var can't be read
2664 // until this code completes.
2665 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2666 wchar_t* const equal = wcschr(*env, L'=');
2667 if (equal == nullptr) {
2668 // Malformed environment variable with no equal sign. Shouldn't
2669 // really happen, but we should be resilient to this.
2670 continue;
2671 }
2672
Spencer Lowd21dc822015-11-12 15:20:15 -08002673 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2674 // var because the program might never even read this particular variable.
2675 std::string name_utf8;
2676 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2677 continue;
2678 }
2679
Spencer Lowe6ae5732015-09-08 17:13:04 -07002680 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002681 name_utf8 = ToLower(name_utf8);
2682
2683 std::string value_utf8;
2684 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2685 continue;
2686 }
2687
2688 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002689
Spencer Lowe6ae5732015-09-08 17:13:04 -07002690 // Don't overwrite a previus env var with the same name. In reality,
2691 // the system probably won't let two env vars with the same name exist
2692 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002693 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002694 }
2695}
2696
2697// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002698// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002699char* adb_getenv(const char* name) {
2700 _ensure_env_setup();
2701
Spencer Lowe6ae5732015-09-08 17:13:04 -07002702 // Case-insensitive search by searching for lowercase name in a map of
2703 // lowercase names.
2704 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002705 if (it == g_environ_utf8.end()) {
2706 return nullptr;
2707 }
2708
2709 return it->second;
2710}
2711
2712// Version of getcwd() that returns the current working directory in UTF-8.
2713char* adb_getcwd(char* buf, int size) {
2714 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2715 if (wbuf == nullptr) {
2716 return nullptr;
2717 }
2718
Spencer Lowd21dc822015-11-12 15:20:15 -08002719 std::string buf_utf8;
2720 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002721 free(wbuf);
2722 wbuf = nullptr;
2723
Spencer Lowd21dc822015-11-12 15:20:15 -08002724 if (!narrow_result) {
2725 return nullptr;
2726 }
2727
Spencer Lowcf4ff642015-05-11 01:08:48 -07002728 // If size was specified, make sure all the chars will fit.
2729 if (size != 0) {
2730 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2731 errno = ERANGE;
2732 return nullptr;
2733 }
2734 }
2735
2736 // If buf was not specified, allocate storage.
2737 if (buf == nullptr) {
2738 if (size == 0) {
2739 size = buf_utf8.length() + 1;
2740 }
2741 buf = reinterpret_cast<char*>(malloc(size));
2742 if (buf == nullptr) {
2743 return nullptr;
2744 }
2745 }
2746
2747 // Destination buffer was allocated with enough space, or we've already
2748 // checked an existing buffer size for enough space.
2749 strcpy(buf, buf_utf8.c_str());
2750
2751 return buf;
2752}