blob: d9cc36f831fd75f9fe0cf25af37be45ff63442bd [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);
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -070063 intptr_t (*_fh_get_os_handle)(FH);
Elliott Hughes6a096932015-04-16 16:47:02 -070064} FHClassRec;
65
66static void _fh_file_init(FH);
67static int _fh_file_close(FH);
Elliott Hughes9dcbc212018-09-20 13:59:49 -070068static int64_t _fh_file_lseek(FH, int64_t, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070069static int _fh_file_read(FH, void*, int);
70static int _fh_file_write(FH, const void*, int);
Josh Gao1bbdd252018-04-05 17:55:25 -070071static int _fh_file_writev(FH, const adb_iovec*, int);
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -070072static intptr_t _fh_file_get_os_handle(FH f);
Elliott Hughes6a096932015-04-16 16:47:02 -070073
74static const FHClassRec _fh_file_class = {
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -070075 _fh_file_init, _fh_file_close, _fh_file_lseek, _fh_file_read,
76 _fh_file_write, _fh_file_writev, _fh_file_get_os_handle,
Elliott Hughes6a096932015-04-16 16:47:02 -070077};
78
79static void _fh_socket_init(FH);
80static int _fh_socket_close(FH);
Elliott Hughes9dcbc212018-09-20 13:59:49 -070081static int64_t _fh_socket_lseek(FH, int64_t, int);
Elliott Hughes6a096932015-04-16 16:47:02 -070082static int _fh_socket_read(FH, void*, int);
83static int _fh_socket_write(FH, const void*, int);
Josh Gao1bbdd252018-04-05 17:55:25 -070084static int _fh_socket_writev(FH, const adb_iovec*, int);
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -070085static intptr_t _fh_socket_get_os_handle(FH f);
Elliott Hughes6a096932015-04-16 16:47:02 -070086
87static const FHClassRec _fh_socket_class = {
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -070088 _fh_socket_init, _fh_socket_close, _fh_socket_lseek, _fh_socket_read,
89 _fh_socket_write, _fh_socket_writev, _fh_socket_get_os_handle,
Elliott Hughes6a096932015-04-16 16:47:02 -070090};
91
Pirama Arumuga Nainar5231aff2018-08-08 10:33:24 -070092#if defined(assert)
93#undef assert
94#endif
95
Spencer Low2bbb3a92015-08-26 18:46:09 -070096void handle_deleter::operator()(HANDLE h) {
97 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
98 // implying that NULL is a valid handle, but this is probably impossible.
99 // Other APIs like CreateEvent() are documented to return NULL on error,
100 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
101 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
102 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
103 // only need to check for INVALID_HANDLE_VALUE.
104 if (h != INVALID_HANDLE_VALUE) {
105 if (!CloseHandle(h)) {
Yabin Cui815ad882015-09-02 17:44:28 -0700106 D("CloseHandle(%p) failed: %s", h,
David Pursellc573d522016-01-27 08:52:53 -0800107 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2bbb3a92015-08-26 18:46:09 -0700108 }
109 }
110}
111
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800112/**************************************************************************/
113/**************************************************************************/
114/***** *****/
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800115/***** common file descriptor handling *****/
116/***** *****/
117/**************************************************************************/
118/**************************************************************************/
119
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800120typedef struct FHRec_
121{
122 FHClass clazz;
123 int used;
124 int eof;
125 union {
126 HANDLE handle;
127 SOCKET socket;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800128 } u;
129
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800130 char name[32];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800131} FHRec;
132
133#define fh_handle u.handle
134#define fh_socket u.socket
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800135
Josh Gao4f657a72016-02-17 16:45:39 -0800136#define WIN32_FH_BASE 2048
Josh Gao7c9e5fb2016-04-18 11:09:28 -0700137#define WIN32_MAX_FHS 2048
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800138
Josh Gaoe7daf572016-09-21 12:37:10 -0700139static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800140static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowb732a372015-07-24 15:38:19 -0700141static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800142
Josh Gao90228a62019-04-25 14:04:57 -0700143static FH _fh_from_int(borrowed_fd bfd, const char* func) {
144 FH f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800145
Josh Gao90228a62019-04-25 14:04:57 -0700146 int fd = bfd.get();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800147 fd -= WIN32_FH_BASE;
148
Spencer Lowb732a372015-07-24 15:38:19 -0700149 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Josh Gao90228a62019-04-25 14:04:57 -0700150 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 -0800151 errno = EBADF;
Yi Kong86e67182018-07-13 18:15:16 -0700152 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800153 }
154
155 f = &_win32_fhs[fd];
156
157 if (f->used == 0) {
Josh Gao90228a62019-04-25 14:04:57 -0700158 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 -0800159 errno = EBADF;
Yi Kong86e67182018-07-13 18:15:16 -0700160 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800161 }
162
163 return f;
164}
165
Josh Gao90228a62019-04-25 14:04:57 -0700166static int _fh_to_int(FH f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800167 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
168 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
169
170 return -1;
171}
172
Josh Gao90228a62019-04-25 14:04:57 -0700173static FH _fh_alloc(FHClass clazz) {
174 FH f = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800175
Josh Gaoe7daf572016-09-21 12:37:10 -0700176 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800177
Josh Gao4f657a72016-02-17 16:45:39 -0800178 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
Yi Kong86e67182018-07-13 18:15:16 -0700179 if (_win32_fhs[i].clazz == nullptr) {
Josh Gao4f657a72016-02-17 16:45:39 -0800180 f = &_win32_fhs[i];
181 _win32_fh_next = i + 1;
Josh Gaoe7daf572016-09-21 12:37:10 -0700182 f->clazz = clazz;
183 f->used = 1;
184 f->eof = 0;
185 f->name[0] = '\0';
186 clazz->_fh_init(f);
187 return f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800188 }
189 }
Josh Gaoe7daf572016-09-21 12:37:10 -0700190
191 D("_fh_alloc: no more free file descriptors");
192 errno = EMFILE; // Too many open files
193 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800194}
195
Josh Gao90228a62019-04-25 14:04:57 -0700196static int _fh_close(FH f) {
Spencer Lowb732a372015-07-24 15:38:19 -0700197 // Use lock so that closing only happens once and so that _fh_alloc can't
198 // allocate a FH that we're in the middle of closing.
Josh Gaoe7daf572016-09-21 12:37:10 -0700199 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gao4f657a72016-02-17 16:45:39 -0800200
201 int offset = f - _win32_fhs;
202 if (_win32_fh_next > offset) {
203 _win32_fh_next = offset;
204 }
205
Spencer Lowb732a372015-07-24 15:38:19 -0700206 if (f->used) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800207 f->clazz->_fh_close( f );
Spencer Lowb732a372015-07-24 15:38:19 -0700208 f->name[0] = '\0';
209 f->eof = 0;
210 f->used = 0;
Yi Kong86e67182018-07-13 18:15:16 -0700211 f->clazz = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800212 }
213 return 0;
214}
215
Spencer Low753d4852015-07-30 23:07:55 -0700216// Deleter for unique_fh.
217class fh_deleter {
218 public:
219 void operator()(struct FHRec_* fh) {
220 // We're called from a destructor and destructors should not overwrite
221 // errno because callers may do:
222 // errno = EBLAH;
223 // return -1; // calls destructor, which should not overwrite errno
224 const int saved_errno = errno;
225 _fh_close(fh);
226 errno = saved_errno;
227 }
228};
229
230// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
231typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
232
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800233/**************************************************************************/
234/**************************************************************************/
235/***** *****/
236/***** file-based descriptor handling *****/
237/***** *****/
238/**************************************************************************/
239/**************************************************************************/
240
Josh Gao1bbdd252018-04-05 17:55:25 -0700241static void _fh_file_init(FH f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800242 f->fh_handle = INVALID_HANDLE_VALUE;
243}
244
Josh Gao1bbdd252018-04-05 17:55:25 -0700245static int _fh_file_close(FH f) {
246 CloseHandle(f->fh_handle);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800247 f->fh_handle = INVALID_HANDLE_VALUE;
248 return 0;
249}
250
Josh Gao1bbdd252018-04-05 17:55:25 -0700251static int _fh_file_read(FH f, void* buf, int len) {
252 DWORD read_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800253
Yi Kong86e67182018-07-13 18:15:16 -0700254 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700255 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800256 errno = EIO;
257 return -1;
258 } else if (read_bytes < (DWORD)len) {
259 f->eof = 1;
260 }
Josh Gao1bbdd252018-04-05 17:55:25 -0700261 return read_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800262}
263
Josh Gao1bbdd252018-04-05 17:55:25 -0700264static int _fh_file_write(FH f, const void* buf, int len) {
265 DWORD wrote_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800266
Yi Kong86e67182018-07-13 18:15:16 -0700267 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700268 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800269 errno = EIO;
270 return -1;
271 } else if (wrote_bytes < (DWORD)len) {
272 f->eof = 1;
273 }
Josh Gao1bbdd252018-04-05 17:55:25 -0700274 return wrote_bytes;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800275}
276
Josh Gao1bbdd252018-04-05 17:55:25 -0700277static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
278 if (iovcnt <= 0) {
279 errno = EINVAL;
280 return -1;
281 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800282
Josh Gao1bbdd252018-04-05 17:55:25 -0700283 DWORD wrote_bytes = 0;
284
285 for (int i = 0; i < iovcnt; ++i) {
286 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
287 if (rc == -1) {
288 return wrote_bytes > 0 ? wrote_bytes : -1;
289 } else if (rc == 0) {
290 return wrote_bytes;
291 }
292
293 wrote_bytes += rc;
294
295 if (static_cast<size_t>(rc) < iov[i].iov_len) {
296 return wrote_bytes;
297 }
298 }
299
300 return wrote_bytes;
301}
302
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700303static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700304 DWORD method;
Josh Gao1bbdd252018-04-05 17:55:25 -0700305 switch (origin) {
306 case SEEK_SET:
307 method = FILE_BEGIN;
308 break;
309 case SEEK_CUR:
310 method = FILE_CURRENT;
311 break;
312 case SEEK_END:
313 method = FILE_END;
314 break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800315 default:
316 errno = EINVAL;
317 return -1;
318 }
319
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700320 LARGE_INTEGER li = {.QuadPart = pos};
321 if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800322 errno = EIO;
323 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800324 }
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700325 f->eof = 0;
326 return li.QuadPart;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800327}
328
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -0700329static intptr_t _fh_file_get_os_handle(FH f) {
330 return reinterpret_cast<intptr_t>(f->u.handle);
331}
332
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800333/**************************************************************************/
334/**************************************************************************/
335/***** *****/
336/***** file-based descriptor handling *****/
337/***** *****/
338/**************************************************************************/
339/**************************************************************************/
340
Josh Gao08229f62018-04-05 18:09:02 -0700341int adb_open(const char* path, int options) {
342 FH f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800343
Josh Gao08229f62018-04-05 18:09:02 -0700344 DWORD desiredAccess = 0;
345 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800346
Josh Gao3befb592019-02-07 14:13:39 -0800347 // CreateFileW is inherently O_CLOEXEC by default.
348 options &= ~O_CLOEXEC;
349
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800350 switch (options) {
351 case O_RDONLY:
352 desiredAccess = GENERIC_READ;
353 break;
354 case O_WRONLY:
355 desiredAccess = GENERIC_WRITE;
356 break;
357 case O_RDWR:
358 desiredAccess = GENERIC_READ | GENERIC_WRITE;
359 break;
360 default:
Yabin Cui815ad882015-09-02 17:44:28 -0700361 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800362 errno = EINVAL;
363 return -1;
364 }
365
Josh Gao08229f62018-04-05 18:09:02 -0700366 f = _fh_alloc(&_fh_file_class);
367 if (!f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800368 return -1;
369 }
370
Spencer Low50f5bf12015-11-12 15:20:15 -0800371 std::wstring path_wide;
372 if (!android::base::UTF8ToWide(path, &path_wide)) {
373 return -1;
374 }
Josh Gao08229f62018-04-05 18:09:02 -0700375 f->fh_handle =
Yi Kong86e67182018-07-13 18:15:16 -0700376 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800377
Josh Gao08229f62018-04-05 18:09:02 -0700378 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700379 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800380 _fh_close(f);
Josh Gao08229f62018-04-05 18:09:02 -0700381 D("adb_open: could not open '%s': ", path);
Spencer Low5c761bd2015-07-21 02:06:26 -0700382 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800383 case ERROR_FILE_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700384 D("file not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800385 errno = ENOENT;
386 return -1;
387
388 case ERROR_PATH_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700389 D("path not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800390 errno = ENOTDIR;
391 return -1;
392
393 default:
David Pursellc573d522016-01-27 08:52:53 -0800394 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800395 errno = ENOENT;
396 return -1;
397 }
398 }
Vladimir Chtchetkineb87b8282011-11-30 10:20:27 -0800399
Josh Gao08229f62018-04-05 18:09:02 -0700400 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
401 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800402 return _fh_to_int(f);
403}
404
405/* ignore mode on Win32 */
Josh Gao08229f62018-04-05 18:09:02 -0700406int adb_creat(const char* path, int mode) {
407 FH f;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800408
Josh Gao08229f62018-04-05 18:09:02 -0700409 f = _fh_alloc(&_fh_file_class);
410 if (!f) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800411 return -1;
412 }
413
Spencer Low50f5bf12015-11-12 15:20:15 -0800414 std::wstring path_wide;
415 if (!android::base::UTF8ToWide(path, &path_wide)) {
416 return -1;
417 }
Josh Gao08229f62018-04-05 18:09:02 -0700418 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
Yi Kong86e67182018-07-13 18:15:16 -0700419 nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800420
Josh Gao08229f62018-04-05 18:09:02 -0700421 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low5c761bd2015-07-21 02:06:26 -0700422 const DWORD err = GetLastError();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800423 _fh_close(f);
Josh Gao08229f62018-04-05 18:09:02 -0700424 D("adb_creat: could not open '%s': ", path);
Spencer Low5c761bd2015-07-21 02:06:26 -0700425 switch (err) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800426 case ERROR_FILE_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700427 D("file not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800428 errno = ENOENT;
429 return -1;
430
431 case ERROR_PATH_NOT_FOUND:
Josh Gao08229f62018-04-05 18:09:02 -0700432 D("path not found");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800433 errno = ENOTDIR;
434 return -1;
435
436 default:
David Pursellc573d522016-01-27 08:52:53 -0800437 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800438 errno = ENOENT;
439 return -1;
440 }
441 }
Josh Gao08229f62018-04-05 18:09:02 -0700442 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
443 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800444 return _fh_to_int(f);
445}
446
Josh Gao90228a62019-04-25 14:04:57 -0700447int adb_read(borrowed_fd fd, void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700448 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800449
Yi Kong86e67182018-07-13 18:15:16 -0700450 if (f == nullptr) {
Josh Gaode165962018-04-05 18:09:39 -0700451 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800452 return -1;
453 }
454
Josh Gao1bbdd252018-04-05 17:55:25 -0700455 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800456}
457
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -0700458int adb_pread(borrowed_fd fd, void* buf, int len, off64_t offset) {
459 OVERLAPPED overlapped = {};
460 overlapped.Offset = static_cast<DWORD>(offset);
461 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
462 DWORD bytes_read;
463 if (!::ReadFile(adb_get_os_handle(fd), buf, static_cast<DWORD>(len), &bytes_read,
464 &overlapped)) {
465 D("adb_pread: could not read %d bytes from FD %d", len, fd.get());
466 switch (::GetLastError()) {
467 case ERROR_IO_PENDING:
468 errno = EAGAIN;
469 return -1;
470 default:
471 errno = EINVAL;
472 return -1;
473 }
474 }
475 return static_cast<int>(bytes_read);
476}
477
Josh Gao90228a62019-04-25 14:04:57 -0700478int adb_write(borrowed_fd fd, const void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700479 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800480
Yi Kong86e67182018-07-13 18:15:16 -0700481 if (f == nullptr) {
Josh Gaode165962018-04-05 18:09:39 -0700482 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483 return -1;
484 }
485
486 return f->clazz->_fh_write(f, buf, len);
487}
488
Josh Gao90228a62019-04-25 14:04:57 -0700489ssize_t adb_writev(borrowed_fd fd, const adb_iovec* iov, int iovcnt) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700490 FH f = _fh_from_int(fd, __func__);
491
Yi Kong86e67182018-07-13 18:15:16 -0700492 if (f == nullptr) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700493 errno = EBADF;
494 return -1;
495 }
496
497 return f->clazz->_fh_writev(f, iov, iovcnt);
498}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800499
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -0700500int adb_pwrite(borrowed_fd fd, const void* buf, int len, off64_t offset) {
501 OVERLAPPED params = {};
502 params.Offset = static_cast<DWORD>(offset);
503 params.OffsetHigh = static_cast<DWORD>(offset >> 32);
504 DWORD bytes_written = 0;
505 if (!::WriteFile(adb_get_os_handle(fd), buf, len, &bytes_written, &params)) {
506 D("adb_pwrite: could not write %d bytes to FD %d", len, fd.get());
507 switch (::GetLastError()) {
508 case ERROR_IO_PENDING:
509 errno = EAGAIN;
510 return -1;
511 default:
512 errno = EINVAL;
513 return -1;
514 }
515 }
516 return static_cast<int>(bytes_written);
517}
518
Josh Gao90228a62019-04-25 14:04:57 -0700519int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where) {
Josh Gao08229f62018-04-05 18:09:02 -0700520 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800521 if (!f) {
Josh Gaode165962018-04-05 18:09:39 -0700522 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800523 return -1;
524 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800525 return f->clazz->_fh_lseek(f, pos, where);
526}
527
Josh Gao08229f62018-04-05 18:09:02 -0700528int adb_close(int fd) {
529 FH f = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800530
531 if (!f) {
Josh Gaode165962018-04-05 18:09:39 -0700532 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800533 return -1;
534 }
535
Josh Gao08229f62018-04-05 18:09:02 -0700536 D("adb_close: %s", f->name);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800537 _fh_close(f);
538 return 0;
539}
540
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -0700541HANDLE adb_get_os_handle(borrowed_fd fd) {
542 FH f = _fh_from_int(fd, __func__);
543
544 if (!f) {
545 errno = EBADF;
546 return nullptr;
547 }
548
549 D("adb_get_os_handle: %s", f->name);
550 const intptr_t intptr_handle = f->clazz->_fh_get_os_handle(f);
551 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
552 return handle;
553}
554
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800555/**************************************************************************/
556/**************************************************************************/
557/***** *****/
558/***** socket-based file descriptors *****/
559/***** *****/
560/**************************************************************************/
561/**************************************************************************/
562
Spencer Low31aafa62015-01-25 14:40:16 -0800563#undef setsockopt
564
Spencer Low753d4852015-07-30 23:07:55 -0700565static void _socket_set_errno( const DWORD err ) {
Spencer Low028e1592015-10-18 16:45:09 -0700566 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
567 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gao75e96bb2016-12-05 13:24:48 -0800568 // are mapped to strings by adb_strerror().
Spencer Low753d4852015-07-30 23:07:55 -0700569 switch ( err ) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800570 case 0: errno = 0; break;
Spencer Low028e1592015-10-18 16:45:09 -0700571 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
572 // case WSAEINTR: errno = EINTR; break;
573 case WSAEFAULT: errno = EFAULT; break;
574 case WSAEINVAL: errno = EINVAL; break;
575 case WSAEMFILE: errno = EMFILE; break;
Spencer Low32625852015-08-11 16:45:32 -0700576 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
577 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
578 // callers check specifically for EAGAIN.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800579 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low028e1592015-10-18 16:45:09 -0700580 case WSAENOTSOCK: errno = ENOTSOCK; break;
581 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
582 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
583 case WSAENETDOWN: errno = ENETDOWN; break;
584 case WSAENETRESET: errno = ENETRESET; break;
585 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
586 // to use EPIPE for these situations and there are some callers that look
587 // for EPIPE.
588 case WSAECONNABORTED: errno = EPIPE; break;
589 case WSAECONNRESET: errno = ECONNRESET; break;
590 case WSAENOBUFS: errno = ENOBUFS; break;
591 case WSAENOTCONN: errno = ENOTCONN; break;
592 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
593 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
594 // considerations: Reportedly send() can return zero on timeout, and POSIX
595 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
596 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
597 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800598 default:
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800599 errno = EINVAL;
Yabin Cui815ad882015-09-02 17:44:28 -0700600 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low753d4852015-07-30 23:07:55 -0700601 err, errno );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800602 }
603}
604
Josh Gaoe7388122016-02-16 17:34:53 -0800605extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
606 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
607 int skipped = 0;
608 std::vector<WSAPOLLFD> sockets;
609 std::vector<adb_pollfd*> original;
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700610
Josh Gaoe7388122016-02-16 17:34:53 -0800611 for (size_t i = 0; i < nfds; ++i) {
612 FH fh = _fh_from_int(fds[i].fd, __func__);
613 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
614 D("adb_poll received bad FD %d", fds[i].fd);
615 fds[i].revents = POLLNVAL;
616 ++skipped;
617 } else {
618 WSAPOLLFD wsapollfd = {
619 .fd = fh->u.socket,
620 .events = static_cast<short>(fds[i].events)
621 };
622 sockets.push_back(wsapollfd);
623 original.push_back(&fds[i]);
624 }
Spencer Low753d4852015-07-30 23:07:55 -0700625 }
Josh Gaoe7388122016-02-16 17:34:53 -0800626
627 if (sockets.empty()) {
628 return skipped;
629 }
630
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700631 // If we have any invalid FDs in our FD set, make sure to return immediately.
632 if (skipped > 0) {
633 timeout = 0;
634 }
635
Josh Gaoe7388122016-02-16 17:34:53 -0800636 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
637 if (result == SOCKET_ERROR) {
638 _socket_set_errno(WSAGetLastError());
639 return -1;
640 }
641
642 // Map the results back onto the original set.
643 for (size_t i = 0; i < sockets.size(); ++i) {
644 original[i]->revents = sockets[i].revents;
645 }
646
Josh Gaobe2ee7b2018-03-29 12:34:28 -0700647 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gaoe7388122016-02-16 17:34:53 -0800648 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
649 // to do. Ignore its result and calculate the proper return value.
650 result = 0;
651 for (size_t i = 0; i < nfds; ++i) {
652 if (fds[i].revents != 0) {
653 ++result;
654 }
655 }
656 return result;
657}
658
659static void _fh_socket_init(FH f) {
660 f->fh_socket = INVALID_SOCKET;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800661}
662
Josh Gao1bbdd252018-04-05 17:55:25 -0700663static int _fh_socket_close(FH f) {
Spencer Low753d4852015-07-30 23:07:55 -0700664 if (f->fh_socket != INVALID_SOCKET) {
Spencer Low753d4852015-07-30 23:07:55 -0700665 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800666 // Don't set errno here, since adb_close will ignore it.
667 const DWORD err = WSAGetLastError();
668 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -0700669 }
670 f->fh_socket = INVALID_SOCKET;
671 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800672 return 0;
673}
674
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700675static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800676 errno = EPIPE;
677 return -1;
678}
679
Elliott Hughes6a096932015-04-16 16:47:02 -0700680static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700681 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800682 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700683 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700684 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
685 // that to reduce spam and confusion.
686 if (err != WSAEWOULDBLOCK) {
Yabin Cui815ad882015-09-02 17:44:28 -0700687 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800688 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low32625852015-08-11 16:45:32 -0700689 }
Spencer Low753d4852015-07-30 23:07:55 -0700690 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800691 result = -1;
692 }
Josh Gao1bbdd252018-04-05 17:55:25 -0700693 return result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800694}
695
Elliott Hughes6a096932015-04-16 16:47:02 -0700696static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao1bbdd252018-04-05 17:55:25 -0700697 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800698 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -0700699 const DWORD err = WSAGetLastError();
Spencer Low028e1592015-10-18 16:45:09 -0700700 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
701 // that to reduce spam and confusion.
702 if (err != WSAEWOULDBLOCK) {
703 D("send fd %d failed: %s", _fh_to_int(f),
David Pursellc573d522016-01-27 08:52:53 -0800704 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low028e1592015-10-18 16:45:09 -0700705 }
Spencer Low753d4852015-07-30 23:07:55 -0700706 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800707 result = -1;
Spencer Lowc7c45612015-09-29 15:05:29 -0700708 } else {
709 // According to https://code.google.com/p/chromium/issues/detail?id=27870
710 // Winsock Layered Service Providers may cause this.
Josh Gao1bbdd252018-04-05 17:55:25 -0700711 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
712 << result << " bytes reportedly written";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800713 }
714 return result;
715}
716
Josh Gao1bbdd252018-04-05 17:55:25 -0700717// Make sure that adb_iovec is compatible with WSABUF.
718static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
719static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
720static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
721
722static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
723static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
724
725static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
726 if (iovcnt <= 0) {
727 errno = EINVAL;
728 return -1;
729 }
730
731 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
732 DWORD bytes_written = 0;
733 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
734 if (result == SOCKET_ERROR) {
735 const DWORD err = WSAGetLastError();
736 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
737 // that to reduce spam and confusion.
738 if (err != WSAEWOULDBLOCK) {
739 D("send fd %d failed: %s", _fh_to_int(f),
740 android::base::SystemErrorCodeToString(err).c_str());
741 }
742 _socket_set_errno(err);
Josh Gaoee977a32019-08-07 18:26:47 -0700743 return -1;
Josh Gao1bbdd252018-04-05 17:55:25 -0700744 }
745 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
746 return static_cast<int>(bytes_written);
747}
748
Yurii Zubrytskyi243d2482019-07-10 17:59:34 -0700749static intptr_t _fh_socket_get_os_handle(FH f) {
750 return f->u.socket;
751}
752
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800753/**************************************************************************/
754/**************************************************************************/
755/***** *****/
756/***** replacement for libs/cutils/socket_xxxx.c *****/
757/***** *****/
758/**************************************************************************/
759/**************************************************************************/
760
Spencer Lowa0903682018-08-10 16:20:57 -0700761static void _init_winsock() {
Josh Gaocaeda2c2018-04-05 18:10:03 -0700762 static std::once_flag once;
763 std::call_once(once, []() {
764 WSADATA wsaData;
765 int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800766 if (rc != 0) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700767 LOG(FATAL) << "could not initialize Winsock: "
768 << android::base::SystemErrorCodeToString(rc);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800769 }
Spencer Lowc7c1ca62015-08-12 18:19:16 -0700770
771 // Note that we do not call atexit() to register WSACleanup to be called
772 // at normal process termination because:
773 // 1) When exit() is called, there are still threads actively using
774 // Winsock because we don't cleanly shutdown all threads, so it
775 // doesn't make sense to call WSACleanup() and may cause problems
776 // with those threads.
777 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
778 // calls WSACleanup() which tries to unload a DLL, which tries to
779 // grab the LoaderLock. This conflicts with the device_poll_thread
780 // which holds the LoaderLock because AdbWinApi.dll calls
781 // setupapi.dll which tries to load wintrust.dll which tries to load
782 // crypt32.dll which calls atexit() which tries to acquire the C
783 // Runtime lock that the other thread holds.
Josh Gaocaeda2c2018-04-05 18:10:03 -0700784 });
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800785}
786
Spencer Lowc7c45612015-09-29 15:05:29 -0700787// Map a socket type to an explicit socket protocol instead of using the socket
788// protocol of 0. Explicit socket protocols are used by most apps and we should
789// do the same to reduce the chance of exercising uncommon code-paths that might
790// have problems or that might load different Winsock service providers that
791// have problems.
792static int GetSocketProtocolFromSocketType(int type) {
793 switch (type) {
794 case SOCK_STREAM:
795 return IPPROTO_TCP;
796 case SOCK_DGRAM:
797 return IPPROTO_UDP;
798 default:
799 LOG(FATAL) << "Unknown socket type: " << type;
800 return 0;
801 }
802}
803
Spencer Low753d4852015-07-30 23:07:55 -0700804int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800805 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800806 SOCKET s;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800807
Josh Gao61eda8d2016-02-18 13:43:55 -0800808 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low753d4852015-07-30 23:07:55 -0700809 if (!f) {
810 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800811 return -1;
Spencer Low753d4852015-07-30 23:07:55 -0700812 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800813
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800814 memset(&addr, 0, sizeof(addr));
815 addr.sin_family = AF_INET;
816 addr.sin_port = htons(port);
817 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
818
Spencer Lowc7c45612015-09-29 15:05:29 -0700819 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao61eda8d2016-02-18 13:43:55 -0800820 if (s == INVALID_SOCKET) {
821 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700822 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800823 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700824 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800825 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700826 return -1;
827 }
828 f->fh_socket = s;
829
Josh Gao61eda8d2016-02-18 13:43:55 -0800830 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700831 // Save err just in case inet_ntoa() or ntohs() changes the last error.
832 const DWORD err = WSAGetLastError();
833 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800834 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
835 android::base::SystemErrorCodeToString(err).c_str());
836 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
837 error->c_str());
838 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800839 return -1;
840 }
841
Spencer Low753d4852015-07-30 23:07:55 -0700842 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800843 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
844 port);
845 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700846 f.release();
847 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800848}
849
Spencer Low753d4852015-07-30 23:07:55 -0700850// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao61eda8d2016-02-18 13:43:55 -0800851static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800852 struct sockaddr_in addr;
Josh Gao61eda8d2016-02-18 13:43:55 -0800853 SOCKET s;
854 int n;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800855
Josh Gao61eda8d2016-02-18 13:43:55 -0800856 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800857 if (!f) {
Spencer Low753d4852015-07-30 23:07:55 -0700858 *error = strerror(errno);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800859 return -1;
860 }
861
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800862 memset(&addr, 0, sizeof(addr));
863 addr.sin_family = AF_INET;
864 addr.sin_port = htons(port);
Spencer Low753d4852015-07-30 23:07:55 -0700865 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800866
Spencer Low753d4852015-07-30 23:07:55 -0700867 // TODO: Consider using dual-stack socket that can simultaneously listen on
868 // IPv4 and IPv6.
Spencer Lowc7c45612015-09-29 15:05:29 -0700869 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low753d4852015-07-30 23:07:55 -0700870 if (s == INVALID_SOCKET) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800871 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700872 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800873 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700874 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800875 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700876 return -1;
877 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800878
879 f->fh_socket = s;
880
Spencer Low32625852015-08-11 16:45:32 -0700881 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
882 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800883 n = 1;
Josh Gao61eda8d2016-02-18 13:43:55 -0800884 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
885 const DWORD err = WSAGetLastError();
886 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
887 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700888 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800889 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -0700890 return -1;
891 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800892
Josh Gao61eda8d2016-02-18 13:43:55 -0800893 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700894 // Save err just in case inet_ntoa() or ntohs() changes the last error.
895 const DWORD err = WSAGetLastError();
Josh Gao61eda8d2016-02-18 13:43:55 -0800896 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
897 ntohs(addr.sin_port),
898 android::base::SystemErrorCodeToString(err).c_str());
899 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
900 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800901 return -1;
902 }
903 if (type == SOCK_STREAM) {
Josh Gaoa076b152018-03-20 14:25:03 -0700904 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800905 const DWORD err = WSAGetLastError();
906 *error = android::base::StringPrintf(
907 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
908 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
909 error->c_str());
910 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800911 return -1;
912 }
913 }
Spencer Low753d4852015-07-30 23:07:55 -0700914 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800915 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
916 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
917 port);
918 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low753d4852015-07-30 23:07:55 -0700919 f.release();
920 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800921}
922
Callum Ryan04efea32019-10-31 07:21:42 -0700923int network_loopback_server(int port, int type, std::string* error, bool prefer_ipv4) {
924 // TODO implement IPv6 support on windows
Spencer Low753d4852015-07-30 23:07:55 -0700925 return _network_server(port, type, INADDR_LOOPBACK, error);
926}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800927
Spencer Low753d4852015-07-30 23:07:55 -0700928int network_inaddr_any_server(int port, int type, std::string* error) {
929 return _network_server(port, type, INADDR_ANY, error);
930}
931
932int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
933 unique_fh f(_fh_alloc(&_fh_socket_class));
934 if (!f) {
935 *error = strerror(errno);
936 return -1;
937 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800938
Spencer Low753d4852015-07-30 23:07:55 -0700939 struct addrinfo hints;
940 memset(&hints, 0, sizeof(hints));
941 hints.ai_family = AF_UNSPEC;
942 hints.ai_socktype = type;
Spencer Lowc7c45612015-09-29 15:05:29 -0700943 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low753d4852015-07-30 23:07:55 -0700944
945 char port_str[16];
946 snprintf(port_str, sizeof(port_str), "%d", port);
947
948 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowcc467f12015-08-02 18:13:54 -0700949
950#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao61eda8d2016-02-18 13:43:55 -0800951// TODO: When the Android SDK tools increases the Windows system
952// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowcc467f12015-08-02 18:13:54 -0700953#else
Josh Gao61eda8d2016-02-18 13:43:55 -0800954// Otherwise, keep using getaddrinfo(), or do runtime API detection
955// with GetProcAddress("GetAddrInfoW").
Spencer Lowcc467f12015-08-02 18:13:54 -0700956#endif
Spencer Low753d4852015-07-30 23:07:55 -0700957 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -0800958 const DWORD err = WSAGetLastError();
959 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
960 host.c_str(), port_str,
961 android::base::SystemErrorCodeToString(err).c_str());
962
Yabin Cui815ad882015-09-02 17:44:28 -0700963 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800964 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800965 return -1;
966 }
Elliott Hughes8ac45992016-08-08 12:52:37 -0700967 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low753d4852015-07-30 23:07:55 -0700968 addrinfo_ptr = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800969
Spencer Low753d4852015-07-30 23:07:55 -0700970 // TODO: Try all the addresses if there's more than one? This just uses
971 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
972 // which tries all addresses, takes a timeout and more.
Josh Gao61eda8d2016-02-18 13:43:55 -0800973 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
974 if (s == INVALID_SOCKET) {
975 const DWORD err = WSAGetLastError();
Spencer Low32625852015-08-11 16:45:32 -0700976 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao61eda8d2016-02-18 13:43:55 -0800977 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui815ad882015-09-02 17:44:28 -0700978 D("%s", error->c_str());
Josh Gao61eda8d2016-02-18 13:43:55 -0800979 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800980 return -1;
981 }
982 f->fh_socket = s;
983
Spencer Low753d4852015-07-30 23:07:55 -0700984 // TODO: Implement timeouts for Windows. Seems like the default in theory
985 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao61eda8d2016-02-18 13:43:55 -0800986 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Low32625852015-08-11 16:45:32 -0700987 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao61eda8d2016-02-18 13:43:55 -0800988 const DWORD err = WSAGetLastError();
989 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
990 android::base::SystemErrorCodeToString(err).c_str());
991 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
992 port_str, error->c_str());
993 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800994 return -1;
995 }
996
Spencer Low753d4852015-07-30 23:07:55 -0700997 const int fd = _fh_to_int(f.get());
Josh Gao61eda8d2016-02-18 13:43:55 -0800998 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
999 port);
1000 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
1001 fd);
Spencer Low753d4852015-07-30 23:07:55 -07001002 f.release();
1003 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001004}
1005
Josh Gao08229f62018-04-05 18:09:02 -07001006int adb_register_socket(SOCKET s) {
1007 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin20238f22016-09-21 14:03:39 -07001008 f->fh_socket = s;
1009 return _fh_to_int(f);
1010}
1011
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001012#undef accept
Josh Gao90228a62019-04-25 14:04:57 -07001013int adb_socket_accept(borrowed_fd serverfd, struct sockaddr* addr, socklen_t* addrlen) {
Josh Gao08229f62018-04-05 18:09:02 -07001014 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001015
Josh Gao08229f62018-04-05 18:09:02 -07001016 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001017 D("adb_socket_accept: invalid fd %d", serverfd.get());
Spencer Low753d4852015-07-30 23:07:55 -07001018 errno = EBADF;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001019 return -1;
1020 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001021
Josh Gao08229f62018-04-05 18:09:02 -07001022 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001023 if (!fh) {
Spencer Low753d4852015-07-30 23:07:55 -07001024 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1025 "descriptor";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001026 return -1;
1027 }
1028
Josh Gao08229f62018-04-05 18:09:02 -07001029 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001030 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low5c761bd2015-07-21 02:06:26 -07001031 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001032 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd.get()
Josh Gao08229f62018-04-05 18:09:02 -07001033 << " failed: " + android::base::SystemErrorCodeToString(err);
1034 _socket_set_errno(err);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001035 return -1;
1036 }
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +02001037
Spencer Low753d4852015-07-30 23:07:55 -07001038 const int fd = _fh_to_int(fh.get());
Josh Gao08229f62018-04-05 18:09:02 -07001039 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
Josh Gao90228a62019-04-25 14:04:57 -07001040 D("adb_socket_accept on fd %d returns fd %d", serverfd.get(), fd);
Spencer Low753d4852015-07-30 23:07:55 -07001041 fh.release();
Josh Gao08229f62018-04-05 18:09:02 -07001042 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001043}
1044
Josh Gao90228a62019-04-25 14:04:57 -07001045int adb_setsockopt(borrowed_fd fd, int level, int optname, const void* optval, socklen_t optlen) {
Josh Gao08229f62018-04-05 18:09:02 -07001046 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001047
Josh Gao08229f62018-04-05 18:09:02 -07001048 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001049 D("adb_setsockopt: invalid fd %d", fd.get());
Spencer Low753d4852015-07-30 23:07:55 -07001050 errno = EBADF;
1051 return -1;
1052 }
Spencer Lowc7c45612015-09-29 15:05:29 -07001053
1054 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1055 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1056 // auto-tuning.
1057
Josh Gao08229f62018-04-05 18:09:02 -07001058 int result =
1059 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1060 if (result == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -07001061 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001062 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd.get(), level,
Josh Gao08229f62018-04-05 18:09:02 -07001063 optname, android::base::SystemErrorCodeToString(err).c_str());
1064 _socket_set_errno(err);
Spencer Low753d4852015-07-30 23:07:55 -07001065 result = -1;
1066 }
1067 return result;
1068}
1069
Josh Gao90228a62019-04-25 14:04:57 -07001070static int adb_getsockname(borrowed_fd fd, struct sockaddr* sockaddr, socklen_t* optlen) {
Josh Gaoe7388122016-02-16 17:34:53 -08001071 FH fh = _fh_from_int(fd, __func__);
1072
1073 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001074 D("adb_getsockname: invalid fd %d", fd.get());
Josh Gaoe7388122016-02-16 17:34:53 -08001075 errno = EBADF;
1076 return -1;
1077 }
1078
Josh Gao4f6f4422017-03-30 13:04:35 -07001079 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gaoe7388122016-02-16 17:34:53 -08001080 if (result == SOCKET_ERROR) {
1081 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001082 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd.get(),
Josh Gaoe7388122016-02-16 17:34:53 -08001083 android::base::SystemErrorCodeToString(err).c_str());
1084 _socket_set_errno(err);
1085 result = -1;
1086 }
1087 return result;
1088}
Spencer Low753d4852015-07-30 23:07:55 -07001089
Josh Gao90228a62019-04-25 14:04:57 -07001090int adb_socket_get_local_port(borrowed_fd fd) {
David Pursell19d0c232016-04-07 11:25:48 -07001091 sockaddr_storage addr_storage;
1092 socklen_t addr_len = sizeof(addr_storage);
1093
1094 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1095 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1096 return -1;
1097 }
1098
1099 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1100 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1101 errno = ECONNABORTED;
1102 return -1;
1103 }
1104
1105 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1106}
1107
Josh Gao90228a62019-04-25 14:04:57 -07001108int adb_shutdown(borrowed_fd fd, int direction) {
Josh Gao96049b92018-03-23 13:03:28 -07001109 FH f = _fh_from_int(fd, __func__);
Spencer Low753d4852015-07-30 23:07:55 -07001110
1111 if (!f || f->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001112 D("adb_shutdown: invalid fd %d", fd.get());
Spencer Low753d4852015-07-30 23:07:55 -07001113 errno = EBADF;
Spencer Low31aafa62015-01-25 14:40:16 -08001114 return -1;
1115 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001116
Josh Gao96049b92018-03-23 13:03:28 -07001117 D("adb_shutdown: %s", f->name);
1118 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low753d4852015-07-30 23:07:55 -07001119 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001120 D("socket shutdown fd %d failed: %s", fd.get(),
David Pursellc573d522016-01-27 08:52:53 -08001121 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low753d4852015-07-30 23:07:55 -07001122 _socket_set_errno(err);
1123 return -1;
1124 }
1125 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001126}
1127
Josh Gaoe7388122016-02-16 17:34:53 -08001128// Emulate socketpair(2) by binding and connecting to a socket.
1129int adb_socketpair(int sv[2]) {
1130 int server = -1;
1131 int client = -1;
1132 int accepted = -1;
David Pursell19d0c232016-04-07 11:25:48 -07001133 int local_port = -1;
Josh Gaoe7388122016-02-16 17:34:53 -08001134 std::string error;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001135
Callum Ryan04efea32019-10-31 07:21:42 -07001136 server = network_loopback_server(0, SOCK_STREAM, &error, true);
Josh Gaoe7388122016-02-16 17:34:53 -08001137 if (server < 0) {
1138 D("adb_socketpair: failed to create server: %s", error.c_str());
1139 goto fail;
David Pursell7616ae12015-09-11 16:06:59 -07001140 }
1141
David Pursell19d0c232016-04-07 11:25:48 -07001142 local_port = adb_socket_get_local_port(server);
1143 if (local_port < 0) {
1144 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gaoe7388122016-02-16 17:34:53 -08001145 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001146 }
David Pursell19d0c232016-04-07 11:25:48 -07001147 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001148
David Pursell19d0c232016-04-07 11:25:48 -07001149 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gaoe7388122016-02-16 17:34:53 -08001150 if (client < 0) {
1151 D("adb_socketpair: failed to connect client: %s", error.c_str());
1152 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001153 }
1154
Josh Gao4f6f4422017-03-30 13:04:35 -07001155 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gaoe7388122016-02-16 17:34:53 -08001156 if (accepted < 0) {
Josh Gao61eda8d2016-02-18 13:43:55 -08001157 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gaoe7388122016-02-16 17:34:53 -08001158 goto fail;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001159 }
Josh Gaoe7388122016-02-16 17:34:53 -08001160 adb_close(server);
1161 sv[0] = client;
1162 sv[1] = accepted;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001163 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001164
Josh Gaoe7388122016-02-16 17:34:53 -08001165fail:
1166 if (server >= 0) {
1167 adb_close(server);
1168 }
1169 if (client >= 0) {
1170 adb_close(client);
1171 }
1172 if (accepted >= 0) {
1173 adb_close(accepted);
1174 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001175 return -1;
1176}
1177
Josh Gao90228a62019-04-25 14:04:57 -07001178bool set_file_block_mode(borrowed_fd fd, bool block) {
Josh Gaoe7388122016-02-16 17:34:53 -08001179 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001180
Josh Gaoe7388122016-02-16 17:34:53 -08001181 if (!fh || !fh->used) {
1182 errno = EBADF;
Josh Gao90228a62019-04-25 14:04:57 -07001183 D("Setting nonblocking on bad file descriptor %d", fd.get());
Josh Gaoe7388122016-02-16 17:34:53 -08001184 return false;
Spencer Low753d4852015-07-30 23:07:55 -07001185 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001186
Josh Gaoe7388122016-02-16 17:34:53 -08001187 if (fh->clazz == &_fh_socket_class) {
1188 u_long x = !block;
1189 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin20238f22016-09-21 14:03:39 -07001190 int error = WSAGetLastError();
1191 _socket_set_errno(error);
Josh Gao90228a62019-04-25 14:04:57 -07001192 D("Setting %d nonblocking failed (%d)", fd.get(), error);
Josh Gaoe7388122016-02-16 17:34:53 -08001193 return false;
1194 }
1195 return true;
Elliott Hughes6a096932015-04-16 16:47:02 -07001196 } else {
Josh Gaoe7388122016-02-16 17:34:53 -08001197 errno = ENOTSOCK;
Josh Gao90228a62019-04-25 14:04:57 -07001198 D("Setting nonblocking on non-socket %d", fd.get());
Josh Gaoe7388122016-02-16 17:34:53 -08001199 return false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001200 }
1201}
1202
Josh Gao90228a62019-04-25 14:04:57 -07001203bool set_tcp_keepalive(borrowed_fd fd, int interval_sec) {
David Pursellc25a34e2016-02-22 14:27:23 -08001204 FH fh = _fh_from_int(fd, __func__);
1205
1206 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao90228a62019-04-25 14:04:57 -07001207 D("set_tcp_keepalive(%d) failed: invalid fd", fd.get());
David Pursellc25a34e2016-02-22 14:27:23 -08001208 errno = EBADF;
1209 return false;
1210 }
1211
1212 tcp_keepalive keepalive;
1213 keepalive.onoff = (interval_sec > 0);
1214 keepalive.keepalivetime = interval_sec * 1000;
1215 keepalive.keepaliveinterval = interval_sec * 1000;
1216
1217 DWORD bytes_returned = 0;
1218 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1219 &bytes_returned, nullptr, nullptr) != 0) {
1220 const DWORD err = WSAGetLastError();
Josh Gao90228a62019-04-25 14:04:57 -07001221 D("set_tcp_keepalive(%d) failed: %s", fd.get(),
David Pursellc25a34e2016-02-22 14:27:23 -08001222 android::base::SystemErrorCodeToString(err).c_str());
1223 _socket_set_errno(err);
1224 return false;
1225 }
1226
1227 return true;
1228}
1229
Spencer Lowbeb61982015-03-01 15:06:21 -08001230/**************************************************************************/
1231/**************************************************************************/
1232/***** *****/
1233/***** Console Window Terminal Emulation *****/
1234/***** *****/
1235/**************************************************************************/
1236/**************************************************************************/
1237
1238// This reads input from a Win32 console window and translates it into Unix
1239// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1240// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1241// is emulated instead of xterm because it is probably more popular than xterm:
1242// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1243// supports modern fonts, etc. It seems best to emulate the terminal that most
1244// Android developers use because they'll fix apps (the shell, etc.) to keep
1245// working with that terminal's emulation.
1246//
1247// The point of this emulation is not to be perfect or to solve all issues with
1248// console windows on Windows, but to be better than the original code which
1249// just called read() (which called ReadFile(), which called ReadConsoleA())
1250// which did not support Ctrl-C, tab completion, shell input line editing
1251// keys, server echo, and more.
1252//
1253// This implementation reconfigures the console with SetConsoleMode(), then
1254// calls ReadConsoleInput() to get raw input which it remaps to Unix
1255// terminal-style sequences which is returned via unix_read() which is used
1256// by the 'adb shell' command.
1257//
1258// Code organization:
1259//
David Pursell58805362015-10-28 14:29:51 -07001260// * _get_console_handle() and unix_isatty() provide console information.
Spencer Lowbeb61982015-03-01 15:06:21 -08001261// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1262// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1263// * _console_read() is the main code of the emulation.
1264
David Pursell58805362015-10-28 14:29:51 -07001265// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1266// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1267// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
Josh Gao90228a62019-04-25 14:04:57 -07001268static HANDLE _get_console_handle(borrowed_fd fd, DWORD* mode = nullptr) {
David Pursell58805362015-10-28 14:29:51 -07001269 // First check isatty(); this is very fast and eliminates most non-console
1270 // FDs, but returns 1 for both consoles and character devices like NUL.
1271#pragma push_macro("isatty")
1272#undef isatty
Josh Gao90228a62019-04-25 14:04:57 -07001273 if (!isatty(fd.get())) {
David Pursell58805362015-10-28 14:29:51 -07001274 return nullptr;
1275 }
1276#pragma pop_macro("isatty")
1277
1278 // To differentiate between character devices and consoles we need to get
1279 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1280 // GENERIC_READ permissions.
Josh Gao90228a62019-04-25 14:04:57 -07001281 const intptr_t intptr_handle = _get_osfhandle(fd.get());
David Pursell58805362015-10-28 14:29:51 -07001282 if (intptr_handle == -1) {
1283 return nullptr;
1284 }
1285 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1286 DWORD temp_mode = 0;
1287 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1288 return nullptr;
1289 }
1290
1291 return handle;
1292}
1293
1294// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1295static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowf373c352015-11-15 16:29:36 -08001296 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1297 android::base::ErrnoRestorer er;
David Pursell58805362015-10-28 14:29:51 -07001298 const int fd = fileno(stream);
1299 if (fd < 0) {
1300 return nullptr;
1301 }
1302 return _get_console_handle(fd);
1303}
1304
Josh Gao90228a62019-04-25 14:04:57 -07001305int unix_isatty(borrowed_fd fd) {
David Pursell58805362015-10-28 14:29:51 -07001306 return _get_console_handle(fd) ? 1 : 0;
1307}
Spencer Lowbeb61982015-03-01 15:06:21 -08001308
Spencer Low9c8f7462015-11-10 19:17:16 -08001309// Get the next KEY_EVENT_RECORD that should be processed.
1310static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001311 for (;;) {
1312 DWORD read_count = 0;
1313 memset(input_record, 0, sizeof(*input_record));
1314 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001315 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursellc573d522016-01-27 08:52:53 -08001316 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08001317 errno = EIO;
1318 return false;
1319 }
1320
1321 if (read_count == 0) { // should be impossible
Elliott Hughese64126b2018-10-19 13:59:44 -07001322 LOG(FATAL) << "ReadConsoleInputA returned 0";
Spencer Lowbeb61982015-03-01 15:06:21 -08001323 }
1324
1325 if (read_count != 1) { // should be impossible
Elliott Hughese64126b2018-10-19 13:59:44 -07001326 LOG(FATAL) << "ReadConsoleInputA did not return one input record";
Spencer Lowbeb61982015-03-01 15:06:21 -08001327 }
1328
Spencer Low55441402015-11-07 17:34:39 -08001329 // If the console window is resized, emulate SIGWINCH by breaking out
1330 // of read() with errno == EINTR. Note that there is no event on
1331 // vertical resize because we don't give the console our own custom
1332 // screen buffer (with CreateConsoleScreenBuffer() +
1333 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1334 // supports scrollback, but doesn't seem to raise an event for vertical
1335 // window resize.
1336 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1337 errno = EINTR;
1338 return false;
1339 }
1340
Spencer Lowbeb61982015-03-01 15:06:21 -08001341 if ((input_record->EventType == KEY_EVENT) &&
1342 (input_record->Event.KeyEvent.bKeyDown)) {
1343 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
Elliott Hughese64126b2018-10-19 13:59:44 -07001344 LOG(FATAL) << "ReadConsoleInputA returned a key event with zero repeat count";
Spencer Lowbeb61982015-03-01 15:06:21 -08001345 }
1346
1347 // Got an interesting INPUT_RECORD, so return
1348 return true;
1349 }
1350 }
1351}
1352
Spencer Lowbeb61982015-03-01 15:06:21 -08001353static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1354 return (control_key_state & SHIFT_PRESSED) != 0;
1355}
1356
1357static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1358 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1359}
1360
1361static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1362 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1363}
1364
1365static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1366 return (control_key_state & NUMLOCK_ON) != 0;
1367}
1368
1369static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1370 return (control_key_state & CAPSLOCK_ON) != 0;
1371}
1372
1373static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1374 return (control_key_state & ENHANCED_KEY) != 0;
1375}
1376
1377// Constants from MSDN for ToAscii().
1378static const BYTE TOASCII_KEY_OFF = 0x00;
1379static const BYTE TOASCII_KEY_DOWN = 0x80;
1380static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1381
1382// Given a key event, ignore a modifier key and return the character that was
1383// entered without the modifier. Writes to *ch and returns the number of bytes
1384// written.
1385static size_t _get_char_ignoring_modifier(char* const ch,
1386 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1387 const WORD modifier) {
1388 // If there is no character from Windows, try ignoring the specified
1389 // modifier and look for a character. Note that if AltGr is being used,
1390 // there will be a character from Windows.
1391 if (key_event->uChar.AsciiChar == '\0') {
1392 // Note that we read the control key state from the passed in argument
1393 // instead of from key_event since the argument has been normalized.
1394 if (((modifier == VK_SHIFT) &&
1395 _is_shift_pressed(control_key_state)) ||
1396 ((modifier == VK_CONTROL) &&
1397 _is_ctrl_pressed(control_key_state)) ||
1398 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1399
1400 BYTE key_state[256] = {0};
1401 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1402 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1403 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1404 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1405 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1406 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1407 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1408 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1409
1410 // cause this modifier to be ignored
1411 key_state[modifier] = TOASCII_KEY_OFF;
1412
1413 WORD translated = 0;
1414 if (ToAscii(key_event->wVirtualKeyCode,
1415 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1416 // Ignoring the modifier, we found a character.
1417 *ch = (CHAR)translated;
1418 return 1;
1419 }
1420 }
1421 }
1422
1423 // Just use whatever Windows told us originally.
1424 *ch = key_event->uChar.AsciiChar;
1425
1426 // If the character from Windows is NULL, return a size of zero.
1427 return (*ch == '\0') ? 0 : 1;
1428}
1429
1430// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1431// but taking into account the shift key. This is because for a sequence like
1432// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1433// we want to find the character ')'.
1434//
1435// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1436// because it is the default key-sequence to switch the input language.
1437// This is configurable in the Region and Language control panel.
1438static __inline__ size_t _get_non_control_char(char* const ch,
1439 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1440 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1441 VK_CONTROL);
1442}
1443
1444// Get without Alt.
1445static __inline__ size_t _get_non_alt_char(char* const ch,
1446 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1447 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1448 VK_MENU);
1449}
1450
1451// Ignore the control key, find the character from Windows, and apply any
1452// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1453// *pch and returns number of bytes written.
1454static size_t _get_control_character(char* const pch,
1455 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1456 const size_t len = _get_non_control_char(pch, key_event,
1457 control_key_state);
1458
1459 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1460 char ch = *pch;
1461 switch (ch) {
1462 case '2':
1463 case '@':
1464 case '`':
1465 ch = '\0';
1466 break;
1467 case '3':
1468 case '[':
1469 case '{':
1470 ch = '\x1b';
1471 break;
1472 case '4':
1473 case '\\':
1474 case '|':
1475 ch = '\x1c';
1476 break;
1477 case '5':
1478 case ']':
1479 case '}':
1480 ch = '\x1d';
1481 break;
1482 case '6':
1483 case '^':
1484 case '~':
1485 ch = '\x1e';
1486 break;
1487 case '7':
1488 case '-':
1489 case '_':
1490 ch = '\x1f';
1491 break;
1492 case '8':
1493 ch = '\x7f';
1494 break;
1495 case '/':
1496 if (!_is_alt_pressed(control_key_state)) {
1497 ch = '\x1f';
1498 }
1499 break;
1500 case '?':
1501 if (!_is_alt_pressed(control_key_state)) {
1502 ch = '\x7f';
1503 }
1504 break;
1505 }
1506 *pch = ch;
1507 }
1508
1509 return len;
1510}
1511
1512static DWORD _normalize_altgr_control_key_state(
1513 const KEY_EVENT_RECORD* const key_event) {
1514 DWORD control_key_state = key_event->dwControlKeyState;
1515
1516 // If we're in an AltGr situation where the AltGr key is down (depending on
1517 // the keyboard layout, that might be the physical right alt key which
1518 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1519 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1520 // a character (which indicates that there was an AltGr mapping), then act
1521 // as if alt and control are not really down for the purposes of modifiers.
1522 // This makes it so that if the user with, say, a German keyboard layout
1523 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1524 // output the key and we don't see the Alt and Ctrl keys.
1525 if (_is_ctrl_pressed(control_key_state) &&
1526 _is_alt_pressed(control_key_state)
1527 && (key_event->uChar.AsciiChar != '\0')) {
1528 // Try to remove as few bits as possible to improve our chances of
1529 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1530 // Left-Alt + Right-Ctrl + AltGr.
1531 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1532 // Remove Right-Alt.
1533 control_key_state &= ~RIGHT_ALT_PRESSED;
1534 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1535 // pressed, Left-Ctrl is almost always set, except if the user
1536 // presses Right-Ctrl, then AltGr (in that specific order) for
1537 // whatever reason. At any rate, make sure the bit is not set.
1538 control_key_state &= ~LEFT_CTRL_PRESSED;
1539 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1540 // Remove Left-Alt.
1541 control_key_state &= ~LEFT_ALT_PRESSED;
1542 // Whichever Ctrl key is down, remove it from the state. We only
1543 // remove one key, to improve our chances of detecting the
1544 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1545 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1546 // Remove Left-Ctrl.
1547 control_key_state &= ~LEFT_CTRL_PRESSED;
1548 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1549 // Remove Right-Ctrl.
1550 control_key_state &= ~RIGHT_CTRL_PRESSED;
1551 }
1552 }
1553
1554 // Note that this logic isn't 100% perfect because Windows doesn't
1555 // allow us to detect all combinations because a physical AltGr key
1556 // press shows up as two bits, plus some combinations are ambiguous
1557 // about what is actually physically pressed.
1558 }
1559
1560 return control_key_state;
1561}
1562
1563// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1564// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1565// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1566// appropriately.
1567static DWORD _normalize_keypad_control_key_state(const WORD vk,
1568 const DWORD control_key_state) {
1569 if (!_is_numlock_on(control_key_state)) {
1570 return control_key_state;
1571 }
1572 if (!_is_enhanced_key(control_key_state)) {
1573 switch (vk) {
1574 case VK_INSERT: // 0
1575 case VK_DELETE: // .
1576 case VK_END: // 1
1577 case VK_DOWN: // 2
1578 case VK_NEXT: // 3
1579 case VK_LEFT: // 4
1580 case VK_CLEAR: // 5
1581 case VK_RIGHT: // 6
1582 case VK_HOME: // 7
1583 case VK_UP: // 8
1584 case VK_PRIOR: // 9
1585 return control_key_state | SHIFT_PRESSED;
1586 }
1587 }
1588
1589 return control_key_state;
1590}
1591
1592static const char* _get_keypad_sequence(const DWORD control_key_state,
1593 const char* const normal, const char* const shifted) {
1594 if (_is_shift_pressed(control_key_state)) {
1595 // Shift is pressed and NumLock is off
1596 return shifted;
1597 } else {
1598 // Shift is not pressed and NumLock is off, or,
1599 // Shift is pressed and NumLock is on, in which case we want the
1600 // NumLock and Shift to neutralize each other, thus, we want the normal
1601 // sequence.
1602 return normal;
1603 }
1604 // If Shift is not pressed and NumLock is on, a different virtual key code
1605 // is returned by Windows, which can be taken care of by a different case
1606 // statement in _console_read().
1607}
1608
1609// Write sequence to buf and return the number of bytes written.
1610static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1611 DWORD control_key_state, const char* const normal) {
1612 // Copy the base sequence into buf.
1613 const size_t len = strlen(normal);
1614 memcpy(buf, normal, len);
1615
1616 int code = 0;
1617
1618 control_key_state = _normalize_keypad_control_key_state(vk,
1619 control_key_state);
1620
1621 if (_is_shift_pressed(control_key_state)) {
1622 code |= 0x1;
1623 }
1624 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1625 code |= 0x2;
1626 }
1627 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1628 code |= 0x4;
1629 }
1630 // If some modifier was held down, then we need to insert the modifier code
1631 if (code != 0) {
1632 if (len == 0) {
1633 // Should be impossible because caller should pass a string of
1634 // non-zero length.
1635 return 0;
1636 }
1637 size_t index = len - 1;
1638 const char lastChar = buf[index];
1639 if (lastChar != '~') {
1640 buf[index++] = '1';
1641 }
1642 buf[index++] = ';'; // modifier separator
1643 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1644 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1645 buf[index++] = '1' + code;
1646 buf[index++] = lastChar; // move ~ (or other last char) to the end
1647 return index;
1648 }
1649 return len;
1650}
1651
1652// Write sequence to buf and return the number of bytes written.
1653static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1654 const DWORD control_key_state, const char* const normal,
1655 const char shifted) {
1656 if (_is_shift_pressed(control_key_state)) {
1657 // Shift is pressed and NumLock is off
1658 if (shifted != '\0') {
1659 buf[0] = shifted;
1660 return sizeof(buf[0]);
1661 } else {
1662 return 0;
1663 }
1664 } else {
1665 // Shift is not pressed and NumLock is off, or,
1666 // Shift is pressed and NumLock is on, in which case we want the
1667 // NumLock and Shift to neutralize each other, thus, we want the normal
1668 // sequence.
1669 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1670 }
1671 // If Shift is not pressed and NumLock is on, a different virtual key code
1672 // is returned by Windows, which can be taken care of by a different case
1673 // statement in _console_read().
1674}
1675
1676// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1677// Standard German. Figure this out at runtime so we know what to output for
1678// Shift-VK_DELETE.
1679static char _get_decimal_char() {
1680 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1681}
1682
1683// Prefix the len bytes in buf with the escape character, and then return the
1684// new buffer length.
Josh Gao90228a62019-04-25 14:04:57 -07001685static size_t _escape_prefix(char* const buf, const size_t len) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001686 // If nothing to prefix, don't do anything. We might be called with
1687 // len == 0, if alt was held down with a dead key which produced nothing.
1688 if (len == 0) {
1689 return 0;
1690 }
1691
1692 memmove(&buf[1], buf, len);
1693 buf[0] = '\x1b';
1694 return len + 1;
1695}
1696
Spencer Low9c8f7462015-11-10 19:17:16 -08001697// Internal buffer to satisfy future _console_read() calls.
Josh Gaoe3a87d02015-11-11 17:56:12 -08001698static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low9c8f7462015-11-10 19:17:16 -08001699
1700// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1701// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Lowbeb61982015-03-01 15:06:21 -08001702static int _console_read(const HANDLE console, void* buf, size_t len) {
1703 for (;;) {
Spencer Low9c8f7462015-11-10 19:17:16 -08001704 // Read of zero bytes should not block waiting for something from the console.
1705 if (len == 0) {
1706 return 0;
1707 }
1708
1709 // Flush as much as possible from input buffer.
1710 if (!g_console_input_buffer.empty()) {
1711 const int bytes_read = std::min(len, g_console_input_buffer.size());
1712 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1713 const auto begin = g_console_input_buffer.begin();
1714 g_console_input_buffer.erase(begin, begin + bytes_read);
1715 return bytes_read;
1716 }
1717
1718 // Read from the actual console. This may block until input.
1719 INPUT_RECORD input_record;
1720 if (!_get_key_event_record(console, &input_record)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08001721 return -1;
1722 }
1723
Spencer Low9c8f7462015-11-10 19:17:16 -08001724 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Lowbeb61982015-03-01 15:06:21 -08001725 const WORD vk = key_event->wVirtualKeyCode;
1726 const CHAR ch = key_event->uChar.AsciiChar;
1727 const DWORD control_key_state = _normalize_altgr_control_key_state(
1728 key_event);
1729
1730 // The following emulation code should write the output sequence to
1731 // either seqstr or to seqbuf and seqbuflen.
Yi Kong86e67182018-07-13 18:15:16 -07001732 const char* seqstr = nullptr; // NULL terminated C-string
Spencer Lowbeb61982015-03-01 15:06:21 -08001733 // Enough space for max sequence string below, plus modifiers and/or
1734 // escape prefix.
1735 char seqbuf[16];
1736 size_t seqbuflen = 0; // Space used in seqbuf.
1737
1738#define MATCH(vk, normal) \
1739 case (vk): \
1740 { \
1741 seqstr = (normal); \
1742 } \
1743 break;
1744
1745 // Modifier keys should affect the output sequence.
1746#define MATCH_MODIFIER(vk, normal) \
1747 case (vk): \
1748 { \
1749 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1750 control_key_state, (normal)); \
1751 } \
1752 break;
1753
1754 // The shift key should affect the output sequence.
1755#define MATCH_KEYPAD(vk, normal, shifted) \
1756 case (vk): \
1757 { \
1758 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1759 (shifted)); \
1760 } \
1761 break;
1762
1763 // The shift key and other modifier keys should affect the output
1764 // sequence.
1765#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1766 case (vk): \
1767 { \
1768 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1769 control_key_state, (normal), (shifted)); \
1770 } \
1771 break;
1772
1773#define ESC "\x1b"
1774#define CSI ESC "["
1775#define SS3 ESC "O"
1776
1777 // Only support normal mode, not application mode.
1778
1779 // Enhanced keys:
1780 // * 6-pack: insert, delete, home, end, page up, page down
1781 // * cursor keys: up, down, right, left
1782 // * keypad: divide, enter
1783 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1784 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1785 if (_is_enhanced_key(control_key_state)) {
1786 switch (vk) {
1787 case VK_RETURN: // Enter key on keypad
1788 if (_is_ctrl_pressed(control_key_state)) {
1789 seqstr = "\n";
1790 } else {
1791 seqstr = "\r";
1792 }
1793 break;
1794
1795 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1796 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1797
1798 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1799 // will be fixed soon to match xterm which sends CSI "F" and
1800 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1801 MATCH(VK_END, CSI "F");
1802 MATCH(VK_HOME, CSI "H");
1803
1804 MATCH_MODIFIER(VK_LEFT, CSI "D");
1805 MATCH_MODIFIER(VK_UP, CSI "A");
1806 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1807 MATCH_MODIFIER(VK_DOWN, CSI "B");
1808
1809 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1810 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1811
1812 MATCH(VK_DIVIDE, "/");
1813 }
1814 } else { // Non-enhanced keys:
1815 switch (vk) {
1816 case VK_BACK: // backspace
1817 if (_is_alt_pressed(control_key_state)) {
1818 seqstr = ESC "\x7f";
1819 } else {
1820 seqstr = "\x7f";
1821 }
1822 break;
1823
1824 case VK_TAB:
1825 if (_is_shift_pressed(control_key_state)) {
1826 seqstr = CSI "Z";
1827 } else {
1828 seqstr = "\t";
1829 }
1830 break;
1831
1832 // Number 5 key in keypad when NumLock is off, or if NumLock is
1833 // on and Shift is down.
1834 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1835
1836 case VK_RETURN: // Enter key on main keyboard
1837 if (_is_alt_pressed(control_key_state)) {
1838 seqstr = ESC "\n";
1839 } else if (_is_ctrl_pressed(control_key_state)) {
1840 seqstr = "\n";
1841 } else {
1842 seqstr = "\r";
1843 }
1844 break;
1845
1846 // VK_ESCAPE: Don't do any special handling. The OS uses many
1847 // of the sequences with Escape and many of the remaining
1848 // sequences don't produce bKeyDown messages, only !bKeyDown
1849 // for whatever reason.
1850
1851 case VK_SPACE:
1852 if (_is_alt_pressed(control_key_state)) {
1853 seqstr = ESC " ";
1854 } else if (_is_ctrl_pressed(control_key_state)) {
1855 seqbuf[0] = '\0'; // NULL char
1856 seqbuflen = 1;
1857 } else {
1858 seqstr = " ";
1859 }
1860 break;
1861
1862 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1863 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1864
1865 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1866 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1867
1868 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1869 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1870 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1871 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1872
1873 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1874 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1875 _get_decimal_char());
1876
1877 case 0x30: // 0
1878 case 0x31: // 1
1879 case 0x39: // 9
1880 case VK_OEM_1: // ;:
1881 case VK_OEM_PLUS: // =+
1882 case VK_OEM_COMMA: // ,<
1883 case VK_OEM_PERIOD: // .>
1884 case VK_OEM_7: // '"
1885 case VK_OEM_102: // depends on keyboard, could be <> or \|
1886 case VK_OEM_2: // /?
1887 case VK_OEM_3: // `~
1888 case VK_OEM_4: // [{
1889 case VK_OEM_5: // \|
1890 case VK_OEM_6: // ]}
1891 {
1892 seqbuflen = _get_control_character(seqbuf, key_event,
1893 control_key_state);
1894
1895 if (_is_alt_pressed(control_key_state)) {
1896 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1897 }
1898 }
1899 break;
1900
1901 case 0x32: // 2
Spencer Low9c8f7462015-11-10 19:17:16 -08001902 case 0x33: // 3
1903 case 0x34: // 4
1904 case 0x35: // 5
Spencer Lowbeb61982015-03-01 15:06:21 -08001905 case 0x36: // 6
Spencer Low9c8f7462015-11-10 19:17:16 -08001906 case 0x37: // 7
1907 case 0x38: // 8
Spencer Lowbeb61982015-03-01 15:06:21 -08001908 case VK_OEM_MINUS: // -_
1909 {
1910 seqbuflen = _get_control_character(seqbuf, key_event,
1911 control_key_state);
1912
1913 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1914 // prefix with escape.
1915 if (_is_alt_pressed(control_key_state) &&
1916 !(_is_ctrl_pressed(control_key_state) &&
1917 !_is_shift_pressed(control_key_state))) {
1918 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1919 }
1920 }
1921 break;
1922
Spencer Lowbeb61982015-03-01 15:06:21 -08001923 case 0x41: // a
1924 case 0x42: // b
1925 case 0x43: // c
1926 case 0x44: // d
1927 case 0x45: // e
1928 case 0x46: // f
1929 case 0x47: // g
1930 case 0x48: // h
1931 case 0x49: // i
1932 case 0x4a: // j
1933 case 0x4b: // k
1934 case 0x4c: // l
1935 case 0x4d: // m
1936 case 0x4e: // n
1937 case 0x4f: // o
1938 case 0x50: // p
1939 case 0x51: // q
1940 case 0x52: // r
1941 case 0x53: // s
1942 case 0x54: // t
1943 case 0x55: // u
1944 case 0x56: // v
1945 case 0x57: // w
1946 case 0x58: // x
1947 case 0x59: // y
1948 case 0x5a: // z
1949 {
1950 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1951 control_key_state);
1952
1953 // If Alt is pressed, then prefix with escape.
1954 if (_is_alt_pressed(control_key_state)) {
1955 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1956 }
1957 }
1958 break;
1959
1960 // These virtual key codes are generated by the keys on the
1961 // keypad *when NumLock is on* and *Shift is up*.
1962 MATCH(VK_NUMPAD0, "0");
1963 MATCH(VK_NUMPAD1, "1");
1964 MATCH(VK_NUMPAD2, "2");
1965 MATCH(VK_NUMPAD3, "3");
1966 MATCH(VK_NUMPAD4, "4");
1967 MATCH(VK_NUMPAD5, "5");
1968 MATCH(VK_NUMPAD6, "6");
1969 MATCH(VK_NUMPAD7, "7");
1970 MATCH(VK_NUMPAD8, "8");
1971 MATCH(VK_NUMPAD9, "9");
1972
1973 MATCH(VK_MULTIPLY, "*");
1974 MATCH(VK_ADD, "+");
1975 MATCH(VK_SUBTRACT, "-");
1976 // VK_DECIMAL is generated by the . key on the keypad *when
1977 // NumLock is on* and *Shift is up* and the sequence is not
1978 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1979 // Windows Security screen to come up).
1980 case VK_DECIMAL:
1981 // U.S. English uses '.', Germany German uses ','.
1982 seqbuflen = _get_non_control_char(seqbuf, key_event,
1983 control_key_state);
1984 break;
1985
1986 MATCH_MODIFIER(VK_F1, SS3 "P");
1987 MATCH_MODIFIER(VK_F2, SS3 "Q");
1988 MATCH_MODIFIER(VK_F3, SS3 "R");
1989 MATCH_MODIFIER(VK_F4, SS3 "S");
1990 MATCH_MODIFIER(VK_F5, CSI "15~");
1991 MATCH_MODIFIER(VK_F6, CSI "17~");
1992 MATCH_MODIFIER(VK_F7, CSI "18~");
1993 MATCH_MODIFIER(VK_F8, CSI "19~");
1994 MATCH_MODIFIER(VK_F9, CSI "20~");
1995 MATCH_MODIFIER(VK_F10, CSI "21~");
1996 MATCH_MODIFIER(VK_F11, CSI "23~");
1997 MATCH_MODIFIER(VK_F12, CSI "24~");
1998
1999 MATCH_MODIFIER(VK_F13, CSI "25~");
2000 MATCH_MODIFIER(VK_F14, CSI "26~");
2001 MATCH_MODIFIER(VK_F15, CSI "28~");
2002 MATCH_MODIFIER(VK_F16, CSI "29~");
2003 MATCH_MODIFIER(VK_F17, CSI "31~");
2004 MATCH_MODIFIER(VK_F18, CSI "32~");
2005 MATCH_MODIFIER(VK_F19, CSI "33~");
2006 MATCH_MODIFIER(VK_F20, CSI "34~");
2007
2008 // MATCH_MODIFIER(VK_F21, ???);
2009 // MATCH_MODIFIER(VK_F22, ???);
2010 // MATCH_MODIFIER(VK_F23, ???);
2011 // MATCH_MODIFIER(VK_F24, ???);
2012 }
2013 }
2014
2015#undef MATCH
2016#undef MATCH_MODIFIER
2017#undef MATCH_KEYPAD
2018#undef MATCH_MODIFIER_KEYPAD
2019#undef ESC
2020#undef CSI
2021#undef SS3
2022
2023 const char* out;
2024 size_t outlen;
2025
2026 // Check for output in any of:
2027 // * seqstr is set (and strlen can be used to determine the length).
2028 // * seqbuf and seqbuflen are set
2029 // Fallback to ch from Windows.
Yi Kong86e67182018-07-13 18:15:16 -07002030 if (seqstr != nullptr) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002031 out = seqstr;
2032 outlen = strlen(seqstr);
2033 } else if (seqbuflen > 0) {
2034 out = seqbuf;
2035 outlen = seqbuflen;
2036 } else if (ch != '\0') {
2037 // Use whatever Windows told us it is.
2038 seqbuf[0] = ch;
2039 seqbuflen = 1;
2040 out = seqbuf;
2041 outlen = seqbuflen;
2042 } else {
2043 // No special handling for the virtual key code and Windows isn't
2044 // telling us a character code, then we don't know how to translate
2045 // the key press.
2046 //
2047 // Consume the input and 'continue' to cause us to get a new key
2048 // event.
Yabin Cui815ad882015-09-02 17:44:28 -07002049 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Lowbeb61982015-03-01 15:06:21 -08002050 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Lowbeb61982015-03-01 15:06:21 -08002051 continue;
2052 }
2053
Spencer Low9c8f7462015-11-10 19:17:16 -08002054 // put output wRepeatCount times into g_console_input_buffer
2055 while (key_event->wRepeatCount-- > 0) {
2056 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Lowbeb61982015-03-01 15:06:21 -08002057 }
2058
Spencer Low9c8f7462015-11-10 19:17:16 -08002059 // Loop around and try to flush g_console_input_buffer
Spencer Lowbeb61982015-03-01 15:06:21 -08002060 }
2061}
2062
2063static DWORD _old_console_mode; // previous GetConsoleMode() result
2064static HANDLE _console_handle; // when set, console mode should be restored
2065
Elliott Hughesa8265792015-11-03 11:18:40 -08002066void stdin_raw_init() {
2067 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowf373c352015-11-15 16:29:36 -08002068 if (in == nullptr) {
2069 return;
2070 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002071
Elliott Hughesa8265792015-11-03 11:18:40 -08002072 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2073 // calling the process Ctrl-C routine (configured by
2074 // SetConsoleCtrlHandler()).
2075 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2076 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2077 // flag also seems necessary to have proper line-ending processing.
Spencer Low55441402015-11-07 17:34:39 -08002078 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2079 ENABLE_LINE_INPUT |
2080 ENABLE_ECHO_INPUT);
2081 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2082 new_console_mode |= ENABLE_WINDOW_INPUT;
2083
2084 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002085 // This really should not fail.
2086 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002087 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002088 }
Elliott Hughesa8265792015-11-03 11:18:40 -08002089
2090 // Once this is set, it means that stdin has been configured for
2091 // reading from and that the old console mode should be restored later.
2092 _console_handle = in;
2093
2094 // Note that we don't need to configure C Runtime line-ending
2095 // translation because _console_read() does not call the C Runtime to
2096 // read from the console.
Spencer Lowbeb61982015-03-01 15:06:21 -08002097}
2098
Elliott Hughesa8265792015-11-03 11:18:40 -08002099void stdin_raw_restore() {
Yi Kong86e67182018-07-13 18:15:16 -07002100 if (_console_handle != nullptr) {
Elliott Hughesa8265792015-11-03 11:18:40 -08002101 const HANDLE in = _console_handle;
Yi Kong86e67182018-07-13 18:15:16 -07002102 _console_handle = nullptr; // clear state
Spencer Lowbeb61982015-03-01 15:06:21 -08002103
Elliott Hughesa8265792015-11-03 11:18:40 -08002104 if (!SetConsoleMode(in, _old_console_mode)) {
2105 // This really should not fail.
2106 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursellc573d522016-01-27 08:52:53 -08002107 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Lowbeb61982015-03-01 15:06:21 -08002108 }
2109 }
2110}
2111
Spencer Low55441402015-11-07 17:34:39 -08002112// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
Josh Gao90228a62019-04-25 14:04:57 -07002113int unix_read_interruptible(borrowed_fd fd, void* buf, size_t len) {
Yi Kong86e67182018-07-13 18:15:16 -07002114 if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) {
Spencer Lowbeb61982015-03-01 15:06:21 -08002115 // If it is a request to read from stdin, and stdin_raw_init() has been
2116 // called, and it successfully configured the console, then read from
2117 // the console using Win32 console APIs and partially emulate a unix
2118 // terminal.
2119 return _console_read(_console_handle, buf, len);
2120 } else {
David Pursell3fe11f62015-10-06 15:30:03 -07002121 // On older versions of Windows (definitely 7, definitely not 10),
2122 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursell58805362015-10-28 14:29:51 -07002123 // we need to limit the read size.
2124 if (len > 4096 && unix_isatty(fd)) {
David Pursell3fe11f62015-10-06 15:30:03 -07002125 len = 4096;
2126 }
Spencer Lowbeb61982015-03-01 15:06:21 -08002127 // Just call into C Runtime which can read from pipes/files and which
Spencer Low3a2421b2015-05-22 20:09:06 -07002128 // can do LF/CR translation (which is overridable with _setmode()).
2129 // Undefine the macro that is set in sysdeps.h which bans calls to
2130 // plain read() in favor of unix_read() or adb_read().
2131#pragma push_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002132#undef read
Josh Gao90228a62019-04-25 14:04:57 -07002133 return read(fd.get(), buf, len);
Spencer Low3a2421b2015-05-22 20:09:06 -07002134#pragma pop_macro("read")
Spencer Lowbeb61982015-03-01 15:06:21 -08002135 }
2136}
Spencer Low6815c072015-05-11 01:08:48 -07002137
2138/**************************************************************************/
2139/**************************************************************************/
2140/***** *****/
2141/***** Unicode support *****/
2142/***** *****/
2143/**************************************************************************/
2144/**************************************************************************/
2145
2146// This implements support for using files with Unicode filenames and for
2147// outputting Unicode text to a Win32 console window. This is inspired from
2148// http://utf8everywhere.org/.
2149//
2150// Background
2151// ----------
2152//
2153// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2154// filenames to APIs such as open(). This works because filenames are largely
2155// opaque 'cookies' (perhaps excluding path separators).
2156//
2157// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2158// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2159// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2160// CreateFile() API is really just a macro that adds the W/A based on whether
2161// the UNICODE preprocessor symbol is defined).
2162//
2163// Options
2164// -------
2165//
2166// Thus, to write a portable program, there are a few options:
2167//
2168// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2169// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2170// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2171// open() API.
2172//
2173// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2174// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2175// potentially touching a lot of code.
2176//
2177// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2178// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2179// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2180// or C Runtime API.
2181//
2182// The Choice
2183// ----------
2184//
Spencer Low50f5bf12015-11-12 15:20:15 -08002185// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2186// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Low6815c072015-05-11 01:08:48 -07002187// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Low50f5bf12015-11-12 15:20:15 -08002188// args that are passed to main() at the beginning of program startup. We also use
2189// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Low6815c072015-05-11 01:08:48 -07002190// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2191//
2192// Unicode console output
2193// ----------------------
2194//
2195// The way to output Unicode to a Win32 console window is to call
2196// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowcc467f12015-08-02 18:13:54 -07002197// such as Lucida Console or Consolas, and in the case of East Asian languages
2198// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2199// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2200// font to be used in console windows.)
Spencer Low6815c072015-05-11 01:08:48 -07002201//
2202// The problem is getting the C Runtime to make fprintf and related APIs call
2203// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2204// promising, but the various modes have issues:
2205//
2206// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2207// UTF-16 do not display properly.
2208// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2209// totally wrong.
2210// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2211// handler to be called (upon a later I/O call), aborting the process.
2212// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2213// to output nothing.
2214//
2215// So the only solution is to write our own adb_fprintf() that converts UTF-8
2216// to UTF-16 and then calls WriteConsoleW().
2217
2218
Spencer Low6815c072015-05-11 01:08:48 -07002219// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2220// be passed to main().
2221NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2222 narrow_args = new char*[argc + 1];
2223
2224 for (int i = 0; i < argc; ++i) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002225 std::string arg_narrow;
2226 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
Elliott Hughese64126b2018-10-19 13:59:44 -07002227 PLOG(FATAL) << "cannot convert argument from UTF-16 to UTF-8";
Spencer Low50f5bf12015-11-12 15:20:15 -08002228 }
2229 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002230 }
2231 narrow_args[argc] = nullptr; // terminate
2232}
2233
2234NarrowArgs::~NarrowArgs() {
2235 if (narrow_args != nullptr) {
2236 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2237 free(*argp);
2238 }
2239 delete[] narrow_args;
2240 narrow_args = nullptr;
2241 }
2242}
2243
Josh Gaof0c44032018-12-12 16:12:28 -08002244int unix_open(std::string_view path, int options, ...) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002245 std::wstring path_wide;
Josh Gaof0c44032018-12-12 16:12:28 -08002246 if (!android::base::UTF8ToWide(path.data(), path.size(), &path_wide)) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002247 return -1;
2248 }
Spencer Low6815c072015-05-11 01:08:48 -07002249 if ((options & O_CREAT) == 0) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002250 return _wopen(path_wide.c_str(), options);
Spencer Low6815c072015-05-11 01:08:48 -07002251 } else {
Josh Gaof0c44032018-12-12 16:12:28 -08002252 int mode;
Spencer Low6815c072015-05-11 01:08:48 -07002253 va_list args;
2254 va_start(args, options);
2255 mode = va_arg(args, int);
2256 va_end(args);
Spencer Low50f5bf12015-11-12 15:20:15 -08002257 return _wopen(path_wide.c_str(), options, mode);
Spencer Low6815c072015-05-11 01:08:48 -07002258 }
2259}
2260
Spencer Low6815c072015-05-11 01:08:48 -07002261// Version of opendir() that takes a UTF-8 path.
Spencer Low50f5bf12015-11-12 15:20:15 -08002262DIR* adb_opendir(const char* path) {
2263 std::wstring path_wide;
2264 if (!android::base::UTF8ToWide(path, &path_wide)) {
2265 return nullptr;
2266 }
2267
Spencer Low6815c072015-05-11 01:08:48 -07002268 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2269 // the fields, but right now all the callers treat the structure as
2270 // opaque.
Spencer Low50f5bf12015-11-12 15:20:15 -08002271 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Low6815c072015-05-11 01:08:48 -07002272}
2273
2274// Version of readdir() that returns UTF-8 paths.
2275struct dirent* adb_readdir(DIR* dir) {
2276 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2277 struct _wdirent* const went = _wreaddir(wdir);
2278 if (went == nullptr) {
2279 return nullptr;
2280 }
Spencer Low50f5bf12015-11-12 15:20:15 -08002281
Spencer Low6815c072015-05-11 01:08:48 -07002282 // Convert from UTF-16 to UTF-8.
Spencer Low50f5bf12015-11-12 15:20:15 -08002283 std::string name_utf8;
2284 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2285 return nullptr;
2286 }
Spencer Low6815c072015-05-11 01:08:48 -07002287
2288 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2289 // space for UTF-16 wchar_t's) with UTF-8 char's.
2290 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2291
2292 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2293 // Name too big to fit in existing buffer.
2294 errno = ENOMEM;
2295 return nullptr;
2296 }
2297
2298 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2299 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2300 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2301 // bigger than the caller expects because they expect a dirent structure
2302 // which has a smaller d_name field. Ignore this since the caller should be
2303 // resilient.
2304
2305 // Rewrite the UTF-16 d_name field to UTF-8.
2306 strcpy(ent->d_name, name_utf8.c_str());
2307
2308 return ent;
2309}
2310
2311// Version of closedir() to go with our version of adb_opendir().
2312int adb_closedir(DIR* dir) {
2313 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2314}
2315
2316// Version of unlink() that takes a UTF-8 path.
2317int adb_unlink(const char* path) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002318 std::wstring wpath;
2319 if (!android::base::UTF8ToWide(path, &wpath)) {
2320 return -1;
2321 }
Spencer Low6815c072015-05-11 01:08:48 -07002322
2323 int rc = _wunlink(wpath.c_str());
2324
2325 if (rc == -1 && errno == EACCES) {
2326 /* unlink returns EACCES when the file is read-only, so we first */
2327 /* try to make it writable, then unlink again... */
2328 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2329 if (rc == 0)
2330 rc = _wunlink(wpath.c_str());
2331 }
2332 return rc;
2333}
2334
2335// Version of mkdir() that takes a UTF-8 path.
2336int adb_mkdir(const std::string& path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002337 std::wstring path_wide;
2338 if (!android::base::UTF8ToWide(path, &path_wide)) {
2339 return -1;
2340 }
2341
2342 return _wmkdir(path_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002343}
2344
2345// Version of utime() that takes a UTF-8 path.
2346int adb_utime(const char* path, struct utimbuf* u) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002347 std::wstring path_wide;
2348 if (!android::base::UTF8ToWide(path, &path_wide)) {
2349 return -1;
2350 }
2351
Spencer Low6815c072015-05-11 01:08:48 -07002352 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2353 "utimbuf and _utimbuf should be the same size because they both "
2354 "contain the same types, namely time_t");
Spencer Low50f5bf12015-11-12 15:20:15 -08002355 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Low6815c072015-05-11 01:08:48 -07002356}
2357
2358// Version of chmod() that takes a UTF-8 path.
2359int adb_chmod(const char* path, int mode) {
Spencer Low50f5bf12015-11-12 15:20:15 -08002360 std::wstring path_wide;
2361 if (!android::base::UTF8ToWide(path, &path_wide)) {
2362 return -1;
2363 }
2364
2365 return _wchmod(path_wide.c_str(), mode);
Spencer Low6815c072015-05-11 01:08:48 -07002366}
2367
Spencer Lowf373c352015-11-15 16:29:36 -08002368// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2369static inline size_t utf8_codepoint_len(uint8_t ch) {
2370 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2371}
Elliott Hughes37be38a2015-11-11 18:02:29 +00002372
Spencer Lowf373c352015-11-15 16:29:36 -08002373namespace internal {
2374
2375// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2376// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2377// remaining_bytes.
2378size_t ParseCompleteUTF8(const char* const first, const char* const last,
2379 std::vector<char>* const remaining_bytes) {
2380 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2381 // Current_after points one byte past the current byte to be examined.
2382 for (const char* current_after = last; current_after != first; --current_after) {
2383 const char* const current = current_after - 1;
2384 const char ch = *current;
2385 const char kHighBit = 0x80u;
2386 const char kTwoHighestBits = 0xC0u;
2387 if ((ch & kHighBit) == 0) { // high bit not set
2388 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2389 // bytes with no leading byte, so return the entire buffer.
2390 break;
2391 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2392 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2393 const size_t bytes_available = last - current;
2394 if (bytes_available < utf8_codepoint_len(ch)) {
2395 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2396 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2397 // to remaining_bytes.
2398 remaining_bytes->insert(remaining_bytes->end(), current, last);
2399 return current - first;
2400 } else {
2401 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2402 // trailing bytes with no lead byte, so return the entire buffer.
2403 break;
2404 }
2405 } else {
2406 // Trailing byte, so keep going backwards looking for the lead byte.
2407 }
2408 }
2409
2410 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2411 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2412 // so that they can be processed.
2413 return last - first;
2414}
2415
2416}
2417
2418// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2419// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2420// This matches the behavior of Linux.
Spencer Lowf373c352015-11-15 16:29:36 -08002421
2422// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2423static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2424 HANDLE console) {
Josh Gaoe7daf572016-09-21 12:37:10 -07002425 static std::mutex& console_output_buffer_lock = *new std::mutex();
2426 static auto& console_output_buffer = *new std::vector<char>();
2427
Spencer Lowf373c352015-11-15 16:29:36 -08002428 const int saved_errno = errno;
2429 std::vector<char> combined_buffer;
2430
2431 // Complete UTF-8 sequences that should be immediately written to the console.
2432 const char* utf8;
2433 size_t utf8_size;
2434
Josh Gaoe7daf572016-09-21 12:37:10 -07002435 {
2436 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2437 if (console_output_buffer.empty()) {
2438 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2439 // common case with plain ASCII), parse buf directly.
2440 utf8 = buf;
2441 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2442 } else {
2443 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2444 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2445 // combined_buffer, then parse it all together.
2446 combined_buffer.swap(console_output_buffer);
2447 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowf373c352015-11-15 16:29:36 -08002448
Josh Gaoe7daf572016-09-21 12:37:10 -07002449 utf8 = combined_buffer.data();
2450 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2451 &console_output_buffer);
2452 }
Spencer Lowf373c352015-11-15 16:29:36 -08002453 }
Spencer Lowf373c352015-11-15 16:29:36 -08002454
2455 std::wstring utf16;
2456
2457 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2458 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2459 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Low6815c072015-05-11 01:08:48 -07002460 // This could throw std::bad_alloc.
Spencer Lowf373c352015-11-15 16:29:36 -08002461 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Low6815c072015-05-11 01:08:48 -07002462
2463 // Note that this does not do \n => \r\n translation because that
2464 // doesn't seem necessary for the Windows console. For the Windows
2465 // console \r moves to the beginning of the line and \n moves to a new
2466 // line.
2467
2468 // Flush any stream buffering so that our output is afterwards which
2469 // makes sense because our call is afterwards.
2470 (void)fflush(stream);
2471
2472 // Write UTF-16 to the console.
2473 DWORD written = 0;
Yi Kong86e67182018-07-13 18:15:16 -07002474 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) {
Spencer Low6815c072015-05-11 01:08:48 -07002475 errno = EIO;
2476 return -1;
2477 }
2478
Spencer Lowf373c352015-11-15 16:29:36 -08002479 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2480 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2481 // matches the Linux behavior.
2482 errno = saved_errno;
2483 return buf_size;
Spencer Low6815c072015-05-11 01:08:48 -07002484}
2485
2486// Function prototype because attributes cannot be placed on func definitions.
Elliott Hughes874c9412018-06-26 13:06:15 -07002487static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap)
2488 __attribute__((__format__(__printf__, 3, 0)));
Spencer Low6815c072015-05-11 01:08:48 -07002489
2490// Internal function to format a UTF-8 string and write it to a Win32 console.
2491// Returns -1 on error.
2492static int _console_vfprintf(const HANDLE console, FILE* stream,
2493 const char *format, va_list ap) {
Spencer Lowf373c352015-11-15 16:29:36 -08002494 const int saved_errno = errno;
Spencer Low6815c072015-05-11 01:08:48 -07002495 std::string output_utf8;
2496
2497 // Format the string.
2498 // This could throw std::bad_alloc.
2499 android::base::StringAppendV(&output_utf8, format, ap);
2500
Spencer Lowf373c352015-11-15 16:29:36 -08002501 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2502 console);
2503 if (result != -1) {
2504 errno = saved_errno;
2505 } else {
2506 // If -1 was returned, errno has been set.
2507 }
2508 return result;
Spencer Low6815c072015-05-11 01:08:48 -07002509}
2510
2511// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2512// Windows console.
2513int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2514 const HANDLE console = _get_console_handle(stream);
2515
2516 // If there is an associated Win32 console, write to it specially,
2517 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kong86e67182018-07-13 18:15:16 -07002518 if (console != nullptr) {
Spencer Low6815c072015-05-11 01:08:48 -07002519 return _console_vfprintf(console, stream, format, ap);
2520 } else {
2521 // If vfprintf is a macro, undefine it, so we can call the real
2522 // C Runtime API.
2523#pragma push_macro("vfprintf")
2524#undef vfprintf
2525 return vfprintf(stream, format, ap);
2526#pragma pop_macro("vfprintf")
2527 }
2528}
2529
Spencer Lowf373c352015-11-15 16:29:36 -08002530// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2531int adb_vprintf(const char *format, va_list ap) {
2532 return adb_vfprintf(stdout, format, ap);
2533}
2534
Spencer Low6815c072015-05-11 01:08:48 -07002535// Version of fprintf() that takes UTF-8 and can write Unicode to a
2536// Windows console.
2537int adb_fprintf(FILE *stream, const char *format, ...) {
2538 va_list ap;
2539 va_start(ap, format);
2540 const int result = adb_vfprintf(stream, format, ap);
2541 va_end(ap);
2542
2543 return result;
2544}
2545
2546// Version of printf() that takes UTF-8 and can write Unicode to a
2547// Windows console.
2548int adb_printf(const char *format, ...) {
2549 va_list ap;
2550 va_start(ap, format);
2551 const int result = adb_vfprintf(stdout, format, ap);
2552 va_end(ap);
2553
2554 return result;
2555}
2556
2557// Version of fputs() that takes UTF-8 and can write Unicode to a
2558// Windows console.
2559int adb_fputs(const char* buf, FILE* stream) {
2560 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2561 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowf373c352015-11-15 16:29:36 -08002562 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Low6815c072015-05-11 01:08:48 -07002563 return adb_fprintf(stream, "%s", buf);
2564}
2565
2566// Version of fputc() that takes UTF-8 and can write Unicode to a
2567// Windows console.
2568int adb_fputc(int ch, FILE* stream) {
2569 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowf373c352015-11-15 16:29:36 -08002570 if (result == -1) {
Spencer Low6815c072015-05-11 01:08:48 -07002571 return EOF;
2572 }
2573 // For success, fputc returns the char, cast to unsigned char, then to int.
2574 return static_cast<unsigned char>(ch);
2575}
2576
Spencer Lowf373c352015-11-15 16:29:36 -08002577// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2578int adb_putchar(int ch) {
2579 return adb_fputc(ch, stdout);
2580}
2581
2582// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2583int adb_puts(const char* buf) {
2584 // adb_printf returns -1 on error, which is conveniently the same as EOF
2585 // which puts (and hence adb_puts) should return on error.
2586 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2587 return adb_printf("%s\n", buf);
2588}
2589
Spencer Low6815c072015-05-11 01:08:48 -07002590// Internal function to write UTF-8 to a Win32 console. Returns the number of
2591// items (of length size) written. On error, returns a short item count or 0.
2592static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2593 FILE* stream, HANDLE console) {
Spencer Lowf373c352015-11-15 16:29:36 -08002594 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2595 console);
Spencer Low6815c072015-05-11 01:08:48 -07002596 if (result == -1) {
2597 return 0;
2598 }
2599 return result / size;
2600}
2601
2602// Version of fwrite() that takes UTF-8 and can write Unicode to a
2603// Windows console.
2604size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2605 const HANDLE console = _get_console_handle(stream);
2606
2607 // If there is an associated Win32 console, write to it specially,
2608 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kong86e67182018-07-13 18:15:16 -07002609 if (console != nullptr) {
Spencer Low6815c072015-05-11 01:08:48 -07002610 return _console_fwrite(ptr, size, nmemb, stream, console);
2611 } else {
2612 // If fwrite is a macro, undefine it, so we can call the real
2613 // C Runtime API.
2614#pragma push_macro("fwrite")
2615#undef fwrite
2616 return fwrite(ptr, size, nmemb, stream);
2617#pragma pop_macro("fwrite")
2618 }
2619}
2620
2621// Version of fopen() that takes a UTF-8 filename and can access a file with
2622// a Unicode filename.
Spencer Low50f5bf12015-11-12 15:20:15 -08002623FILE* adb_fopen(const char* path, const char* mode) {
2624 std::wstring path_wide;
2625 if (!android::base::UTF8ToWide(path, &path_wide)) {
2626 return nullptr;
2627 }
2628
2629 std::wstring mode_wide;
2630 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2631 return nullptr;
2632 }
2633
2634 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002635}
2636
Spencer Low50740f52015-09-08 17:13:04 -07002637// Return a lowercase version of the argument. Uses C Runtime tolower() on
2638// each byte which is not UTF-8 aware, and theoretically uses the current C
2639// Runtime locale (which in practice is not changed, so this becomes a ASCII
2640// conversion).
2641static std::string ToLower(const std::string& anycase) {
2642 // copy string
2643 std::string str(anycase);
2644 // transform the copy
2645 std::transform(str.begin(), str.end(), str.begin(), tolower);
2646 return str;
2647}
2648
2649extern "C" int main(int argc, char** argv);
2650
2651// Link with -municode to cause this wmain() to be used as the program
2652// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2653// regular main() with UTF-8 args.
2654extern "C" int wmain(int argc, wchar_t **argv) {
2655 // Convert args from UTF-16 to UTF-8 and pass that to main().
2656 NarrowArgs narrow_args(argc, argv);
Josh Gaoe08e0452019-06-10 12:48:34 -07002657
2658 // Avoid destructing NarrowArgs: argv might have been mutated to point to string literals.
2659 _exit(main(argc, narrow_args.data()));
Spencer Low50740f52015-09-08 17:13:04 -07002660}
2661
Spencer Low6815c072015-05-11 01:08:48 -07002662// Shadow UTF-8 environment variable name/value pairs that are created from
Spencer Lowa0903682018-08-10 16:20:57 -07002663// _wenviron by _init_env(). Note that this is not currently updated if putenv, setenv, unsetenv are
2664// called. Note that no thread synchronization is done, but we're called early enough in
Spencer Lowcc467f12015-08-02 18:13:54 -07002665// single-threaded startup that things work ok.
Josh Gaoe3a87d02015-11-11 17:56:12 -08002666static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Low6815c072015-05-11 01:08:48 -07002667
Spencer Lowa0903682018-08-10 16:20:57 -07002668// Setup shadow UTF-8 environment variables.
2669static void _init_env() {
Spencer Low6815c072015-05-11 01:08:48 -07002670 // If some name/value pairs exist, then we've already done the setup below.
2671 if (g_environ_utf8.size() != 0) {
2672 return;
2673 }
2674
Spencer Low50740f52015-09-08 17:13:04 -07002675 if (_wenviron == nullptr) {
2676 // If _wenviron is null, then -municode probably wasn't used. That
2677 // linker flag will cause the entry point to setup _wenviron. It will
2678 // also require an implementation of wmain() (which we provide above).
Elliott Hughese64126b2018-10-19 13:59:44 -07002679 LOG(FATAL) << "_wenviron is not set, did you link with -municode?";
Spencer Low50740f52015-09-08 17:13:04 -07002680 }
2681
Spencer Low6815c072015-05-11 01:08:48 -07002682 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2683 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2684 // to use the D() macro here because that tracing only works if the
2685 // ADB_TRACE environment variable is setup, but that env var can't be read
2686 // until this code completes.
2687 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2688 wchar_t* const equal = wcschr(*env, L'=');
2689 if (equal == nullptr) {
2690 // Malformed environment variable with no equal sign. Shouldn't
2691 // really happen, but we should be resilient to this.
2692 continue;
2693 }
2694
Spencer Low50f5bf12015-11-12 15:20:15 -08002695 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2696 // var because the program might never even read this particular variable.
2697 std::string name_utf8;
2698 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2699 continue;
2700 }
2701
Spencer Low50740f52015-09-08 17:13:04 -07002702 // Store lowercase name so that we can do case-insensitive searches.
Spencer Low50f5bf12015-11-12 15:20:15 -08002703 name_utf8 = ToLower(name_utf8);
2704
2705 std::string value_utf8;
2706 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2707 continue;
2708 }
2709
2710 char* const value_dup = strdup(value_utf8.c_str());
Spencer Low6815c072015-05-11 01:08:48 -07002711
Spencer Low50740f52015-09-08 17:13:04 -07002712 // Don't overwrite a previus env var with the same name. In reality,
2713 // the system probably won't let two env vars with the same name exist
2714 // in _wenviron.
Spencer Low50f5bf12015-11-12 15:20:15 -08002715 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Low6815c072015-05-11 01:08:48 -07002716 }
2717}
2718
2719// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Low50740f52015-09-08 17:13:04 -07002720// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Low6815c072015-05-11 01:08:48 -07002721char* adb_getenv(const char* name) {
Spencer Low50740f52015-09-08 17:13:04 -07002722 // Case-insensitive search by searching for lowercase name in a map of
2723 // lowercase names.
2724 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Low6815c072015-05-11 01:08:48 -07002725 if (it == g_environ_utf8.end()) {
2726 return nullptr;
2727 }
2728
2729 return it->second;
2730}
2731
2732// Version of getcwd() that returns the current working directory in UTF-8.
2733char* adb_getcwd(char* buf, int size) {
2734 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2735 if (wbuf == nullptr) {
2736 return nullptr;
2737 }
2738
Spencer Low50f5bf12015-11-12 15:20:15 -08002739 std::string buf_utf8;
2740 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Low6815c072015-05-11 01:08:48 -07002741 free(wbuf);
2742 wbuf = nullptr;
2743
Spencer Low50f5bf12015-11-12 15:20:15 -08002744 if (!narrow_result) {
2745 return nullptr;
2746 }
2747
Spencer Low6815c072015-05-11 01:08:48 -07002748 // If size was specified, make sure all the chars will fit.
2749 if (size != 0) {
2750 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2751 errno = ERANGE;
2752 return nullptr;
2753 }
2754 }
2755
2756 // If buf was not specified, allocate storage.
2757 if (buf == nullptr) {
2758 if (size == 0) {
2759 size = buf_utf8.length() + 1;
2760 }
2761 buf = reinterpret_cast<char*>(malloc(size));
2762 if (buf == nullptr) {
2763 return nullptr;
2764 }
2765 }
2766
2767 // Destination buffer was allocated with enough space, or we've already
2768 // checked an existing buffer size for enough space.
2769 strcpy(buf, buf_utf8.c_str());
2770
2771 return buf;
2772}
Spencer Lowae37a312018-09-03 16:03:22 -07002773
2774// The SetThreadDescription API was brought in version 1607 of Windows 10.
2775typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);
2776
2777// Based on PlatformThread::SetName() from
2778// https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc
2779int adb_thread_setname(const std::string& name) {
2780 // The SetThreadDescription API works even if no debugger is attached.
2781 auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(
2782 ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
2783 if (set_thread_description_func) {
2784 std::wstring name_wide;
2785 if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) {
2786 return errno;
2787 }
2788 set_thread_description_func(::GetCurrentThread(), name_wide.c_str());
2789 }
2790
2791 // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions.
2792 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017
2793
2794 return 0;
2795}
Spencer Lowa0903682018-08-10 16:20:57 -07002796
2797#if !defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2798#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
2799#endif
2800
2801#if !defined(DISABLE_NEWLINE_AUTO_RETURN)
2802#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
2803#endif
2804
2805static void _init_console() {
2806 DWORD old_out_console_mode;
2807
2808 const HANDLE out = _get_console_handle(STDOUT_FILENO, &old_out_console_mode);
2809 if (out == nullptr) {
2810 return;
2811 }
2812
2813 // Try to use ENABLE_VIRTUAL_TERMINAL_PROCESSING on the output console to process virtual
2814 // terminal sequences on newer versions of Windows 10 and later.
2815 // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
2816 // On older OSes that don't support the flag, SetConsoleMode() will return an error.
2817 // ENABLE_VIRTUAL_TERMINAL_PROCESSING also solves a problem where the last column of the
2818 // console cannot be overwritten.
2819 //
2820 // Note that we don't use DISABLE_NEWLINE_AUTO_RETURN because it doesn't seem to be necessary.
2821 // If we use DISABLE_NEWLINE_AUTO_RETURN, _console_write_utf8() would need to be modified to
2822 // translate \n to \r\n.
2823 if (!SetConsoleMode(out, old_out_console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
2824 return;
2825 }
2826
2827 // If SetConsoleMode() succeeded, the console supports virtual terminal processing, so we
2828 // should set the TERM env var to match so that it will be propagated to adbd on devices.
2829 //
2830 // Below's direct manipulation of env vars and not g_environ_utf8 assumes that _init_env() has
2831 // not yet been called. If this fails, _init_env() should be called after _init_console().
2832 if (g_environ_utf8.size() > 0) {
2833 LOG(FATAL) << "environment variables have already been converted to UTF-8";
2834 }
2835
2836#pragma push_macro("getenv")
2837#undef getenv
2838#pragma push_macro("putenv")
2839#undef putenv
2840 if (getenv("TERM") == nullptr) {
2841 // This is the same TERM value used by Gnome Terminal and the version of ssh included with
2842 // Windows.
2843 putenv("TERM=xterm-256color");
2844 }
2845#pragma pop_macro("putenv")
2846#pragma pop_macro("getenv")
2847}
2848
2849static bool _init_sysdeps() {
2850 // _init_console() depends on _init_env() not being called yet.
2851 _init_console();
2852 _init_env();
2853 _init_winsock();
2854 return true;
2855}
2856
2857static bool _sysdeps_init = _init_sysdeps();