blob: dc2525c5368221938cc6abb3ace3948f41a55066 [file] [log] [blame]
Dan Albertdb6fe642015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albertdb6fe642015-03-19 15:21:08 -070018
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albertdb6fe642015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hinesb1170852014-10-01 17:37:06 -070022#include <windows.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris054d1702014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albertdb6fe642015-03-19 15:21:08 -070027
Spencer Low50740f52015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low753d4852015-07-30 23:07:55 -070029#include <memory>
Josh Gaoe7daf572016-09-21 12:37:10 -070030#include <mutex>
Spencer Low753d4852015-07-30 23:07:55 -070031#include <string>
Josh Gaof0c44032018-12-12 16:12:28 -080032#include <string_view>
Spencer Low6815c072015-05-11 01:08:48 -070033#include <unordered_map>
Josh Gaoe7388122016-02-16 17:34:53 -080034#include <vector>
Spencer Low753d4852015-07-30 23:07:55 -070035
Elliott Hughesfe447512015-07-24 11:35:40 -070036#include <cutils/sockets.h>
37
David Pursellc573d522016-01-27 08:52:53 -080038#include <android-base/errors.h>
Elliott Hughese64126b2018-10-19 13:59:44 -070039#include <android-base/file.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080040#include <android-base/logging.h>
Josh Gao1bbdd252018-04-05 17:55:25 -070041#include <android-base/macros.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080042#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
44#include <android-base/utf8.h>
Spencer Low753d4852015-07-30 23:07:55 -070045
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080046#include "adb.h"
Josh Gaoe7388122016-02-16 17:34:53 -080047#include "adb_utils.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080048
Josh Gao1bbdd252018-04-05 17:55:25 -070049#include "sysdeps/uio.h"
50
Elliott Hughes6a096932015-04-16 16:47:02 -070051/* forward declarations */
52
53typedef const struct FHClassRec_* FHClass;
54typedef struct FHRec_* FH;
Elliott Hughes6a096932015-04-16 16:47:02 -070055
56typedef struct FHClassRec_ {
57 void (*_fh_init)(FH);
58 int (*_fh_close)(FH);
Elliott Hughes9dcbc212018-09-20 13:59:49 -070059 int64_t (*_fh_lseek)(FH, int64_t, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070060 int (*_fh_read)(FH, void*, int);
61 int (*_fh_write)(FH, const void*, int);
Josh Gao1bbdd252018-04-05 17:55:25 -070062 int (*_fh_writev)(FH, const adb_iovec*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070063} FHClassRec;
64
65static void _fh_file_init(FH);
66static int _fh_file_close(FH);
Elliott Hughes9dcbc212018-09-20 13:59:49 -070067static int64_t _fh_file_lseek(FH, int64_t, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070068static int _fh_file_read(FH, void*, int);
69static int _fh_file_write(FH, const void*, int);
Josh Gao1bbdd252018-04-05 17:55:25 -070070static int _fh_file_writev(FH, const adb_iovec*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070071
72static const FHClassRec _fh_file_class = {
73 _fh_file_init,
74 _fh_file_close,
75 _fh_file_lseek,
76 _fh_file_read,
77 _fh_file_write,
Josh Gao1bbdd252018-04-05 17:55:25 -070078 _fh_file_writev,
Elliott Hughes6a096932015-04-16 16:47:02 -070079};
80
81static void _fh_socket_init(FH);
82static int _fh_socket_close(FH);
Elliott Hughes9dcbc212018-09-20 13:59:49 -070083static int64_t _fh_socket_lseek(FH, int64_t, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070084static int _fh_socket_read(FH, void*, int);
85static int _fh_socket_write(FH, const void*, int);
Josh Gao1bbdd252018-04-05 17:55:25 -070086static int _fh_socket_writev(FH, const adb_iovec*, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070087
88static const FHClassRec _fh_socket_class = {
89 _fh_socket_init,
90 _fh_socket_close,
91 _fh_socket_lseek,
92 _fh_socket_read,
93 _fh_socket_write,
Josh Gao1bbdd252018-04-05 17:55:25 -070094 _fh_socket_writev,
Elliott Hughes6a096932015-04-16 16:47:02 -070095};
96
Pirama Arumuga Nainar5231aff2018-08-08 10:33:24 -070097#if defined(assert)
98#undef assert
99#endif
100
Spencer Low2bbb3a92015-08-26 18:46:09 -0700101void handle_deleter::operator()(HANDLE h) {
102 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
103 // implying that NULL is a valid handle, but this is probably impossible.
104 // Other APIs like CreateEvent() are documented to return NULL on error,
105 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
106 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
107 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
108 // only need to check for INVALID_HANDLE_VALUE.
109 if (h != INVALID_HANDLE_VALUE) {
110 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700111 D("CloseHandle(%p) failed: %s", h,
David Pursellc573d522016-01-27 08:52:53 -0800112 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2bbb3a92015-08-26 18:46:09 -0700113 }
114 }
115}
116
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800117/**************************************************************************/
118/**************************************************************************/
119/***** *****/
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800120/***** common file descriptor handling *****/
121/***** *****/
122/**************************************************************************/
123/**************************************************************************/
124
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800125typedef struct FHRec_
126{
127 FHClass clazz;
128 int used;
129 int eof;
130 union {
131 HANDLE handle;
132 SOCKET socket;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800133 } u;
134
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800135 char name[32];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800136} FHRec;
137
138#define fh_handle u.handle
139#define fh_socket u.socket
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800140
Josh Gao4f657a72016-02-17 16:45:39 -0800141#define WIN32_FH_BASE 2048
Josh Gao7c9e5fb2016-04-18 11:09:28 -0700142#define WIN32_MAX_FHS 2048
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800143
Josh Gaoe7daf572016-09-21 12:37:10 -0700144static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800145static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700146static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800147
Josh Gao90228a62019-04-25 14:04:57 -0700148static FH _fh_from_int(borrowed_fd bfd, const char* func) {
149 FH f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800150
Josh Gao90228a62019-04-25 14:04:57 -0700151 int fd = bfd.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800152 fd -= WIN32_FH_BASE;
153
Spencer Lowb732a372015-07-24 15:38:19 -0700154 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Josh Gao90228a62019-04-25 14:04:57 -0700155 D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800156 errno = EBADF;
Yi Kong86e67182018-07-13 18:15:16 -0700157 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800158 }
159
160 f = &_win32_fhs[fd];
161
162 if (f->used == 0) {
Josh Gao90228a62019-04-25 14:04:57 -0700163 D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800164 errno = EBADF;
Yi Kong86e67182018-07-13 18:15:16 -0700165 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800166 }
167
168 return f;
169}
170
Josh Gao90228a62019-04-25 14:04:57 -0700171static int _fh_to_int(FH f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800172 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
173 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
174
175 return -1;
176}
177
Josh Gao90228a62019-04-25 14:04:57 -0700178static FH _fh_alloc(FHClass clazz) {
179 FH f = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800180
Josh Gaoe7daf572016-09-21 12:37:10 -0700181 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800182
Josh Gao4f657a72016-02-17 16:45:39 -0800183 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
Yi Kong86e67182018-07-13 18:15:16 -0700184 if (_win32_fhs[i].clazz == nullptr) {
Josh Gao4f657a72016-02-17 16:45:39 -0800185 f = &_win32_fhs[i];
186 _win32_fh_next = i + 1;
Josh Gaoe7daf572016-09-21 12:37:10 -0700187 f->clazz = clazz;
188 f->used = 1;
189 f->eof = 0;
190 f->name[0] = '\0';
191 clazz->_fh_init(f);
192 return f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800193 }
194 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700195
196 D("_fh_alloc: no more free file descriptors");
197 errno = EMFILE; // Too many open files
198 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800199}
200
Josh Gao90228a62019-04-25 14:04:57 -0700201static int _fh_close(FH f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700202 // Use lock so that closing only happens once and so that _fh_alloc can't
203 // allocate a FH that we're in the middle of closing.
Josh Gaoe7daf572016-09-21 12:37:10 -0700204 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gao4f657a72016-02-17 16:45:39 -0800205
206 int offset = f - _win32_fhs;
207 if (_win32_fh_next > offset) {
208 _win32_fh_next = offset;
209 }
210
Spencer Lowb732a372015-07-24 15:38:19 -0700211 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800212 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700213 f->name[0] = '\0';
214 f->eof = 0;
215 f->used = 0;
Yi Kong86e67182018-07-13 18:15:16 -0700216 f->clazz = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800217 }
218 return 0;
219}
220
Spencer Low753d4852015-07-30 23:07:55 -0700221// Deleter for unique_fh.
222class fh_deleter {
223 public:
224 void operator()(struct FHRec_* fh) {
225 // We're called from a destructor and destructors should not overwrite
226 // errno because callers may do:
227 // errno = EBLAH;
228 // return -1; // calls destructor, which should not overwrite errno
229 const int saved_errno = errno;
230 _fh_close(fh);
231 errno = saved_errno;
232 }
233};
234
235// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
236typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
237
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800238/**************************************************************************/
239/**************************************************************************/
240/***** *****/
241/***** file-based descriptor handling *****/
242/***** *****/
243/**************************************************************************/
244/**************************************************************************/
245
Josh Gao1bbdd252018-04-05 17:55:25 -0700246static void _fh_file_init(FH f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800247 f->fh_handle = INVALID_HANDLE_VALUE;
248}
249
Josh Gao1bbdd252018-04-05 17:55:25 -0700250static int _fh_file_close(FH f) {
251 CloseHandle(f->fh_handle);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800252 f->fh_handle = INVALID_HANDLE_VALUE;
253 return 0;
254}
255
Josh Gao1bbdd252018-04-05 17:55:25 -0700256static int _fh_file_read(FH f, void* buf, int len) {
257 DWORD read_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800258
Yi Kong86e67182018-07-13 18:15:16 -0700259 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700260 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800261 errno = EIO;
262 return -1;
263 } else if (read_bytes < (DWORD)len) {
264 f->eof = 1;
265 }
Josh Gao1bbdd252018-04-05 17:55:25 -0700266 return read_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800267}
268
Josh Gao1bbdd252018-04-05 17:55:25 -0700269static int _fh_file_write(FH f, const void* buf, int len) {
270 DWORD wrote_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800271
Yi Kong86e67182018-07-13 18:15:16 -0700272 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700273 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800274 errno = EIO;
275 return -1;
276 } else if (wrote_bytes < (DWORD)len) {
277 f->eof = 1;
278 }
Josh Gao1bbdd252018-04-05 17:55:25 -0700279 return wrote_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800280}
281
Josh Gao1bbdd252018-04-05 17:55:25 -0700282static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
283 if (iovcnt <= 0) {
284 errno = EINVAL;
285 return -1;
286 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800287
Josh Gao1bbdd252018-04-05 17:55:25 -0700288 DWORD wrote_bytes = 0;
289
290 for (int i = 0; i < iovcnt; ++i) {
291 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
292 if (rc == -1) {
293 return wrote_bytes > 0 ? wrote_bytes : -1;
294 } else if (rc == 0) {
295 return wrote_bytes;
296 }
297
298 wrote_bytes += rc;
299
300 if (static_cast<size_t>(rc) < iov[i].iov_len) {
301 return wrote_bytes;
302 }
303 }
304
305 return wrote_bytes;
306}
307
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700308static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700309 DWORD method;
Josh Gao1bbdd252018-04-05 17:55:25 -0700310 switch (origin) {
311 case SEEK_SET:
312 method = FILE_BEGIN;
313 break;
314 case SEEK_CUR:
315 method = FILE_CURRENT;
316 break;
317 case SEEK_END:
318 method = FILE_END;
319 break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800320 default:
321 errno = EINVAL;
322 return -1;
323 }
324
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700325 LARGE_INTEGER li = {.QuadPart = pos};
326 if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800327 errno = EIO;
328 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800329 }
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700330 f->eof = 0;
331 return li.QuadPart;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800332}
333
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800334/**************************************************************************/
335/**************************************************************************/
336/***** *****/
337/***** file-based descriptor handling *****/
338/***** *****/
339/**************************************************************************/
340/**************************************************************************/
341
Josh Gao08229f62018-04-05 18:09:02 -0700342int adb_open(const char* path, int options) {
343 FH f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800344
Josh Gao08229f62018-04-05 18:09:02 -0700345 DWORD desiredAccess = 0;
346 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800347
Josh Gao3befb592019-02-07 14:13:39 -0800348 // CreateFileW is inherently O_CLOEXEC by default.
349 options &= ~O_CLOEXEC;
350
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800351 switch (options) {
352 case O_RDONLY:
353 desiredAccess = GENERIC_READ;
354 break;
355 case O_WRONLY:
356 desiredAccess = GENERIC_WRITE;
357 break;
358 case O_RDWR:
359 desiredAccess = GENERIC_READ | GENERIC_WRITE;
360 break;
361 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700362 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800363 errno = EINVAL;
364 return -1;
365 }
366
Josh Gao08229f62018-04-05 18:09:02 -0700367 f = _fh_alloc(&_fh_file_class);
368 if (!f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800369 return -1;
370 }
371
Spencer Low50f5bf12015-11-12 15:20:15 -0800372 std::wstring path_wide;
373 if (!android::base::UTF8ToWide(path, &path_wide)) {
374 return -1;
375 }
Josh Gao08229f62018-04-05 18:09:02 -0700376 f->fh_handle =
Yi Kong86e67182018-07-13 18:15:16 -0700377 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800378
Josh Gao08229f62018-04-05 18:09:02 -0700379 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700380 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800381 _fh_close(f);
Josh Gao08229f62018-04-05 18:09:02 -0700382 D("adb_open: could not open '%s': ", path);
Spencer Low5c761bd2015-07-21 02:06:26 -0700383 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800384 case ERROR_FILE_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700385 D("file not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800386 errno = ENOENT;
387 return -1;
388
389 case ERROR_PATH_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700390 D("path not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800391 errno = ENOTDIR;
392 return -1;
393
394 default:
David Pursellc573d522016-01-27 08:52:53 -0800395 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800396 errno = ENOENT;
397 return -1;
398 }
399 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800400
Josh Gao08229f62018-04-05 18:09:02 -0700401 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
402 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800403 return _fh_to_int(f);
404}
405
406/* ignore mode on Win32 */
Josh Gao08229f62018-04-05 18:09:02 -0700407int adb_creat(const char* path, int mode) {
408 FH f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800409
Josh Gao08229f62018-04-05 18:09:02 -0700410 f = _fh_alloc(&_fh_file_class);
411 if (!f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800412 return -1;
413 }
414
Spencer Low50f5bf12015-11-12 15:20:15 -0800415 std::wstring path_wide;
416 if (!android::base::UTF8ToWide(path, &path_wide)) {
417 return -1;
418 }
Josh Gao08229f62018-04-05 18:09:02 -0700419 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
Yi Kong86e67182018-07-13 18:15:16 -0700420 nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800421
Josh Gao08229f62018-04-05 18:09:02 -0700422 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700423 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800424 _fh_close(f);
Josh Gao08229f62018-04-05 18:09:02 -0700425 D("adb_creat: could not open '%s': ", path);
Spencer Low5c761bd2015-07-21 02:06:26 -0700426 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800427 case ERROR_FILE_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700428 D("file not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800429 errno = ENOENT;
430 return -1;
431
432 case ERROR_PATH_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700433 D("path not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800434 errno = ENOTDIR;
435 return -1;
436
437 default:
David Pursellc573d522016-01-27 08:52:53 -0800438 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800439 errno = ENOENT;
440 return -1;
441 }
442 }
Josh Gao08229f62018-04-05 18:09:02 -0700443 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
444 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800445 return _fh_to_int(f);
446}
447
Josh Gao90228a62019-04-25 14:04:57 -0700448int adb_read(borrowed_fd fd, void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700449 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800450
Yi Kong86e67182018-07-13 18:15:16 -0700451 if (f == nullptr) {
Josh Gaode165962018-04-05 18:09:39 -0700452 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800453 return -1;
454 }
455
Josh Gao1bbdd252018-04-05 17:55:25 -0700456 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800457}
458
Josh Gao90228a62019-04-25 14:04:57 -0700459int adb_write(borrowed_fd fd, const void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700460 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800461
Yi Kong86e67182018-07-13 18:15:16 -0700462 if (f == nullptr) {
Josh Gaode165962018-04-05 18:09:39 -0700463 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800464 return -1;
465 }
466
467 return f->clazz->_fh_write(f, buf, len);
468}
469
Josh Gao90228a62019-04-25 14:04:57 -0700470ssize_t adb_writev(borrowed_fd fd, const adb_iovec* iov, int iovcnt) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700471 FH f = _fh_from_int(fd, __func__);
472
Yi Kong86e67182018-07-13 18:15:16 -0700473 if (f == nullptr) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700474 errno = EBADF;
475 return -1;
476 }
477
478 return f->clazz->_fh_writev(f, iov, iovcnt);
479}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800480
Josh Gao90228a62019-04-25 14:04:57 -0700481int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where) {
Josh Gao08229f62018-04-05 18:09:02 -0700482 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483 if (!f) {
Josh Gaode165962018-04-05 18:09:39 -0700484 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800485 return -1;
486 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800487 return f->clazz->_fh_lseek(f, pos, where);
488}
489
Josh Gao08229f62018-04-05 18:09:02 -0700490int adb_close(int fd) {
491 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800492
493 if (!f) {
Josh Gaode165962018-04-05 18:09:39 -0700494 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800495 return -1;
496 }
497
Josh Gao08229f62018-04-05 18:09:02 -0700498 D("adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800499 _fh_close(f);
500 return 0;
501}
502
503/**************************************************************************/
504/**************************************************************************/
505/***** *****/
506/***** socket-based file descriptors *****/
507/***** *****/
508/**************************************************************************/
509/**************************************************************************/
510
Spencer Low31aafa62015-01-25 14:40:16 -0800511#undef setsockopt
512
Spencer Low753d4852015-07-30 23:07:55 -0700513static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700514 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
515 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gao75e96bb2016-12-05 13:24:48 -0800516 // are mapped to strings by adb_strerror().
Spencer Low753d4852015-07-30 23:07:55 -0700517 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800518 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700519 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
520 // case WSAEINTR: errno = EINTR; break;
521 case WSAEFAULT: errno = EFAULT; break;
522 case WSAEINVAL: errno = EINVAL; break;
523 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700524 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
525 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
526 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800527 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700528 case WSAENOTSOCK: errno = ENOTSOCK; break;
529 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
530 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
531 case WSAENETDOWN: errno = ENETDOWN; break;
532 case WSAENETRESET: errno = ENETRESET; break;
533 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
534 // to use EPIPE for these situations and there are some callers that look
535 // for EPIPE.
536 case WSAECONNABORTED: errno = EPIPE; break;
537 case WSAECONNRESET: errno = ECONNRESET; break;
538 case WSAENOBUFS: errno = ENOBUFS; break;
539 case WSAENOTCONN: errno = ENOTCONN; break;
540 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
541 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
542 // considerations: Reportedly send() can return zero on timeout, and POSIX
543 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
544 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
545 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800546 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800547 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700548 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700549 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800550 }
551}
552
Josh Gaoe7388122016-02-16 17:34:53 -0800553extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
554 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
555 int skipped = 0;
556 std::vector<WSAPOLLFD> sockets;
557 std::vector<adb_pollfd*> original;
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700558
Josh Gaoe7388122016-02-16 17:34:53 -0800559 for (size_t i = 0; i < nfds; ++i) {
560 FH fh = _fh_from_int(fds[i].fd, __func__);
561 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
562 D("adb_poll received bad FD %d", fds[i].fd);
563 fds[i].revents = POLLNVAL;
564 ++skipped;
565 } else {
566 WSAPOLLFD wsapollfd = {
567 .fd = fh->u.socket,
568 .events = static_cast<short>(fds[i].events)
569 };
570 sockets.push_back(wsapollfd);
571 original.push_back(&fds[i]);
572 }
Spencer Low753d4852015-07-30 23:07:55 -0700573 }
Josh Gaoe7388122016-02-16 17:34:53 -0800574
575 if (sockets.empty()) {
576 return skipped;
577 }
578
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700579 // If we have any invalid FDs in our FD set, make sure to return immediately.
580 if (skipped > 0) {
581 timeout = 0;
582 }
583
Josh Gaoe7388122016-02-16 17:34:53 -0800584 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
585 if (result == SOCKET_ERROR) {
586 _socket_set_errno(WSAGetLastError());
587 return -1;
588 }
589
590 // Map the results back onto the original set.
591 for (size_t i = 0; i < sockets.size(); ++i) {
592 original[i]->revents = sockets[i].revents;
593 }
594
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700595 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gaoe7388122016-02-16 17:34:53 -0800596 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
597 // to do. Ignore its result and calculate the proper return value.
598 result = 0;
599 for (size_t i = 0; i < nfds; ++i) {
600 if (fds[i].revents != 0) {
601 ++result;
602 }
603 }
604 return result;
605}
606
607static void _fh_socket_init(FH f) {
608 f->fh_socket = INVALID_SOCKET;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800609}
610
Josh Gao1bbdd252018-04-05 17:55:25 -0700611static int _fh_socket_close(FH f) {
Spencer Low753d4852015-07-30 23:07:55 -0700612 if (f->fh_socket != INVALID_SOCKET) {
Spencer Low753d4852015-07-30 23:07:55 -0700613 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800614 // Don't set errno here, since adb_close will ignore it.
615 const DWORD err = WSAGetLastError();
616 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700617 }
618 f->fh_socket = INVALID_SOCKET;
619 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800620 return 0;
621}
622
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700623static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800624 errno = EPIPE;
625 return -1;
626}
627
Elliott Hughes6a096932015-04-16 16:47:02 -0700628static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700629 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800630 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700631 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700632 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
633 // that to reduce spam and confusion.
634 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700635 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800636 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low32625852015-08-11 16:45:32 -0700637 }
Spencer Low753d4852015-07-30 23:07:55 -0700638 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639 result = -1;
640 }
Josh Gao1bbdd252018-04-05 17:55:25 -0700641 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800642}
643
Elliott Hughes6a096932015-04-16 16:47:02 -0700644static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700645 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800646 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700647 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700648 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
649 // that to reduce spam and confusion.
650 if (err != WSAEWOULDBLOCK) {
651 D("send fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800652 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low028e1592015-10-18 16:45:09 -0700653 }
Spencer Low753d4852015-07-30 23:07:55 -0700654 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800655 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700656 } else {
657 // According to https://code.google.com/p/chromium/issues/detail?id=27870
658 // Winsock Layered Service Providers may cause this.
Josh Gao1bbdd252018-04-05 17:55:25 -0700659 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
660 << result << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800661 }
662 return result;
663}
664
Josh Gao1bbdd252018-04-05 17:55:25 -0700665// Make sure that adb_iovec is compatible with WSABUF.
666static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
667static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
668static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
669
670static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
671static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
672
673static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
674 if (iovcnt <= 0) {
675 errno = EINVAL;
676 return -1;
677 }
678
679 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
680 DWORD bytes_written = 0;
681 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
682 if (result == SOCKET_ERROR) {
683 const DWORD err = WSAGetLastError();
684 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
685 // that to reduce spam and confusion.
686 if (err != WSAEWOULDBLOCK) {
687 D("send fd %d failed: %s", _fh_to_int(f),
688 android::base::SystemErrorCodeToString(err).c_str());
689 }
690 _socket_set_errno(err);
Josh Gaoee977a32019-08-07 18:26:47 -0700691 return -1;
Josh Gao1bbdd252018-04-05 17:55:25 -0700692 }
693 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
694 return static_cast<int>(bytes_written);
695}
696
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800697/**************************************************************************/
698/**************************************************************************/
699/***** *****/
700/***** replacement for libs/cutils/socket_xxxx.c *****/
701/***** *****/
702/**************************************************************************/
703/**************************************************************************/
704
Spencer Lowa0903682018-08-10 16:20:57 -0700705static void _init_winsock() {
Josh Gaocaeda2c2018-04-05 18:10:03 -0700706 static std::once_flag once;
707 std::call_once(once, []() {
708 WSADATA wsaData;
709 int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800710 if (rc != 0) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700711 LOG(FATAL) << "could not initialize Winsock: "
712 << android::base::SystemErrorCodeToString(rc);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800713 }
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700714
715 // Note that we do not call atexit() to register WSACleanup to be called
716 // at normal process termination because:
717 // 1) When exit() is called, there are still threads actively using
718 // Winsock because we don't cleanly shutdown all threads, so it
719 // doesn't make sense to call WSACleanup() and may cause problems
720 // with those threads.
721 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
722 // calls WSACleanup() which tries to unload a DLL, which tries to
723 // grab the LoaderLock. This conflicts with the device_poll_thread
724 // which holds the LoaderLock because AdbWinApi.dll calls
725 // setupapi.dll which tries to load wintrust.dll which tries to load
726 // crypt32.dll which calls atexit() which tries to acquire the C
727 // Runtime lock that the other thread holds.
Josh Gaocaeda2c2018-04-05 18:10:03 -0700728 });
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800729}
730
Spencer Lowc7c45612015-09-29 15:05:29 -0700731// Map a socket type to an explicit socket protocol instead of using the socket
732// protocol of 0. Explicit socket protocols are used by most apps and we should
733// do the same to reduce the chance of exercising uncommon code-paths that might
734// have problems or that might load different Winsock service providers that
735// have problems.
736static int GetSocketProtocolFromSocketType(int type) {
737 switch (type) {
738 case SOCK_STREAM:
739 return IPPROTO_TCP;
740 case SOCK_DGRAM:
741 return IPPROTO_UDP;
742 default:
743 LOG(FATAL) << "Unknown socket type: " << type;
744 return 0;
745 }
746}
747
Spencer Low753d4852015-07-30 23:07:55 -0700748int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800749 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800750 SOCKET s;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800751
Josh Gao61eda8d2016-02-18 13:43:55 -0800752 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low753d4852015-07-30 23:07:55 -0700753 if (!f) {
754 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800755 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700756 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800757
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800758 memset(&addr, 0, sizeof(addr));
759 addr.sin_family = AF_INET;
760 addr.sin_port = htons(port);
761 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
762
Spencer Lowc7c45612015-09-29 15:05:29 -0700763 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao61eda8d2016-02-18 13:43:55 -0800764 if (s == INVALID_SOCKET) {
765 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700766 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800767 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700768 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800769 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700770 return -1;
771 }
772 f->fh_socket = s;
773
Josh Gao61eda8d2016-02-18 13:43:55 -0800774 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700775 // Save err just in case inet_ntoa() or ntohs() changes the last error.
776 const DWORD err = WSAGetLastError();
777 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800778 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
779 android::base::SystemErrorCodeToString(err).c_str());
780 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
781 error->c_str());
782 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800783 return -1;
784 }
785
Spencer Low753d4852015-07-30 23:07:55 -0700786 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800787 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
788 port);
789 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700790 f.release();
791 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800792}
793
Spencer Low753d4852015-07-30 23:07:55 -0700794// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao61eda8d2016-02-18 13:43:55 -0800795static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800796 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800797 SOCKET s;
798 int n;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800799
Josh Gao61eda8d2016-02-18 13:43:55 -0800800 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800801 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700802 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800803 return -1;
804 }
805
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800806 memset(&addr, 0, sizeof(addr));
807 addr.sin_family = AF_INET;
808 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700809 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800810
Spencer Low753d4852015-07-30 23:07:55 -0700811 // TODO: Consider using dual-stack socket that can simultaneously listen on
812 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700813 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700814 if (s == INVALID_SOCKET) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800815 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700816 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800817 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700818 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800819 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700820 return -1;
821 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800822
823 f->fh_socket = s;
824
Spencer Low32625852015-08-11 16:45:32 -0700825 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
826 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800827 n = 1;
Josh Gao61eda8d2016-02-18 13:43:55 -0800828 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
829 const DWORD err = WSAGetLastError();
830 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
831 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700832 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800833 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700834 return -1;
835 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800836
Josh Gao61eda8d2016-02-18 13:43:55 -0800837 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700838 // Save err just in case inet_ntoa() or ntohs() changes the last error.
839 const DWORD err = WSAGetLastError();
Josh Gao61eda8d2016-02-18 13:43:55 -0800840 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
841 ntohs(addr.sin_port),
842 android::base::SystemErrorCodeToString(err).c_str());
843 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
844 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800845 return -1;
846 }
847 if (type == SOCK_STREAM) {
Josh Gaoa076b152018-03-20 14:25:03 -0700848 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800849 const DWORD err = WSAGetLastError();
850 *error = android::base::StringPrintf(
851 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
852 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
853 error->c_str());
854 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800855 return -1;
856 }
857 }
Spencer Low753d4852015-07-30 23:07:55 -0700858 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800859 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
860 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
861 port);
862 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700863 f.release();
864 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800865}
866
Spencer Low753d4852015-07-30 23:07:55 -0700867int network_loopback_server(int port, int type, std::string* error) {
868 return _network_server(port, type, INADDR_LOOPBACK, error);
869}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800870
Spencer Low753d4852015-07-30 23:07:55 -0700871int network_inaddr_any_server(int port, int type, std::string* error) {
872 return _network_server(port, type, INADDR_ANY, error);
873}
874
875int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
876 unique_fh f(_fh_alloc(&_fh_socket_class));
877 if (!f) {
878 *error = strerror(errno);
879 return -1;
880 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800881
Spencer Low753d4852015-07-30 23:07:55 -0700882 struct addrinfo hints;
883 memset(&hints, 0, sizeof(hints));
884 hints.ai_family = AF_UNSPEC;
885 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700886 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700887
888 char port_str[16];
889 snprintf(port_str, sizeof(port_str), "%d", port);
890
891 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700892
893#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao61eda8d2016-02-18 13:43:55 -0800894// TODO: When the Android SDK tools increases the Windows system
895// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700896#else
Josh Gao61eda8d2016-02-18 13:43:55 -0800897// Otherwise, keep using getaddrinfo(), or do runtime API detection
898// with GetProcAddress("GetAddrInfoW").
Spencer Lowcc467f12015-08-02 18:13:54 -0700899#endif
Spencer Low753d4852015-07-30 23:07:55 -0700900 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800901 const DWORD err = WSAGetLastError();
902 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
903 host.c_str(), port_str,
904 android::base::SystemErrorCodeToString(err).c_str());
905
Yabin Cui815ad882015-09-02 17:44:28 -0700906 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800907 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800908 return -1;
909 }
Elliott Hughes8ac45992016-08-08 12:52:37 -0700910 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low753d4852015-07-30 23:07:55 -0700911 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800912
Spencer Low753d4852015-07-30 23:07:55 -0700913 // TODO: Try all the addresses if there's more than one? This just uses
914 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
915 // which tries all addresses, takes a timeout and more.
Josh Gao61eda8d2016-02-18 13:43:55 -0800916 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
917 if (s == INVALID_SOCKET) {
918 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700919 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800920 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700921 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800922 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800923 return -1;
924 }
925 f->fh_socket = s;
926
Spencer Low753d4852015-07-30 23:07:55 -0700927 // TODO: Implement timeouts for Windows. Seems like the default in theory
928 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao61eda8d2016-02-18 13:43:55 -0800929 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700930 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao61eda8d2016-02-18 13:43:55 -0800931 const DWORD err = WSAGetLastError();
932 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
933 android::base::SystemErrorCodeToString(err).c_str());
934 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
935 port_str, error->c_str());
936 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800937 return -1;
938 }
939
Spencer Low753d4852015-07-30 23:07:55 -0700940 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800941 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
942 port);
943 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
944 fd);
Spencer Low753d4852015-07-30 23:07:55 -0700945 f.release();
946 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800947}
948
Josh Gao08229f62018-04-05 18:09:02 -0700949int adb_register_socket(SOCKET s) {
950 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin20238f22016-09-21 14:03:39 -0700951 f->fh_socket = s;
952 return _fh_to_int(f);
953}
954
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800955#undef accept
Josh Gao90228a62019-04-25 14:04:57 -0700956int adb_socket_accept(borrowed_fd serverfd, struct sockaddr* addr, socklen_t* addrlen) {
Josh Gao08229f62018-04-05 18:09:02 -0700957 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200958
Josh Gao08229f62018-04-05 18:09:02 -0700959 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -0700960 D("adb_socket_accept: invalid fd %d", serverfd.get());
Spencer Low753d4852015-07-30 23:07:55 -0700961 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800962 return -1;
963 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200964
Josh Gao08229f62018-04-05 18:09:02 -0700965 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800966 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -0700967 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
968 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800969 return -1;
970 }
971
Josh Gao08229f62018-04-05 18:09:02 -0700972 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800973 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700974 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -0700975 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd.get()
Josh Gao08229f62018-04-05 18:09:02 -0700976 << " failed: " + android::base::SystemErrorCodeToString(err);
977 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800978 return -1;
979 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200980
Spencer Low753d4852015-07-30 23:07:55 -0700981 const int fd = _fh_to_int(fh.get());
Josh Gao08229f62018-04-05 18:09:02 -0700982 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
Josh Gao90228a62019-04-25 14:04:57 -0700983 D("adb_socket_accept on fd %d returns fd %d", serverfd.get(), fd);
Spencer Low753d4852015-07-30 23:07:55 -0700984 fh.release();
Josh Gao08229f62018-04-05 18:09:02 -0700985 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800986}
987
Josh Gao90228a62019-04-25 14:04:57 -0700988int adb_setsockopt(borrowed_fd fd, int level, int optname, const void* optval, socklen_t optlen) {
Josh Gao08229f62018-04-05 18:09:02 -0700989 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800990
Josh Gao08229f62018-04-05 18:09:02 -0700991 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -0700992 D("adb_setsockopt: invalid fd %d", fd.get());
Spencer Low753d4852015-07-30 23:07:55 -0700993 errno = EBADF;
994 return -1;
995 }
Spencer Lowc7c45612015-09-29 15:05:29 -0700996
997 // TODO: Once we can assume Windows Vista or later, if the caller is trying
998 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
999 // auto-tuning.
1000
Josh Gao08229f62018-04-05 18:09:02 -07001001 int result =
1002 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1003 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -07001004 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001005 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd.get(), level,
Josh Gao08229f62018-04-05 18:09:02 -07001006 optname, android::base::SystemErrorCodeToString(err).c_str());
1007 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -07001008 result = -1;
1009 }
1010 return result;
1011}
1012
Josh Gao90228a62019-04-25 14:04:57 -07001013static int adb_getsockname(borrowed_fd fd, struct sockaddr* sockaddr, socklen_t* optlen) {
Josh Gaoe7388122016-02-16 17:34:53 -08001014 FH fh = _fh_from_int(fd, __func__);
1015
1016 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001017 D("adb_getsockname: invalid fd %d", fd.get());
Josh Gaoe7388122016-02-16 17:34:53 -08001018 errno = EBADF;
1019 return -1;
1020 }
1021
Josh Gao4f6f4422017-03-30 13:04:35 -07001022 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gaoe7388122016-02-16 17:34:53 -08001023 if (result == SOCKET_ERROR) {
1024 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001025 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd.get(),
Josh Gaoe7388122016-02-16 17:34:53 -08001026 android::base::SystemErrorCodeToString(err).c_str());
1027 _socket_set_errno(err);
1028 result = -1;
1029 }
1030 return result;
1031}
Spencer Low753d4852015-07-30 23:07:55 -07001032
Josh Gao90228a62019-04-25 14:04:57 -07001033int adb_socket_get_local_port(borrowed_fd fd) {
David Pursell19d0c232016-04-07 11:25:48 -07001034 sockaddr_storage addr_storage;
1035 socklen_t addr_len = sizeof(addr_storage);
1036
1037 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1038 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1039 return -1;
1040 }
1041
1042 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1043 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1044 errno = ECONNABORTED;
1045 return -1;
1046 }
1047
1048 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1049}
1050
Josh Gao90228a62019-04-25 14:04:57 -07001051int adb_shutdown(borrowed_fd fd, int direction) {
Josh Gao96049b92018-03-23 13:03:28 -07001052 FH f = _fh_from_int(fd, __func__);
Spencer Low753d4852015-07-30 23:07:55 -07001053
1054 if (!f || f->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001055 D("adb_shutdown: invalid fd %d", fd.get());
Spencer Low753d4852015-07-30 23:07:55 -07001056 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001057 return -1;
1058 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001059
Josh Gao96049b92018-03-23 13:03:28 -07001060 D("adb_shutdown: %s", f->name);
1061 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -07001062 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001063 D("socket shutdown fd %d failed: %s", fd.get(),
David Pursellc573d522016-01-27 08:52:53 -08001064 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001065 _socket_set_errno(err);
1066 return -1;
1067 }
1068 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001069}
1070
Josh Gaoe7388122016-02-16 17:34:53 -08001071// Emulate socketpair(2) by binding and connecting to a socket.
1072int adb_socketpair(int sv[2]) {
1073 int server = -1;
1074 int client = -1;
1075 int accepted = -1;
David Pursell19d0c232016-04-07 11:25:48 -07001076 int local_port = -1;
Josh Gaoe7388122016-02-16 17:34:53 -08001077 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001078
Josh Gaoe7388122016-02-16 17:34:53 -08001079 server = network_loopback_server(0, SOCK_STREAM, &error);
1080 if (server < 0) {
1081 D("adb_socketpair: failed to create server: %s", error.c_str());
1082 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001083 }
1084
David Pursell19d0c232016-04-07 11:25:48 -07001085 local_port = adb_socket_get_local_port(server);
1086 if (local_port < 0) {
1087 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gaoe7388122016-02-16 17:34:53 -08001088 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001089 }
David Pursell19d0c232016-04-07 11:25:48 -07001090 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001091
David Pursell19d0c232016-04-07 11:25:48 -07001092 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gaoe7388122016-02-16 17:34:53 -08001093 if (client < 0) {
1094 D("adb_socketpair: failed to connect client: %s", error.c_str());
1095 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001096 }
1097
Josh Gao4f6f4422017-03-30 13:04:35 -07001098 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gaoe7388122016-02-16 17:34:53 -08001099 if (accepted < 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -08001100 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoe7388122016-02-16 17:34:53 -08001101 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001102 }
Josh Gaoe7388122016-02-16 17:34:53 -08001103 adb_close(server);
1104 sv[0] = client;
1105 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001106 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001107
Josh Gaoe7388122016-02-16 17:34:53 -08001108fail:
1109 if (server >= 0) {
1110 adb_close(server);
1111 }
1112 if (client >= 0) {
1113 adb_close(client);
1114 }
1115 if (accepted >= 0) {
1116 adb_close(accepted);
1117 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001118 return -1;
1119}
1120
Josh Gao90228a62019-04-25 14:04:57 -07001121bool set_file_block_mode(borrowed_fd fd, bool block) {
Josh Gaoe7388122016-02-16 17:34:53 -08001122 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001123
Josh Gaoe7388122016-02-16 17:34:53 -08001124 if (!fh || !fh->used) {
1125 errno = EBADF;
Josh Gao90228a62019-04-25 14:04:57 -07001126 D("Setting nonblocking on bad file descriptor %d", fd.get());
Josh Gaoe7388122016-02-16 17:34:53 -08001127 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001128 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001129
Josh Gaoe7388122016-02-16 17:34:53 -08001130 if (fh->clazz == &_fh_socket_class) {
1131 u_long x = !block;
1132 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin20238f22016-09-21 14:03:39 -07001133 int error = WSAGetLastError();
1134 _socket_set_errno(error);
Josh Gao90228a62019-04-25 14:04:57 -07001135 D("Setting %d nonblocking failed (%d)", fd.get(), error);
Josh Gaoe7388122016-02-16 17:34:53 -08001136 return false;
1137 }
1138 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001139 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001140 errno = ENOTSOCK;
Josh Gao90228a62019-04-25 14:04:57 -07001141 D("Setting nonblocking on non-socket %d", fd.get());
Josh Gaoe7388122016-02-16 17:34:53 -08001142 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001143 }
1144}
1145
Josh Gao90228a62019-04-25 14:04:57 -07001146bool set_tcp_keepalive(borrowed_fd fd, int interval_sec) {
David Pursellc25a34e2016-02-22 14:27:23 -08001147 FH fh = _fh_from_int(fd, __func__);
1148
1149 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001150 D("set_tcp_keepalive(%d) failed: invalid fd", fd.get());
David Pursellc25a34e2016-02-22 14:27:23 -08001151 errno = EBADF;
1152 return false;
1153 }
1154
1155 tcp_keepalive keepalive;
1156 keepalive.onoff = (interval_sec > 0);
1157 keepalive.keepalivetime = interval_sec * 1000;
1158 keepalive.keepaliveinterval = interval_sec * 1000;
1159
1160 DWORD bytes_returned = 0;
1161 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1162 &bytes_returned, nullptr, nullptr) != 0) {
1163 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001164 D("set_tcp_keepalive(%d) failed: %s", fd.get(),
David Pursellc25a34e2016-02-22 14:27:23 -08001165 android::base::SystemErrorCodeToString(err).c_str());
1166 _socket_set_errno(err);
1167 return false;
1168 }
1169
1170 return true;
1171}
1172
Spencer Lowbeb61982015-03-01 15:06:21 -08001173/**************************************************************************/
1174/**************************************************************************/
1175/***** *****/
1176/***** Console Window Terminal Emulation *****/
1177/***** *****/
1178/**************************************************************************/
1179/**************************************************************************/
1180
1181// This reads input from a Win32 console window and translates it into Unix
1182// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1183// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1184// is emulated instead of xterm because it is probably more popular than xterm:
1185// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1186// supports modern fonts, etc. It seems best to emulate the terminal that most
1187// Android developers use because they'll fix apps (the shell, etc.) to keep
1188// working with that terminal's emulation.
1189//
1190// The point of this emulation is not to be perfect or to solve all issues with
1191// console windows on Windows, but to be better than the original code which
1192// just called read() (which called ReadFile(), which called ReadConsoleA())
1193// which did not support Ctrl-C, tab completion, shell input line editing
1194// keys, server echo, and more.
1195//
1196// This implementation reconfigures the console with SetConsoleMode(), then
1197// calls ReadConsoleInput() to get raw input which it remaps to Unix
1198// terminal-style sequences which is returned via unix_read() which is used
1199// by the 'adb shell' command.
1200//
1201// Code organization:
1202//
David Pursell58805362015-10-28 14:29:51 -07001203// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001204// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1205// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1206// * _console_read() is the main code of the emulation.
1207
David Pursell58805362015-10-28 14:29:51 -07001208// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1209// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1210// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
Josh Gao90228a62019-04-25 14:04:57 -07001211static HANDLE _get_console_handle(borrowed_fd fd, DWORD* mode = nullptr) {
David Pursell58805362015-10-28 14:29:51 -07001212 // First check isatty(); this is very fast and eliminates most non-console
1213 // FDs, but returns 1 for both consoles and character devices like NUL.
1214#pragma push_macro("isatty")
1215#undef isatty
Josh Gao90228a62019-04-25 14:04:57 -07001216 if (!isatty(fd.get())) {
David Pursell58805362015-10-28 14:29:51 -07001217 return nullptr;
1218 }
1219#pragma pop_macro("isatty")
1220
1221 // To differentiate between character devices and consoles we need to get
1222 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1223 // GENERIC_READ permissions.
Josh Gao90228a62019-04-25 14:04:57 -07001224 const intptr_t intptr_handle = _get_osfhandle(fd.get());
David Pursell58805362015-10-28 14:29:51 -07001225 if (intptr_handle == -1) {
1226 return nullptr;
1227 }
1228 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1229 DWORD temp_mode = 0;
1230 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1231 return nullptr;
1232 }
1233
1234 return handle;
1235}
1236
1237// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1238static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001239 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1240 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001241 const int fd = fileno(stream);
1242 if (fd < 0) {
1243 return nullptr;
1244 }
1245 return _get_console_handle(fd);
1246}
1247
Josh Gao90228a62019-04-25 14:04:57 -07001248int unix_isatty(borrowed_fd fd) {
David Pursell58805362015-10-28 14:29:51 -07001249 return _get_console_handle(fd) ? 1 : 0;
1250}
Spencer Lowbeb61982015-03-01 15:06:21 -08001251
Spencer Low9c8f7462015-11-10 19:17:16 -08001252// Get the next KEY_EVENT_RECORD that should be processed.
1253static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001254 for (;;) {
1255 DWORD read_count = 0;
1256 memset(input_record, 0, sizeof(*input_record));
1257 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001258 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001259 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001260 errno = EIO;
1261 return false;
1262 }
1263
1264 if (read_count == 0) { // should be impossible
Elliott Hughese64126b2018-10-19 13:59:44 -07001265 LOG(FATAL) << "ReadConsoleInputA returned 0";
Spencer Lowbeb61982015-03-01 15:06:21 -08001266 }
1267
1268 if (read_count != 1) { // should be impossible
Elliott Hughese64126b2018-10-19 13:59:44 -07001269 LOG(FATAL) << "ReadConsoleInputA did not return one input record";
Spencer Lowbeb61982015-03-01 15:06:21 -08001270 }
1271
Spencer Low55441402015-11-07 17:34:39 -08001272 // If the console window is resized, emulate SIGWINCH by breaking out
1273 // of read() with errno == EINTR. Note that there is no event on
1274 // vertical resize because we don't give the console our own custom
1275 // screen buffer (with CreateConsoleScreenBuffer() +
1276 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1277 // supports scrollback, but doesn't seem to raise an event for vertical
1278 // window resize.
1279 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1280 errno = EINTR;
1281 return false;
1282 }
1283
Spencer Lowbeb61982015-03-01 15:06:21 -08001284 if ((input_record->EventType == KEY_EVENT) &&
1285 (input_record->Event.KeyEvent.bKeyDown)) {
1286 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
Elliott Hughese64126b2018-10-19 13:59:44 -07001287 LOG(FATAL) << "ReadConsoleInputA returned a key event with zero repeat count";
Spencer Lowbeb61982015-03-01 15:06:21 -08001288 }
1289
1290 // Got an interesting INPUT_RECORD, so return
1291 return true;
1292 }
1293 }
1294}
1295
Spencer Lowbeb61982015-03-01 15:06:21 -08001296static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1297 return (control_key_state & SHIFT_PRESSED) != 0;
1298}
1299
1300static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1301 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1302}
1303
1304static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1305 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1306}
1307
1308static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1309 return (control_key_state & NUMLOCK_ON) != 0;
1310}
1311
1312static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1313 return (control_key_state & CAPSLOCK_ON) != 0;
1314}
1315
1316static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1317 return (control_key_state & ENHANCED_KEY) != 0;
1318}
1319
1320// Constants from MSDN for ToAscii().
1321static const BYTE TOASCII_KEY_OFF = 0x00;
1322static const BYTE TOASCII_KEY_DOWN = 0x80;
1323static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1324
1325// Given a key event, ignore a modifier key and return the character that was
1326// entered without the modifier. Writes to *ch and returns the number of bytes
1327// written.
1328static size_t _get_char_ignoring_modifier(char* const ch,
1329 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1330 const WORD modifier) {
1331 // If there is no character from Windows, try ignoring the specified
1332 // modifier and look for a character. Note that if AltGr is being used,
1333 // there will be a character from Windows.
1334 if (key_event->uChar.AsciiChar == '\0') {
1335 // Note that we read the control key state from the passed in argument
1336 // instead of from key_event since the argument has been normalized.
1337 if (((modifier == VK_SHIFT) &&
1338 _is_shift_pressed(control_key_state)) ||
1339 ((modifier == VK_CONTROL) &&
1340 _is_ctrl_pressed(control_key_state)) ||
1341 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1342
1343 BYTE key_state[256] = {0};
1344 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1345 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1346 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1347 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1348 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1349 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1350 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1351 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1352
1353 // cause this modifier to be ignored
1354 key_state[modifier] = TOASCII_KEY_OFF;
1355
1356 WORD translated = 0;
1357 if (ToAscii(key_event->wVirtualKeyCode,
1358 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1359 // Ignoring the modifier, we found a character.
1360 *ch = (CHAR)translated;
1361 return 1;
1362 }
1363 }
1364 }
1365
1366 // Just use whatever Windows told us originally.
1367 *ch = key_event->uChar.AsciiChar;
1368
1369 // If the character from Windows is NULL, return a size of zero.
1370 return (*ch == '\0') ? 0 : 1;
1371}
1372
1373// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1374// but taking into account the shift key. This is because for a sequence like
1375// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1376// we want to find the character ')'.
1377//
1378// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1379// because it is the default key-sequence to switch the input language.
1380// This is configurable in the Region and Language control panel.
1381static __inline__ size_t _get_non_control_char(char* const ch,
1382 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1383 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1384 VK_CONTROL);
1385}
1386
1387// Get without Alt.
1388static __inline__ size_t _get_non_alt_char(char* const ch,
1389 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1390 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1391 VK_MENU);
1392}
1393
1394// Ignore the control key, find the character from Windows, and apply any
1395// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1396// *pch and returns number of bytes written.
1397static size_t _get_control_character(char* const pch,
1398 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1399 const size_t len = _get_non_control_char(pch, key_event,
1400 control_key_state);
1401
1402 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1403 char ch = *pch;
1404 switch (ch) {
1405 case '2':
1406 case '@':
1407 case '`':
1408 ch = '\0';
1409 break;
1410 case '3':
1411 case '[':
1412 case '{':
1413 ch = '\x1b';
1414 break;
1415 case '4':
1416 case '\\':
1417 case '|':
1418 ch = '\x1c';
1419 break;
1420 case '5':
1421 case ']':
1422 case '}':
1423 ch = '\x1d';
1424 break;
1425 case '6':
1426 case '^':
1427 case '~':
1428 ch = '\x1e';
1429 break;
1430 case '7':
1431 case '-':
1432 case '_':
1433 ch = '\x1f';
1434 break;
1435 case '8':
1436 ch = '\x7f';
1437 break;
1438 case '/':
1439 if (!_is_alt_pressed(control_key_state)) {
1440 ch = '\x1f';
1441 }
1442 break;
1443 case '?':
1444 if (!_is_alt_pressed(control_key_state)) {
1445 ch = '\x7f';
1446 }
1447 break;
1448 }
1449 *pch = ch;
1450 }
1451
1452 return len;
1453}
1454
1455static DWORD _normalize_altgr_control_key_state(
1456 const KEY_EVENT_RECORD* const key_event) {
1457 DWORD control_key_state = key_event->dwControlKeyState;
1458
1459 // If we're in an AltGr situation where the AltGr key is down (depending on
1460 // the keyboard layout, that might be the physical right alt key which
1461 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1462 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1463 // a character (which indicates that there was an AltGr mapping), then act
1464 // as if alt and control are not really down for the purposes of modifiers.
1465 // This makes it so that if the user with, say, a German keyboard layout
1466 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1467 // output the key and we don't see the Alt and Ctrl keys.
1468 if (_is_ctrl_pressed(control_key_state) &&
1469 _is_alt_pressed(control_key_state)
1470 && (key_event->uChar.AsciiChar != '\0')) {
1471 // Try to remove as few bits as possible to improve our chances of
1472 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1473 // Left-Alt + Right-Ctrl + AltGr.
1474 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1475 // Remove Right-Alt.
1476 control_key_state &= ~RIGHT_ALT_PRESSED;
1477 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1478 // pressed, Left-Ctrl is almost always set, except if the user
1479 // presses Right-Ctrl, then AltGr (in that specific order) for
1480 // whatever reason. At any rate, make sure the bit is not set.
1481 control_key_state &= ~LEFT_CTRL_PRESSED;
1482 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1483 // Remove Left-Alt.
1484 control_key_state &= ~LEFT_ALT_PRESSED;
1485 // Whichever Ctrl key is down, remove it from the state. We only
1486 // remove one key, to improve our chances of detecting the
1487 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1488 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1489 // Remove Left-Ctrl.
1490 control_key_state &= ~LEFT_CTRL_PRESSED;
1491 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1492 // Remove Right-Ctrl.
1493 control_key_state &= ~RIGHT_CTRL_PRESSED;
1494 }
1495 }
1496
1497 // Note that this logic isn't 100% perfect because Windows doesn't
1498 // allow us to detect all combinations because a physical AltGr key
1499 // press shows up as two bits, plus some combinations are ambiguous
1500 // about what is actually physically pressed.
1501 }
1502
1503 return control_key_state;
1504}
1505
1506// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1507// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1508// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1509// appropriately.
1510static DWORD _normalize_keypad_control_key_state(const WORD vk,
1511 const DWORD control_key_state) {
1512 if (!_is_numlock_on(control_key_state)) {
1513 return control_key_state;
1514 }
1515 if (!_is_enhanced_key(control_key_state)) {
1516 switch (vk) {
1517 case VK_INSERT: // 0
1518 case VK_DELETE: // .
1519 case VK_END: // 1
1520 case VK_DOWN: // 2
1521 case VK_NEXT: // 3
1522 case VK_LEFT: // 4
1523 case VK_CLEAR: // 5
1524 case VK_RIGHT: // 6
1525 case VK_HOME: // 7
1526 case VK_UP: // 8
1527 case VK_PRIOR: // 9
1528 return control_key_state | SHIFT_PRESSED;
1529 }
1530 }
1531
1532 return control_key_state;
1533}
1534
1535static const char* _get_keypad_sequence(const DWORD control_key_state,
1536 const char* const normal, const char* const shifted) {
1537 if (_is_shift_pressed(control_key_state)) {
1538 // Shift is pressed and NumLock is off
1539 return shifted;
1540 } else {
1541 // Shift is not pressed and NumLock is off, or,
1542 // Shift is pressed and NumLock is on, in which case we want the
1543 // NumLock and Shift to neutralize each other, thus, we want the normal
1544 // sequence.
1545 return normal;
1546 }
1547 // If Shift is not pressed and NumLock is on, a different virtual key code
1548 // is returned by Windows, which can be taken care of by a different case
1549 // statement in _console_read().
1550}
1551
1552// Write sequence to buf and return the number of bytes written.
1553static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1554 DWORD control_key_state, const char* const normal) {
1555 // Copy the base sequence into buf.
1556 const size_t len = strlen(normal);
1557 memcpy(buf, normal, len);
1558
1559 int code = 0;
1560
1561 control_key_state = _normalize_keypad_control_key_state(vk,
1562 control_key_state);
1563
1564 if (_is_shift_pressed(control_key_state)) {
1565 code |= 0x1;
1566 }
1567 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1568 code |= 0x2;
1569 }
1570 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1571 code |= 0x4;
1572 }
1573 // If some modifier was held down, then we need to insert the modifier code
1574 if (code != 0) {
1575 if (len == 0) {
1576 // Should be impossible because caller should pass a string of
1577 // non-zero length.
1578 return 0;
1579 }
1580 size_t index = len - 1;
1581 const char lastChar = buf[index];
1582 if (lastChar != '~') {
1583 buf[index++] = '1';
1584 }
1585 buf[index++] = ';'; // modifier separator
1586 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1587 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1588 buf[index++] = '1' + code;
1589 buf[index++] = lastChar; // move ~ (or other last char) to the end
1590 return index;
1591 }
1592 return len;
1593}
1594
1595// Write sequence to buf and return the number of bytes written.
1596static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1597 const DWORD control_key_state, const char* const normal,
1598 const char shifted) {
1599 if (_is_shift_pressed(control_key_state)) {
1600 // Shift is pressed and NumLock is off
1601 if (shifted != '\0') {
1602 buf[0] = shifted;
1603 return sizeof(buf[0]);
1604 } else {
1605 return 0;
1606 }
1607 } else {
1608 // Shift is not pressed and NumLock is off, or,
1609 // Shift is pressed and NumLock is on, in which case we want the
1610 // NumLock and Shift to neutralize each other, thus, we want the normal
1611 // sequence.
1612 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1613 }
1614 // If Shift is not pressed and NumLock is on, a different virtual key code
1615 // is returned by Windows, which can be taken care of by a different case
1616 // statement in _console_read().
1617}
1618
1619// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1620// Standard German. Figure this out at runtime so we know what to output for
1621// Shift-VK_DELETE.
1622static char _get_decimal_char() {
1623 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1624}
1625
1626// Prefix the len bytes in buf with the escape character, and then return the
1627// new buffer length.
Josh Gao90228a62019-04-25 14:04:57 -07001628static size_t _escape_prefix(char* const buf, const size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001629 // If nothing to prefix, don't do anything. We might be called with
1630 // len == 0, if alt was held down with a dead key which produced nothing.
1631 if (len == 0) {
1632 return 0;
1633 }
1634
1635 memmove(&buf[1], buf, len);
1636 buf[0] = '\x1b';
1637 return len + 1;
1638}
1639
Spencer Low9c8f7462015-11-10 19:17:16 -08001640// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001641static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001642
1643// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1644// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001645static int _console_read(const HANDLE console, void* buf, size_t len) {
1646 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001647 // Read of zero bytes should not block waiting for something from the console.
1648 if (len == 0) {
1649 return 0;
1650 }
1651
1652 // Flush as much as possible from input buffer.
1653 if (!g_console_input_buffer.empty()) {
1654 const int bytes_read = std::min(len, g_console_input_buffer.size());
1655 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1656 const auto begin = g_console_input_buffer.begin();
1657 g_console_input_buffer.erase(begin, begin + bytes_read);
1658 return bytes_read;
1659 }
1660
1661 // Read from the actual console. This may block until input.
1662 INPUT_RECORD input_record;
1663 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001664 return -1;
1665 }
1666
Spencer Low9c8f7462015-11-10 19:17:16 -08001667 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001668 const WORD vk = key_event->wVirtualKeyCode;
1669 const CHAR ch = key_event->uChar.AsciiChar;
1670 const DWORD control_key_state = _normalize_altgr_control_key_state(
1671 key_event);
1672
1673 // The following emulation code should write the output sequence to
1674 // either seqstr or to seqbuf and seqbuflen.
Yi Kong86e67182018-07-13 18:15:16 -07001675 const char* seqstr = nullptr; // NULL terminated C-string
Spencer Lowbeb61982015-03-01 15:06:21 -08001676 // Enough space for max sequence string below, plus modifiers and/or
1677 // escape prefix.
1678 char seqbuf[16];
1679 size_t seqbuflen = 0; // Space used in seqbuf.
1680
1681#define MATCH(vk, normal) \
1682 case (vk): \
1683 { \
1684 seqstr = (normal); \
1685 } \
1686 break;
1687
1688 // Modifier keys should affect the output sequence.
1689#define MATCH_MODIFIER(vk, normal) \
1690 case (vk): \
1691 { \
1692 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1693 control_key_state, (normal)); \
1694 } \
1695 break;
1696
1697 // The shift key should affect the output sequence.
1698#define MATCH_KEYPAD(vk, normal, shifted) \
1699 case (vk): \
1700 { \
1701 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1702 (shifted)); \
1703 } \
1704 break;
1705
1706 // The shift key and other modifier keys should affect the output
1707 // sequence.
1708#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1709 case (vk): \
1710 { \
1711 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1712 control_key_state, (normal), (shifted)); \
1713 } \
1714 break;
1715
1716#define ESC "\x1b"
1717#define CSI ESC "["
1718#define SS3 ESC "O"
1719
1720 // Only support normal mode, not application mode.
1721
1722 // Enhanced keys:
1723 // * 6-pack: insert, delete, home, end, page up, page down
1724 // * cursor keys: up, down, right, left
1725 // * keypad: divide, enter
1726 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1727 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1728 if (_is_enhanced_key(control_key_state)) {
1729 switch (vk) {
1730 case VK_RETURN: // Enter key on keypad
1731 if (_is_ctrl_pressed(control_key_state)) {
1732 seqstr = "\n";
1733 } else {
1734 seqstr = "\r";
1735 }
1736 break;
1737
1738 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1739 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1740
1741 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1742 // will be fixed soon to match xterm which sends CSI "F" and
1743 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1744 MATCH(VK_END, CSI "F");
1745 MATCH(VK_HOME, CSI "H");
1746
1747 MATCH_MODIFIER(VK_LEFT, CSI "D");
1748 MATCH_MODIFIER(VK_UP, CSI "A");
1749 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1750 MATCH_MODIFIER(VK_DOWN, CSI "B");
1751
1752 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1753 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1754
1755 MATCH(VK_DIVIDE, "/");
1756 }
1757 } else { // Non-enhanced keys:
1758 switch (vk) {
1759 case VK_BACK: // backspace
1760 if (_is_alt_pressed(control_key_state)) {
1761 seqstr = ESC "\x7f";
1762 } else {
1763 seqstr = "\x7f";
1764 }
1765 break;
1766
1767 case VK_TAB:
1768 if (_is_shift_pressed(control_key_state)) {
1769 seqstr = CSI "Z";
1770 } else {
1771 seqstr = "\t";
1772 }
1773 break;
1774
1775 // Number 5 key in keypad when NumLock is off, or if NumLock is
1776 // on and Shift is down.
1777 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1778
1779 case VK_RETURN: // Enter key on main keyboard
1780 if (_is_alt_pressed(control_key_state)) {
1781 seqstr = ESC "\n";
1782 } else if (_is_ctrl_pressed(control_key_state)) {
1783 seqstr = "\n";
1784 } else {
1785 seqstr = "\r";
1786 }
1787 break;
1788
1789 // VK_ESCAPE: Don't do any special handling. The OS uses many
1790 // of the sequences with Escape and many of the remaining
1791 // sequences don't produce bKeyDown messages, only !bKeyDown
1792 // for whatever reason.
1793
1794 case VK_SPACE:
1795 if (_is_alt_pressed(control_key_state)) {
1796 seqstr = ESC " ";
1797 } else if (_is_ctrl_pressed(control_key_state)) {
1798 seqbuf[0] = '\0'; // NULL char
1799 seqbuflen = 1;
1800 } else {
1801 seqstr = " ";
1802 }
1803 break;
1804
1805 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1806 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1807
1808 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1809 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1810
1811 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1812 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1813 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1814 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1815
1816 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1817 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1818 _get_decimal_char());
1819
1820 case 0x30: // 0
1821 case 0x31: // 1
1822 case 0x39: // 9
1823 case VK_OEM_1: // ;:
1824 case VK_OEM_PLUS: // =+
1825 case VK_OEM_COMMA: // ,<
1826 case VK_OEM_PERIOD: // .>
1827 case VK_OEM_7: // '"
1828 case VK_OEM_102: // depends on keyboard, could be <> or \|
1829 case VK_OEM_2: // /?
1830 case VK_OEM_3: // `~
1831 case VK_OEM_4: // [{
1832 case VK_OEM_5: // \|
1833 case VK_OEM_6: // ]}
1834 {
1835 seqbuflen = _get_control_character(seqbuf, key_event,
1836 control_key_state);
1837
1838 if (_is_alt_pressed(control_key_state)) {
1839 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1840 }
1841 }
1842 break;
1843
1844 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001845 case 0x33: // 3
1846 case 0x34: // 4
1847 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001848 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001849 case 0x37: // 7
1850 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001851 case VK_OEM_MINUS: // -_
1852 {
1853 seqbuflen = _get_control_character(seqbuf, key_event,
1854 control_key_state);
1855
1856 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1857 // prefix with escape.
1858 if (_is_alt_pressed(control_key_state) &&
1859 !(_is_ctrl_pressed(control_key_state) &&
1860 !_is_shift_pressed(control_key_state))) {
1861 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1862 }
1863 }
1864 break;
1865
Spencer Lowbeb61982015-03-01 15:06:21 -08001866 case 0x41: // a
1867 case 0x42: // b
1868 case 0x43: // c
1869 case 0x44: // d
1870 case 0x45: // e
1871 case 0x46: // f
1872 case 0x47: // g
1873 case 0x48: // h
1874 case 0x49: // i
1875 case 0x4a: // j
1876 case 0x4b: // k
1877 case 0x4c: // l
1878 case 0x4d: // m
1879 case 0x4e: // n
1880 case 0x4f: // o
1881 case 0x50: // p
1882 case 0x51: // q
1883 case 0x52: // r
1884 case 0x53: // s
1885 case 0x54: // t
1886 case 0x55: // u
1887 case 0x56: // v
1888 case 0x57: // w
1889 case 0x58: // x
1890 case 0x59: // y
1891 case 0x5a: // z
1892 {
1893 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1894 control_key_state);
1895
1896 // If Alt is pressed, then prefix with escape.
1897 if (_is_alt_pressed(control_key_state)) {
1898 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1899 }
1900 }
1901 break;
1902
1903 // These virtual key codes are generated by the keys on the
1904 // keypad *when NumLock is on* and *Shift is up*.
1905 MATCH(VK_NUMPAD0, "0");
1906 MATCH(VK_NUMPAD1, "1");
1907 MATCH(VK_NUMPAD2, "2");
1908 MATCH(VK_NUMPAD3, "3");
1909 MATCH(VK_NUMPAD4, "4");
1910 MATCH(VK_NUMPAD5, "5");
1911 MATCH(VK_NUMPAD6, "6");
1912 MATCH(VK_NUMPAD7, "7");
1913 MATCH(VK_NUMPAD8, "8");
1914 MATCH(VK_NUMPAD9, "9");
1915
1916 MATCH(VK_MULTIPLY, "*");
1917 MATCH(VK_ADD, "+");
1918 MATCH(VK_SUBTRACT, "-");
1919 // VK_DECIMAL is generated by the . key on the keypad *when
1920 // NumLock is on* and *Shift is up* and the sequence is not
1921 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1922 // Windows Security screen to come up).
1923 case VK_DECIMAL:
1924 // U.S. English uses '.', Germany German uses ','.
1925 seqbuflen = _get_non_control_char(seqbuf, key_event,
1926 control_key_state);
1927 break;
1928
1929 MATCH_MODIFIER(VK_F1, SS3 "P");
1930 MATCH_MODIFIER(VK_F2, SS3 "Q");
1931 MATCH_MODIFIER(VK_F3, SS3 "R");
1932 MATCH_MODIFIER(VK_F4, SS3 "S");
1933 MATCH_MODIFIER(VK_F5, CSI "15~");
1934 MATCH_MODIFIER(VK_F6, CSI "17~");
1935 MATCH_MODIFIER(VK_F7, CSI "18~");
1936 MATCH_MODIFIER(VK_F8, CSI "19~");
1937 MATCH_MODIFIER(VK_F9, CSI "20~");
1938 MATCH_MODIFIER(VK_F10, CSI "21~");
1939 MATCH_MODIFIER(VK_F11, CSI "23~");
1940 MATCH_MODIFIER(VK_F12, CSI "24~");
1941
1942 MATCH_MODIFIER(VK_F13, CSI "25~");
1943 MATCH_MODIFIER(VK_F14, CSI "26~");
1944 MATCH_MODIFIER(VK_F15, CSI "28~");
1945 MATCH_MODIFIER(VK_F16, CSI "29~");
1946 MATCH_MODIFIER(VK_F17, CSI "31~");
1947 MATCH_MODIFIER(VK_F18, CSI "32~");
1948 MATCH_MODIFIER(VK_F19, CSI "33~");
1949 MATCH_MODIFIER(VK_F20, CSI "34~");
1950
1951 // MATCH_MODIFIER(VK_F21, ???);
1952 // MATCH_MODIFIER(VK_F22, ???);
1953 // MATCH_MODIFIER(VK_F23, ???);
1954 // MATCH_MODIFIER(VK_F24, ???);
1955 }
1956 }
1957
1958#undef MATCH
1959#undef MATCH_MODIFIER
1960#undef MATCH_KEYPAD
1961#undef MATCH_MODIFIER_KEYPAD
1962#undef ESC
1963#undef CSI
1964#undef SS3
1965
1966 const char* out;
1967 size_t outlen;
1968
1969 // Check for output in any of:
1970 // * seqstr is set (and strlen can be used to determine the length).
1971 // * seqbuf and seqbuflen are set
1972 // Fallback to ch from Windows.
Yi Kong86e67182018-07-13 18:15:16 -07001973 if (seqstr != nullptr) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001974 out = seqstr;
1975 outlen = strlen(seqstr);
1976 } else if (seqbuflen > 0) {
1977 out = seqbuf;
1978 outlen = seqbuflen;
1979 } else if (ch != '\0') {
1980 // Use whatever Windows told us it is.
1981 seqbuf[0] = ch;
1982 seqbuflen = 1;
1983 out = seqbuf;
1984 outlen = seqbuflen;
1985 } else {
1986 // No special handling for the virtual key code and Windows isn't
1987 // telling us a character code, then we don't know how to translate
1988 // the key press.
1989 //
1990 // Consume the input and 'continue' to cause us to get a new key
1991 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07001992 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08001993 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08001994 continue;
1995 }
1996
Spencer Low9c8f7462015-11-10 19:17:16 -08001997 // put output wRepeatCount times into g_console_input_buffer
1998 while (key_event->wRepeatCount-- > 0) {
1999 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08002000 }
2001
Spencer Low9c8f7462015-11-10 19:17:16 -08002002 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08002003 }
2004}
2005
2006static DWORD _old_console_mode; // previous GetConsoleMode() result
2007static HANDLE _console_handle; // when set, console mode should be restored
2008
Elliott Hughesa8265792015-11-03 11:18:40 -08002009void stdin_raw_init() {
2010 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08002011 if (in == nullptr) {
2012 return;
2013 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002014
Elliott Hughesa8265792015-11-03 11:18:40 -08002015 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2016 // calling the process Ctrl-C routine (configured by
2017 // SetConsoleCtrlHandler()).
2018 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2019 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2020 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08002021 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2022 ENABLE_LINE_INPUT |
2023 ENABLE_ECHO_INPUT);
2024 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2025 new_console_mode |= ENABLE_WINDOW_INPUT;
2026
2027 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002028 // This really should not fail.
2029 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002030 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002031 }
Elliott Hughesa8265792015-11-03 11:18:40 -08002032
2033 // Once this is set, it means that stdin has been configured for
2034 // reading from and that the old console mode should be restored later.
2035 _console_handle = in;
2036
2037 // Note that we don't need to configure C Runtime line-ending
2038 // translation because _console_read() does not call the C Runtime to
2039 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002040}
2041
Elliott Hughesa8265792015-11-03 11:18:40 -08002042void stdin_raw_restore() {
Yi Kong86e67182018-07-13 18:15:16 -07002043 if (_console_handle != nullptr) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002044 const HANDLE in = _console_handle;
Yi Kong86e67182018-07-13 18:15:16 -07002045 _console_handle = nullptr; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002046
Elliott Hughesa8265792015-11-03 11:18:40 -08002047 if (!SetConsoleMode(in, _old_console_mode)) {
2048 // This really should not fail.
2049 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002050 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002051 }
2052 }
2053}
2054
Spencer Low55441402015-11-07 17:34:39 -08002055// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
Josh Gao90228a62019-04-25 14:04:57 -07002056int unix_read_interruptible(borrowed_fd fd, void* buf, size_t len) {
Yi Kong86e67182018-07-13 18:15:16 -07002057 if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002058 // If it is a request to read from stdin, and stdin_raw_init() has been
2059 // called, and it successfully configured the console, then read from
2060 // the console using Win32 console APIs and partially emulate a unix
2061 // terminal.
2062 return _console_read(_console_handle, buf, len);
2063 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002064 // On older versions of Windows (definitely 7, definitely not 10),
2065 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002066 // we need to limit the read size.
2067 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002068 len = 4096;
2069 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002070 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002071 // can do LF/CR translation (which is overridable with _setmode()).
2072 // Undefine the macro that is set in sysdeps.h which bans calls to
2073 // plain read() in favor of unix_read() or adb_read().
2074#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002075#undef read
Josh Gao90228a62019-04-25 14:04:57 -07002076 return read(fd.get(), buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002077#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002078 }
2079}
Spencer Low6815c072015-05-11 01:08:48 -07002080
2081/**************************************************************************/
2082/**************************************************************************/
2083/***** *****/
2084/***** Unicode support *****/
2085/***** *****/
2086/**************************************************************************/
2087/**************************************************************************/
2088
2089// This implements support for using files with Unicode filenames and for
2090// outputting Unicode text to a Win32 console window. This is inspired from
2091// http://utf8everywhere.org/.
2092//
2093// Background
2094// ----------
2095//
2096// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2097// filenames to APIs such as open(). This works because filenames are largely
2098// opaque 'cookies' (perhaps excluding path separators).
2099//
2100// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2101// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2102// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2103// CreateFile() API is really just a macro that adds the W/A based on whether
2104// the UNICODE preprocessor symbol is defined).
2105//
2106// Options
2107// -------
2108//
2109// Thus, to write a portable program, there are a few options:
2110//
2111// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2112// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2113// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2114// open() API.
2115//
2116// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2117// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2118// potentially touching a lot of code.
2119//
2120// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2121// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2122// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2123// or C Runtime API.
2124//
2125// The Choice
2126// ----------
2127//
Spencer Low50f5bf12015-11-12 15:20:15 -08002128// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2129// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002130// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002131// args that are passed to main() at the beginning of program startup. We also use
2132// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002133// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2134//
2135// Unicode console output
2136// ----------------------
2137//
2138// The way to output Unicode to a Win32 console window is to call
2139// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002140// such as Lucida Console or Consolas, and in the case of East Asian languages
2141// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2142// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2143// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002144//
2145// The problem is getting the C Runtime to make fprintf and related APIs call
2146// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2147// promising, but the various modes have issues:
2148//
2149// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2150// UTF-16 do not display properly.
2151// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2152// totally wrong.
2153// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2154// handler to be called (upon a later I/O call), aborting the process.
2155// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2156// to output nothing.
2157//
2158// So the only solution is to write our own adb_fprintf() that converts UTF-8
2159// to UTF-16 and then calls WriteConsoleW().
2160
2161
Spencer Low6815c072015-05-11 01:08:48 -07002162// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2163// be passed to main().
2164NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2165 narrow_args = new char*[argc + 1];
2166
2167 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002168 std::string arg_narrow;
2169 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
Elliott Hughese64126b2018-10-19 13:59:44 -07002170 PLOG(FATAL) << "cannot convert argument from UTF-16 to UTF-8";
Spencer Low50f5bf12015-11-12 15:20:15 -08002171 }
2172 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002173 }
2174 narrow_args[argc] = nullptr; // terminate
2175}
2176
2177NarrowArgs::~NarrowArgs() {
2178 if (narrow_args != nullptr) {
2179 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2180 free(*argp);
2181 }
2182 delete[] narrow_args;
2183 narrow_args = nullptr;
2184 }
2185}
2186
Josh Gaof0c44032018-12-12 16:12:28 -08002187int unix_open(std::string_view path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002188 std::wstring path_wide;
Josh Gaof0c44032018-12-12 16:12:28 -08002189 if (!android::base::UTF8ToWide(path.data(), path.size(), &path_wide)) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002190 return -1;
2191 }
Spencer Low6815c072015-05-11 01:08:48 -07002192 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002193 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002194 } else {
Josh Gaof0c44032018-12-12 16:12:28 -08002195 int mode;
Spencer Low6815c072015-05-11 01:08:48 -07002196 va_list args;
2197 va_start(args, options);
2198 mode = va_arg(args, int);
2199 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002200 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002201 }
2202}
2203
Spencer Low6815c072015-05-11 01:08:48 -07002204// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002205DIR* adb_opendir(const char* path) {
2206 std::wstring path_wide;
2207 if (!android::base::UTF8ToWide(path, &path_wide)) {
2208 return nullptr;
2209 }
2210
Spencer Low6815c072015-05-11 01:08:48 -07002211 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2212 // the fields, but right now all the callers treat the structure as
2213 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002214 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002215}
2216
2217// Version of readdir() that returns UTF-8 paths.
2218struct dirent* adb_readdir(DIR* dir) {
2219 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2220 struct _wdirent* const went = _wreaddir(wdir);
2221 if (went == nullptr) {
2222 return nullptr;
2223 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002224
Spencer Low6815c072015-05-11 01:08:48 -07002225 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002226 std::string name_utf8;
2227 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2228 return nullptr;
2229 }
Spencer Low6815c072015-05-11 01:08:48 -07002230
2231 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2232 // space for UTF-16 wchar_t's) with UTF-8 char's.
2233 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2234
2235 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2236 // Name too big to fit in existing buffer.
2237 errno = ENOMEM;
2238 return nullptr;
2239 }
2240
2241 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2242 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2243 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2244 // bigger than the caller expects because they expect a dirent structure
2245 // which has a smaller d_name field. Ignore this since the caller should be
2246 // resilient.
2247
2248 // Rewrite the UTF-16 d_name field to UTF-8.
2249 strcpy(ent->d_name, name_utf8.c_str());
2250
2251 return ent;
2252}
2253
2254// Version of closedir() to go with our version of adb_opendir().
2255int adb_closedir(DIR* dir) {
2256 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2257}
2258
2259// Version of unlink() that takes a UTF-8 path.
2260int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002261 std::wstring wpath;
2262 if (!android::base::UTF8ToWide(path, &wpath)) {
2263 return -1;
2264 }
Spencer Low6815c072015-05-11 01:08:48 -07002265
2266 int rc = _wunlink(wpath.c_str());
2267
2268 if (rc == -1 && errno == EACCES) {
2269 /* unlink returns EACCES when the file is read-only, so we first */
2270 /* try to make it writable, then unlink again... */
2271 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2272 if (rc == 0)
2273 rc = _wunlink(wpath.c_str());
2274 }
2275 return rc;
2276}
2277
2278// Version of mkdir() that takes a UTF-8 path.
2279int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002280 std::wstring path_wide;
2281 if (!android::base::UTF8ToWide(path, &path_wide)) {
2282 return -1;
2283 }
2284
2285 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002286}
2287
2288// Version of utime() that takes a UTF-8 path.
2289int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002290 std::wstring path_wide;
2291 if (!android::base::UTF8ToWide(path, &path_wide)) {
2292 return -1;
2293 }
2294
Spencer Low6815c072015-05-11 01:08:48 -07002295 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2296 "utimbuf and _utimbuf should be the same size because they both "
2297 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002298 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002299}
2300
2301// Version of chmod() that takes a UTF-8 path.
2302int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002303 std::wstring path_wide;
2304 if (!android::base::UTF8ToWide(path, &path_wide)) {
2305 return -1;
2306 }
2307
2308 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002309}
2310
Spencer Lowf373c352015-11-15 16:29:36 -08002311// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2312static inline size_t utf8_codepoint_len(uint8_t ch) {
2313 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2314}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002315
Spencer Lowf373c352015-11-15 16:29:36 -08002316namespace internal {
2317
2318// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2319// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2320// remaining_bytes.
2321size_t ParseCompleteUTF8(const char* const first, const char* const last,
2322 std::vector<char>* const remaining_bytes) {
2323 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2324 // Current_after points one byte past the current byte to be examined.
2325 for (const char* current_after = last; current_after != first; --current_after) {
2326 const char* const current = current_after - 1;
2327 const char ch = *current;
2328 const char kHighBit = 0x80u;
2329 const char kTwoHighestBits = 0xC0u;
2330 if ((ch & kHighBit) == 0) { // high bit not set
2331 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2332 // bytes with no leading byte, so return the entire buffer.
2333 break;
2334 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2335 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2336 const size_t bytes_available = last - current;
2337 if (bytes_available < utf8_codepoint_len(ch)) {
2338 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2339 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2340 // to remaining_bytes.
2341 remaining_bytes->insert(remaining_bytes->end(), current, last);
2342 return current - first;
2343 } else {
2344 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2345 // trailing bytes with no lead byte, so return the entire buffer.
2346 break;
2347 }
2348 } else {
2349 // Trailing byte, so keep going backwards looking for the lead byte.
2350 }
2351 }
2352
2353 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2354 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2355 // so that they can be processed.
2356 return last - first;
2357}
2358
2359}
2360
2361// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2362// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2363// This matches the behavior of Linux.
Spencer Lowf373c352015-11-15 16:29:36 -08002364
2365// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2366static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2367 HANDLE console) {
Josh Gaoe7daf572016-09-21 12:37:10 -07002368 static std::mutex& console_output_buffer_lock = *new std::mutex();
2369 static auto& console_output_buffer = *new std::vector<char>();
2370
Spencer Lowf373c352015-11-15 16:29:36 -08002371 const int saved_errno = errno;
2372 std::vector<char> combined_buffer;
2373
2374 // Complete UTF-8 sequences that should be immediately written to the console.
2375 const char* utf8;
2376 size_t utf8_size;
2377
Josh Gaoe7daf572016-09-21 12:37:10 -07002378 {
2379 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2380 if (console_output_buffer.empty()) {
2381 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2382 // common case with plain ASCII), parse buf directly.
2383 utf8 = buf;
2384 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2385 } else {
2386 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2387 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2388 // combined_buffer, then parse it all together.
2389 combined_buffer.swap(console_output_buffer);
2390 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowf373c352015-11-15 16:29:36 -08002391
Josh Gaoe7daf572016-09-21 12:37:10 -07002392 utf8 = combined_buffer.data();
2393 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2394 &console_output_buffer);
2395 }
Spencer Lowf373c352015-11-15 16:29:36 -08002396 }
Spencer Lowf373c352015-11-15 16:29:36 -08002397
2398 std::wstring utf16;
2399
2400 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2401 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2402 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002403 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002404 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002405
2406 // Note that this does not do \n => \r\n translation because that
2407 // doesn't seem necessary for the Windows console. For the Windows
2408 // console \r moves to the beginning of the line and \n moves to a new
2409 // line.
2410
2411 // Flush any stream buffering so that our output is afterwards which
2412 // makes sense because our call is afterwards.
2413 (void)fflush(stream);
2414
2415 // Write UTF-16 to the console.
2416 DWORD written = 0;
Yi Kong86e67182018-07-13 18:15:16 -07002417 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) {
Spencer Low6815c072015-05-11 01:08:48 -07002418 errno = EIO;
2419 return -1;
2420 }
2421
Spencer Lowf373c352015-11-15 16:29:36 -08002422 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2423 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2424 // matches the Linux behavior.
2425 errno = saved_errno;
2426 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002427}
2428
2429// Function prototype because attributes cannot be placed on func definitions.
Elliott Hughes874c9412018-06-26 13:06:15 -07002430static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap)
2431 __attribute__((__format__(__printf__, 3, 0)));
Spencer Low6815c072015-05-11 01:08:48 -07002432
2433// Internal function to format a UTF-8 string and write it to a Win32 console.
2434// Returns -1 on error.
2435static int _console_vfprintf(const HANDLE console, FILE* stream,
2436 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002437 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002438 std::string output_utf8;
2439
2440 // Format the string.
2441 // This could throw std::bad_alloc.
2442 android::base::StringAppendV(&output_utf8, format, ap);
2443
Spencer Lowf373c352015-11-15 16:29:36 -08002444 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2445 console);
2446 if (result != -1) {
2447 errno = saved_errno;
2448 } else {
2449 // If -1 was returned, errno has been set.
2450 }
2451 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002452}
2453
2454// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2455// Windows console.
2456int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2457 const HANDLE console = _get_console_handle(stream);
2458
2459 // If there is an associated Win32 console, write to it specially,
2460 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kong86e67182018-07-13 18:15:16 -07002461 if (console != nullptr) {
Spencer Low6815c072015-05-11 01:08:48 -07002462 return _console_vfprintf(console, stream, format, ap);
2463 } else {
2464 // If vfprintf is a macro, undefine it, so we can call the real
2465 // C Runtime API.
2466#pragma push_macro("vfprintf")
2467#undef vfprintf
2468 return vfprintf(stream, format, ap);
2469#pragma pop_macro("vfprintf")
2470 }
2471}
2472
Spencer Lowf373c352015-11-15 16:29:36 -08002473// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2474int adb_vprintf(const char *format, va_list ap) {
2475 return adb_vfprintf(stdout, format, ap);
2476}
2477
Spencer Low6815c072015-05-11 01:08:48 -07002478// Version of fprintf() that takes UTF-8 and can write Unicode to a
2479// Windows console.
2480int adb_fprintf(FILE *stream, const char *format, ...) {
2481 va_list ap;
2482 va_start(ap, format);
2483 const int result = adb_vfprintf(stream, format, ap);
2484 va_end(ap);
2485
2486 return result;
2487}
2488
2489// Version of printf() that takes UTF-8 and can write Unicode to a
2490// Windows console.
2491int adb_printf(const char *format, ...) {
2492 va_list ap;
2493 va_start(ap, format);
2494 const int result = adb_vfprintf(stdout, format, ap);
2495 va_end(ap);
2496
2497 return result;
2498}
2499
2500// Version of fputs() that takes UTF-8 and can write Unicode to a
2501// Windows console.
2502int adb_fputs(const char* buf, FILE* stream) {
2503 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2504 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002505 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002506 return adb_fprintf(stream, "%s", buf);
2507}
2508
2509// Version of fputc() that takes UTF-8 and can write Unicode to a
2510// Windows console.
2511int adb_fputc(int ch, FILE* stream) {
2512 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002513 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002514 return EOF;
2515 }
2516 // For success, fputc returns the char, cast to unsigned char, then to int.
2517 return static_cast<unsigned char>(ch);
2518}
2519
Spencer Lowf373c352015-11-15 16:29:36 -08002520// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2521int adb_putchar(int ch) {
2522 return adb_fputc(ch, stdout);
2523}
2524
2525// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2526int adb_puts(const char* buf) {
2527 // adb_printf returns -1 on error, which is conveniently the same as EOF
2528 // which puts (and hence adb_puts) should return on error.
2529 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2530 return adb_printf("%s\n", buf);
2531}
2532
Spencer Low6815c072015-05-11 01:08:48 -07002533// Internal function to write UTF-8 to a Win32 console. Returns the number of
2534// items (of length size) written. On error, returns a short item count or 0.
2535static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2536 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002537 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2538 console);
Spencer Low6815c072015-05-11 01:08:48 -07002539 if (result == -1) {
2540 return 0;
2541 }
2542 return result / size;
2543}
2544
2545// Version of fwrite() that takes UTF-8 and can write Unicode to a
2546// Windows console.
2547size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2548 const HANDLE console = _get_console_handle(stream);
2549
2550 // If there is an associated Win32 console, write to it specially,
2551 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kong86e67182018-07-13 18:15:16 -07002552 if (console != nullptr) {
Spencer Low6815c072015-05-11 01:08:48 -07002553 return _console_fwrite(ptr, size, nmemb, stream, console);
2554 } else {
2555 // If fwrite is a macro, undefine it, so we can call the real
2556 // C Runtime API.
2557#pragma push_macro("fwrite")
2558#undef fwrite
2559 return fwrite(ptr, size, nmemb, stream);
2560#pragma pop_macro("fwrite")
2561 }
2562}
2563
2564// Version of fopen() that takes a UTF-8 filename and can access a file with
2565// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002566FILE* adb_fopen(const char* path, const char* mode) {
2567 std::wstring path_wide;
2568 if (!android::base::UTF8ToWide(path, &path_wide)) {
2569 return nullptr;
2570 }
2571
2572 std::wstring mode_wide;
2573 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2574 return nullptr;
2575 }
2576
2577 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002578}
2579
Spencer Low50740f52015-09-08 17:13:04 -07002580// Return a lowercase version of the argument. Uses C Runtime tolower() on
2581// each byte which is not UTF-8 aware, and theoretically uses the current C
2582// Runtime locale (which in practice is not changed, so this becomes a ASCII
2583// conversion).
2584static std::string ToLower(const std::string& anycase) {
2585 // copy string
2586 std::string str(anycase);
2587 // transform the copy
2588 std::transform(str.begin(), str.end(), str.begin(), tolower);
2589 return str;
2590}
2591
2592extern "C" int main(int argc, char** argv);
2593
2594// Link with -municode to cause this wmain() to be used as the program
2595// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2596// regular main() with UTF-8 args.
2597extern "C" int wmain(int argc, wchar_t **argv) {
2598 // Convert args from UTF-16 to UTF-8 and pass that to main().
2599 NarrowArgs narrow_args(argc, argv);
Josh Gaoe08e0452019-06-10 12:48:34 -07002600
2601 // Avoid destructing NarrowArgs: argv might have been mutated to point to string literals.
2602 _exit(main(argc, narrow_args.data()));
Spencer Low50740f52015-09-08 17:13:04 -07002603}
2604
Spencer Low6815c072015-05-11 01:08:48 -07002605// Shadow UTF-8 environment variable name/value pairs that are created from
Spencer Lowa0903682018-08-10 16:20:57 -07002606// _wenviron by _init_env(). Note that this is not currently updated if putenv, setenv, unsetenv are
2607// called. Note that no thread synchronization is done, but we're called early enough in
Spencer Lowcc467f12015-08-02 18:13:54 -07002608// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002609static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002610
Spencer Lowa0903682018-08-10 16:20:57 -07002611// Setup shadow UTF-8 environment variables.
2612static void _init_env() {
Spencer Low6815c072015-05-11 01:08:48 -07002613 // If some name/value pairs exist, then we've already done the setup below.
2614 if (g_environ_utf8.size() != 0) {
2615 return;
2616 }
2617
Spencer Low50740f52015-09-08 17:13:04 -07002618 if (_wenviron == nullptr) {
2619 // If _wenviron is null, then -municode probably wasn't used. That
2620 // linker flag will cause the entry point to setup _wenviron. It will
2621 // also require an implementation of wmain() (which we provide above).
Elliott Hughese64126b2018-10-19 13:59:44 -07002622 LOG(FATAL) << "_wenviron is not set, did you link with -municode?";
Spencer Low50740f52015-09-08 17:13:04 -07002623 }
2624
Spencer Low6815c072015-05-11 01:08:48 -07002625 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2626 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2627 // to use the D() macro here because that tracing only works if the
2628 // ADB_TRACE environment variable is setup, but that env var can't be read
2629 // until this code completes.
2630 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2631 wchar_t* const equal = wcschr(*env, L'=');
2632 if (equal == nullptr) {
2633 // Malformed environment variable with no equal sign. Shouldn't
2634 // really happen, but we should be resilient to this.
2635 continue;
2636 }
2637
Spencer Low50f5bf12015-11-12 15:20:15 -08002638 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2639 // var because the program might never even read this particular variable.
2640 std::string name_utf8;
2641 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2642 continue;
2643 }
2644
Spencer Low50740f52015-09-08 17:13:04 -07002645 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002646 name_utf8 = ToLower(name_utf8);
2647
2648 std::string value_utf8;
2649 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2650 continue;
2651 }
2652
2653 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002654
Spencer Low50740f52015-09-08 17:13:04 -07002655 // Don't overwrite a previus env var with the same name. In reality,
2656 // the system probably won't let two env vars with the same name exist
2657 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002658 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002659 }
2660}
2661
2662// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002663// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002664char* adb_getenv(const char* name) {
Spencer Low50740f52015-09-08 17:13:04 -07002665 // Case-insensitive search by searching for lowercase name in a map of
2666 // lowercase names.
2667 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002668 if (it == g_environ_utf8.end()) {
2669 return nullptr;
2670 }
2671
2672 return it->second;
2673}
2674
2675// Version of getcwd() that returns the current working directory in UTF-8.
2676char* adb_getcwd(char* buf, int size) {
2677 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2678 if (wbuf == nullptr) {
2679 return nullptr;
2680 }
2681
Spencer Low50f5bf12015-11-12 15:20:15 -08002682 std::string buf_utf8;
2683 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002684 free(wbuf);
2685 wbuf = nullptr;
2686
Spencer Low50f5bf12015-11-12 15:20:15 -08002687 if (!narrow_result) {
2688 return nullptr;
2689 }
2690
Spencer Low6815c072015-05-11 01:08:48 -07002691 // If size was specified, make sure all the chars will fit.
2692 if (size != 0) {
2693 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2694 errno = ERANGE;
2695 return nullptr;
2696 }
2697 }
2698
2699 // If buf was not specified, allocate storage.
2700 if (buf == nullptr) {
2701 if (size == 0) {
2702 size = buf_utf8.length() + 1;
2703 }
2704 buf = reinterpret_cast<char*>(malloc(size));
2705 if (buf == nullptr) {
2706 return nullptr;
2707 }
2708 }
2709
2710 // Destination buffer was allocated with enough space, or we've already
2711 // checked an existing buffer size for enough space.
2712 strcpy(buf, buf_utf8.c_str());
2713
2714 return buf;
2715}
Spencer Lowae37a312018-09-03 16:03:22 -07002716
2717// The SetThreadDescription API was brought in version 1607 of Windows 10.
2718typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);
2719
2720// Based on PlatformThread::SetName() from
2721// https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc
2722int adb_thread_setname(const std::string& name) {
2723 // The SetThreadDescription API works even if no debugger is attached.
2724 auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(
2725 ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
2726 if (set_thread_description_func) {
2727 std::wstring name_wide;
2728 if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) {
2729 return errno;
2730 }
2731 set_thread_description_func(::GetCurrentThread(), name_wide.c_str());
2732 }
2733
2734 // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions.
2735 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017
2736
2737 return 0;
2738}
Spencer Lowa0903682018-08-10 16:20:57 -07002739
2740#if !defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2741#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
2742#endif
2743
2744#if !defined(DISABLE_NEWLINE_AUTO_RETURN)
2745#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
2746#endif
2747
2748static void _init_console() {
2749 DWORD old_out_console_mode;
2750
2751 const HANDLE out = _get_console_handle(STDOUT_FILENO, &old_out_console_mode);
2752 if (out == nullptr) {
2753 return;
2754 }
2755
2756 // Try to use ENABLE_VIRTUAL_TERMINAL_PROCESSING on the output console to process virtual
2757 // terminal sequences on newer versions of Windows 10 and later.
2758 // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
2759 // On older OSes that don't support the flag, SetConsoleMode() will return an error.
2760 // ENABLE_VIRTUAL_TERMINAL_PROCESSING also solves a problem where the last column of the
2761 // console cannot be overwritten.
2762 //
2763 // Note that we don't use DISABLE_NEWLINE_AUTO_RETURN because it doesn't seem to be necessary.
2764 // If we use DISABLE_NEWLINE_AUTO_RETURN, _console_write_utf8() would need to be modified to
2765 // translate \n to \r\n.
2766 if (!SetConsoleMode(out, old_out_console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
2767 return;
2768 }
2769
2770 // If SetConsoleMode() succeeded, the console supports virtual terminal processing, so we
2771 // should set the TERM env var to match so that it will be propagated to adbd on devices.
2772 //
2773 // Below's direct manipulation of env vars and not g_environ_utf8 assumes that _init_env() has
2774 // not yet been called. If this fails, _init_env() should be called after _init_console().
2775 if (g_environ_utf8.size() > 0) {
2776 LOG(FATAL) << "environment variables have already been converted to UTF-8";
2777 }
2778
2779#pragma push_macro("getenv")
2780#undef getenv
2781#pragma push_macro("putenv")
2782#undef putenv
2783 if (getenv("TERM") == nullptr) {
2784 // This is the same TERM value used by Gnome Terminal and the version of ssh included with
2785 // Windows.
2786 putenv("TERM=xterm-256color");
2787 }
2788#pragma pop_macro("putenv")
2789#pragma pop_macro("getenv")
2790}
2791
2792static bool _init_sysdeps() {
2793 // _init_console() depends on _init_env() not being called yet.
2794 _init_console();
2795 _init_env();
2796 _init_winsock();
2797 return true;
2798}
2799
2800static bool _sysdeps_init = _init_sysdeps();