blob: 217a6b7f8957324d9cef25aeddad947a6799dcdb [file] [log] [blame]
Dan Albert33134262015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
Joshua Duongd85f5c02019-11-20 14:18:43 -080021#include <lmcons.h>
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Joshua Duongd85f5c02019-11-20 14:18:43 -080023#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Dan Albert33134262015-03-19 15:21:08 -070024
25#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080026#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080027#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070028
Spencer Lowe6ae5732015-09-08 17:13:04 -070029#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070030#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070031#include <mutex>
Spencer Low5200c662015-07-30 23:07:55 -070032#include <string>
Josh Gao0f29cbc2018-12-12 16:12:28 -080033#include <string_view>
Spencer Lowcf4ff642015-05-11 01:08:48 -070034#include <unordered_map>
Josh Gao3777d2e2016-02-16 17:34:53 -080035#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070036
Elliott Hughesd48dbd82015-07-24 11:35:40 -070037#include <cutils/sockets.h>
38
David Pursell5f787ed2016-01-27 08:52:53 -080039#include <android-base/errors.h>
Elliott Hughes4679a392018-10-19 13:59:44 -070040#include <android-base/file.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080041#include <android-base/logging.h>
Josh Gao116aa0a2018-04-05 17:55:25 -070042#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080043#include <android-base/stringprintf.h>
44#include <android-base/strings.h>
45#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070046
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047#include "adb.h"
Josh Gao3777d2e2016-02-16 17:34:53 -080048#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080049
Josh Gao116aa0a2018-04-05 17:55:25 -070050#include "sysdeps/uio.h"
51
Elliott Hughesa2f2e562015-04-16 16:47:02 -070052/* forward declarations */
53
54typedef const struct FHClassRec_* FHClass;
55typedef struct FHRec_* FH;
Elliott Hughesa2f2e562015-04-16 16:47:02 -070056
57typedef struct FHClassRec_ {
58 void (*_fh_init)(FH);
59 int (*_fh_close)(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070060 int64_t (*_fh_lseek)(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070061 int (*_fh_read)(FH, void*, int);
62 int (*_fh_write)(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070063 int (*_fh_writev)(FH, const adb_iovec*, int);
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070064 intptr_t (*_fh_get_os_handle)(FH);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070065} FHClassRec;
66
67static void _fh_file_init(FH);
68static int _fh_file_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070069static int64_t _fh_file_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070070static int _fh_file_read(FH, void*, int);
71static int _fh_file_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070072static int _fh_file_writev(FH, const adb_iovec*, int);
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070073static intptr_t _fh_file_get_os_handle(FH f);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070074
75static const FHClassRec _fh_file_class = {
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070076 _fh_file_init, _fh_file_close, _fh_file_lseek, _fh_file_read,
77 _fh_file_write, _fh_file_writev, _fh_file_get_os_handle,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070078};
79
80static void _fh_socket_init(FH);
81static int _fh_socket_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070082static int64_t _fh_socket_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070083static int _fh_socket_read(FH, void*, int);
84static int _fh_socket_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070085static int _fh_socket_writev(FH, const adb_iovec*, int);
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070086static intptr_t _fh_socket_get_os_handle(FH f);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070087
88static const FHClassRec _fh_socket_class = {
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070089 _fh_socket_init, _fh_socket_close, _fh_socket_lseek, _fh_socket_read,
90 _fh_socket_write, _fh_socket_writev, _fh_socket_get_os_handle,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070091};
92
Pirama Arumuga Nainar29e3dd82018-08-08 10:33:24 -070093#if defined(assert)
94#undef assert
95#endif
96
Spencer Low2122c7a2015-08-26 18:46:09 -070097void handle_deleter::operator()(HANDLE h) {
98 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
99 // implying that NULL is a valid handle, but this is probably impossible.
100 // Other APIs like CreateEvent() are documented to return NULL on error,
101 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
102 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
103 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
104 // only need to check for INVALID_HANDLE_VALUE.
105 if (h != INVALID_HANDLE_VALUE) {
106 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700107 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800108 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700109 }
110 }
111}
112
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800113/**************************************************************************/
114/**************************************************************************/
115/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800116/***** common file descriptor handling *****/
117/***** *****/
118/**************************************************************************/
119/**************************************************************************/
120
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800121typedef struct FHRec_
122{
123 FHClass clazz;
124 int used;
125 int eof;
126 union {
127 HANDLE handle;
128 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800129 } u;
130
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800131 char name[32];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800132} FHRec;
133
134#define fh_handle u.handle
135#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800136
Josh Gaob6232b92016-02-17 16:45:39 -0800137#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700138#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800139
Josh Gao0cd3ae12016-09-21 12:37:10 -0700140static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800141static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700142static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800143
Josh Gao27241a72019-04-25 14:04:57 -0700144static FH _fh_from_int(borrowed_fd bfd, const char* func) {
145 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800146
Josh Gao27241a72019-04-25 14:04:57 -0700147 int fd = bfd.get();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148 fd -= WIN32_FH_BASE;
149
Spencer Lowc3211552015-07-24 15:38:19 -0700150 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Josh Gao27241a72019-04-25 14:04:57 -0700151 D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800152 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700153 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800154 }
155
156 f = &_win32_fhs[fd];
157
158 if (f->used == 0) {
Josh Gao27241a72019-04-25 14:04:57 -0700159 D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800160 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700161 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800162 }
163
164 return f;
165}
166
Josh Gao27241a72019-04-25 14:04:57 -0700167static int _fh_to_int(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800168 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
169 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
170
171 return -1;
172}
173
Josh Gao27241a72019-04-25 14:04:57 -0700174static FH _fh_alloc(FHClass clazz) {
175 FH f = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800176
Josh Gao0cd3ae12016-09-21 12:37:10 -0700177 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800178
Josh Gaob6232b92016-02-17 16:45:39 -0800179 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
Yi Kongaed415c2018-07-13 18:15:16 -0700180 if (_win32_fhs[i].clazz == nullptr) {
Josh Gaob6232b92016-02-17 16:45:39 -0800181 f = &_win32_fhs[i];
182 _win32_fh_next = i + 1;
Josh Gao0cd3ae12016-09-21 12:37:10 -0700183 f->clazz = clazz;
184 f->used = 1;
185 f->eof = 0;
186 f->name[0] = '\0';
187 clazz->_fh_init(f);
188 return f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189 }
190 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700191
192 D("_fh_alloc: no more free file descriptors");
193 errno = EMFILE; // Too many open files
194 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800195}
196
Josh Gao27241a72019-04-25 14:04:57 -0700197static int _fh_close(FH f) {
Spencer Lowc3211552015-07-24 15:38:19 -0700198 // Use lock so that closing only happens once and so that _fh_alloc can't
199 // allocate a FH that we're in the middle of closing.
Josh Gao0cd3ae12016-09-21 12:37:10 -0700200 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800201
202 int offset = f - _win32_fhs;
203 if (_win32_fh_next > offset) {
204 _win32_fh_next = offset;
205 }
206
Spencer Lowc3211552015-07-24 15:38:19 -0700207 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800208 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700209 f->name[0] = '\0';
210 f->eof = 0;
211 f->used = 0;
Yi Kongaed415c2018-07-13 18:15:16 -0700212 f->clazz = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800213 }
214 return 0;
215}
216
Spencer Low5200c662015-07-30 23:07:55 -0700217// Deleter for unique_fh.
218class fh_deleter {
219 public:
220 void operator()(struct FHRec_* fh) {
221 // We're called from a destructor and destructors should not overwrite
222 // errno because callers may do:
223 // errno = EBLAH;
224 // return -1; // calls destructor, which should not overwrite errno
225 const int saved_errno = errno;
226 _fh_close(fh);
227 errno = saved_errno;
228 }
229};
230
231// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
232typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
233
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800234/**************************************************************************/
235/**************************************************************************/
236/***** *****/
237/***** file-based descriptor handling *****/
238/***** *****/
239/**************************************************************************/
240/**************************************************************************/
241
Josh Gao116aa0a2018-04-05 17:55:25 -0700242static void _fh_file_init(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800243 f->fh_handle = INVALID_HANDLE_VALUE;
244}
245
Josh Gao116aa0a2018-04-05 17:55:25 -0700246static int _fh_file_close(FH f) {
247 CloseHandle(f->fh_handle);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800248 f->fh_handle = INVALID_HANDLE_VALUE;
249 return 0;
250}
251
Josh Gao116aa0a2018-04-05 17:55:25 -0700252static int _fh_file_read(FH f, void* buf, int len) {
253 DWORD read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800254
Yi Kongaed415c2018-07-13 18:15:16 -0700255 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700256 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800257 errno = EIO;
258 return -1;
259 } else if (read_bytes < (DWORD)len) {
260 f->eof = 1;
261 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700262 return read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800263}
264
Josh Gao116aa0a2018-04-05 17:55:25 -0700265static int _fh_file_write(FH f, const void* buf, int len) {
266 DWORD wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800267
Yi Kongaed415c2018-07-13 18:15:16 -0700268 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700269 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800270 errno = EIO;
271 return -1;
272 } else if (wrote_bytes < (DWORD)len) {
273 f->eof = 1;
274 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700275 return wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800276}
277
Josh Gao116aa0a2018-04-05 17:55:25 -0700278static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
279 if (iovcnt <= 0) {
280 errno = EINVAL;
281 return -1;
282 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800283
Josh Gao116aa0a2018-04-05 17:55:25 -0700284 DWORD wrote_bytes = 0;
285
286 for (int i = 0; i < iovcnt; ++i) {
287 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
288 if (rc == -1) {
289 return wrote_bytes > 0 ? wrote_bytes : -1;
290 } else if (rc == 0) {
291 return wrote_bytes;
292 }
293
294 wrote_bytes += rc;
295
296 if (static_cast<size_t>(rc) < iov[i].iov_len) {
297 return wrote_bytes;
298 }
299 }
300
301 return wrote_bytes;
302}
303
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700304static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700305 DWORD method;
Josh Gao116aa0a2018-04-05 17:55:25 -0700306 switch (origin) {
307 case SEEK_SET:
308 method = FILE_BEGIN;
309 break;
310 case SEEK_CUR:
311 method = FILE_CURRENT;
312 break;
313 case SEEK_END:
314 method = FILE_END;
315 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800316 default:
317 errno = EINVAL;
318 return -1;
319 }
320
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700321 LARGE_INTEGER li = {.QuadPart = pos};
322 if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800323 errno = EIO;
324 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800325 }
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700326 f->eof = 0;
327 return li.QuadPart;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800328}
329
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700330static intptr_t _fh_file_get_os_handle(FH f) {
331 return reinterpret_cast<intptr_t>(f->u.handle);
332}
333
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800334/**************************************************************************/
335/**************************************************************************/
336/***** *****/
337/***** file-based descriptor handling *****/
338/***** *****/
339/**************************************************************************/
340/**************************************************************************/
341
Josh Gao64a63ac2018-04-05 18:09:02 -0700342int adb_open(const char* path, int options) {
343 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800344
Josh Gao64a63ac2018-04-05 18:09:02 -0700345 DWORD desiredAccess = 0;
346 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800347
Josh Gao4b019a52019-02-07 14:13:39 -0800348 // CreateFileW is inherently O_CLOEXEC by default.
349 options &= ~O_CLOEXEC;
350
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800351 switch (options) {
352 case O_RDONLY:
353 desiredAccess = GENERIC_READ;
354 break;
355 case O_WRONLY:
356 desiredAccess = GENERIC_WRITE;
357 break;
358 case O_RDWR:
359 desiredAccess = GENERIC_READ | GENERIC_WRITE;
360 break;
361 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700362 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363 errno = EINVAL;
364 return -1;
365 }
366
Josh Gao64a63ac2018-04-05 18:09:02 -0700367 f = _fh_alloc(&_fh_file_class);
368 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800369 return -1;
370 }
371
Spencer Lowd21dc822015-11-12 15:20:15 -0800372 std::wstring path_wide;
373 if (!android::base::UTF8ToWide(path, &path_wide)) {
374 return -1;
375 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700376 f->fh_handle =
Yi Kongaed415c2018-07-13 18:15:16 -0700377 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800378
Josh Gao64a63ac2018-04-05 18:09:02 -0700379 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700380 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800381 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700382 D("adb_open: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700383 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800384 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700385 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800386 errno = ENOENT;
387 return -1;
388
389 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700390 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391 errno = ENOTDIR;
392 return -1;
393
394 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800395 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800396 errno = ENOENT;
397 return -1;
398 }
399 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800400
Josh Gao64a63ac2018-04-05 18:09:02 -0700401 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
402 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800403 return _fh_to_int(f);
404}
405
406/* ignore mode on Win32 */
Josh Gao64a63ac2018-04-05 18:09:02 -0700407int adb_creat(const char* path, int mode) {
408 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409
Josh Gao64a63ac2018-04-05 18:09:02 -0700410 f = _fh_alloc(&_fh_file_class);
411 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800412 return -1;
413 }
414
Spencer Lowd21dc822015-11-12 15:20:15 -0800415 std::wstring path_wide;
416 if (!android::base::UTF8ToWide(path, &path_wide)) {
417 return -1;
418 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700419 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
Yi Kongaed415c2018-07-13 18:15:16 -0700420 nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800421
Josh Gao64a63ac2018-04-05 18:09:02 -0700422 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700423 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700425 D("adb_creat: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700426 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800427 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700428 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429 errno = ENOENT;
430 return -1;
431
432 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700433 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434 errno = ENOTDIR;
435 return -1;
436
437 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800438 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439 errno = ENOENT;
440 return -1;
441 }
442 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700443 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
444 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800445 return _fh_to_int(f);
446}
447
Josh Gao27241a72019-04-25 14:04:57 -0700448int adb_read(borrowed_fd fd, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700449 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800450
Yi Kongaed415c2018-07-13 18:15:16 -0700451 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700452 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800453 return -1;
454 }
455
Josh Gao116aa0a2018-04-05 17:55:25 -0700456 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800457}
458
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700459int adb_pread(borrowed_fd fd, void* buf, int len, off64_t offset) {
460 OVERLAPPED overlapped = {};
461 overlapped.Offset = static_cast<DWORD>(offset);
462 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
463 DWORD bytes_read;
464 if (!::ReadFile(adb_get_os_handle(fd), buf, static_cast<DWORD>(len), &bytes_read,
465 &overlapped)) {
466 D("adb_pread: could not read %d bytes from FD %d", len, fd.get());
467 switch (::GetLastError()) {
468 case ERROR_IO_PENDING:
469 errno = EAGAIN;
470 return -1;
471 default:
472 errno = EINVAL;
473 return -1;
474 }
475 }
476 return static_cast<int>(bytes_read);
477}
478
Josh Gao27241a72019-04-25 14:04:57 -0700479int adb_write(borrowed_fd fd, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700480 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800481
Yi Kongaed415c2018-07-13 18:15:16 -0700482 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700483 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800484 return -1;
485 }
486
487 return f->clazz->_fh_write(f, buf, len);
488}
489
Josh Gao27241a72019-04-25 14:04:57 -0700490ssize_t adb_writev(borrowed_fd fd, const adb_iovec* iov, int iovcnt) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700491 FH f = _fh_from_int(fd, __func__);
492
Yi Kongaed415c2018-07-13 18:15:16 -0700493 if (f == nullptr) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700494 errno = EBADF;
495 return -1;
496 }
497
498 return f->clazz->_fh_writev(f, iov, iovcnt);
499}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700501int adb_pwrite(borrowed_fd fd, const void* buf, int len, off64_t offset) {
502 OVERLAPPED params = {};
503 params.Offset = static_cast<DWORD>(offset);
504 params.OffsetHigh = static_cast<DWORD>(offset >> 32);
505 DWORD bytes_written = 0;
506 if (!::WriteFile(adb_get_os_handle(fd), buf, len, &bytes_written, &params)) {
507 D("adb_pwrite: could not write %d bytes to FD %d", len, fd.get());
508 switch (::GetLastError()) {
509 case ERROR_IO_PENDING:
510 errno = EAGAIN;
511 return -1;
512 default:
513 errno = EINVAL;
514 return -1;
515 }
516 }
517 return static_cast<int>(bytes_written);
518}
519
Josh Gao27241a72019-04-25 14:04:57 -0700520int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where) {
Josh Gao64a63ac2018-04-05 18:09:02 -0700521 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700523 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800524 return -1;
525 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526 return f->clazz->_fh_lseek(f, pos, where);
527}
528
Josh Gao64a63ac2018-04-05 18:09:02 -0700529int adb_close(int fd) {
530 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800531
532 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700533 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800534 return -1;
535 }
536
Josh Gao64a63ac2018-04-05 18:09:02 -0700537 D("adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800538 _fh_close(f);
539 return 0;
540}
541
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700542HANDLE adb_get_os_handle(borrowed_fd fd) {
543 FH f = _fh_from_int(fd, __func__);
544
545 if (!f) {
546 errno = EBADF;
547 return nullptr;
548 }
549
550 D("adb_get_os_handle: %s", f->name);
551 const intptr_t intptr_handle = f->clazz->_fh_get_os_handle(f);
552 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
553 return handle;
554}
555
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556/**************************************************************************/
557/**************************************************************************/
558/***** *****/
559/***** socket-based file descriptors *****/
560/***** *****/
561/**************************************************************************/
562/**************************************************************************/
563
Spencer Lowf055c192015-01-25 14:40:16 -0800564#undef setsockopt
565
Spencer Low5200c662015-07-30 23:07:55 -0700566static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700567 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
568 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gaoa3577e12016-12-05 13:24:48 -0800569 // are mapped to strings by adb_strerror().
Spencer Low5200c662015-07-30 23:07:55 -0700570 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800571 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700572 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
573 // case WSAEINTR: errno = EINTR; break;
574 case WSAEFAULT: errno = EFAULT; break;
575 case WSAEINVAL: errno = EINVAL; break;
576 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700577 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
578 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
579 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800580 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700581 case WSAENOTSOCK: errno = ENOTSOCK; break;
582 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
583 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
584 case WSAENETDOWN: errno = ENETDOWN; break;
585 case WSAENETRESET: errno = ENETRESET; break;
586 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
587 // to use EPIPE for these situations and there are some callers that look
588 // for EPIPE.
589 case WSAECONNABORTED: errno = EPIPE; break;
590 case WSAECONNRESET: errno = ECONNRESET; break;
591 case WSAENOBUFS: errno = ENOBUFS; break;
592 case WSAENOTCONN: errno = ENOTCONN; break;
593 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
594 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
595 // considerations: Reportedly send() can return zero on timeout, and POSIX
596 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
597 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
598 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800600 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700601 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700602 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800603 }
604}
605
Josh Gao3777d2e2016-02-16 17:34:53 -0800606extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
607 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
608 int skipped = 0;
609 std::vector<WSAPOLLFD> sockets;
610 std::vector<adb_pollfd*> original;
Josh Gao05fb45b2018-03-29 12:34:28 -0700611
Josh Gao3777d2e2016-02-16 17:34:53 -0800612 for (size_t i = 0; i < nfds; ++i) {
613 FH fh = _fh_from_int(fds[i].fd, __func__);
614 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
615 D("adb_poll received bad FD %d", fds[i].fd);
616 fds[i].revents = POLLNVAL;
617 ++skipped;
618 } else {
619 WSAPOLLFD wsapollfd = {
620 .fd = fh->u.socket,
621 .events = static_cast<short>(fds[i].events)
622 };
623 sockets.push_back(wsapollfd);
624 original.push_back(&fds[i]);
625 }
Spencer Low5200c662015-07-30 23:07:55 -0700626 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800627
628 if (sockets.empty()) {
629 return skipped;
630 }
631
Josh Gao05fb45b2018-03-29 12:34:28 -0700632 // If we have any invalid FDs in our FD set, make sure to return immediately.
633 if (skipped > 0) {
634 timeout = 0;
635 }
636
Josh Gao3777d2e2016-02-16 17:34:53 -0800637 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
638 if (result == SOCKET_ERROR) {
639 _socket_set_errno(WSAGetLastError());
640 return -1;
641 }
642
643 // Map the results back onto the original set.
644 for (size_t i = 0; i < sockets.size(); ++i) {
645 original[i]->revents = sockets[i].revents;
646 }
647
Josh Gao05fb45b2018-03-29 12:34:28 -0700648 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gao3777d2e2016-02-16 17:34:53 -0800649 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
650 // to do. Ignore its result and calculate the proper return value.
651 result = 0;
652 for (size_t i = 0; i < nfds; ++i) {
653 if (fds[i].revents != 0) {
654 ++result;
655 }
656 }
657 return result;
658}
659
660static void _fh_socket_init(FH f) {
661 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800662}
663
Josh Gao116aa0a2018-04-05 17:55:25 -0700664static int _fh_socket_close(FH f) {
Spencer Low5200c662015-07-30 23:07:55 -0700665 if (f->fh_socket != INVALID_SOCKET) {
Spencer Low5200c662015-07-30 23:07:55 -0700666 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800667 // Don't set errno here, since adb_close will ignore it.
668 const DWORD err = WSAGetLastError();
669 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700670 }
671 f->fh_socket = INVALID_SOCKET;
672 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800673 return 0;
674}
675
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700676static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677 errno = EPIPE;
678 return -1;
679}
680
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700681static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700682 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800683 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700684 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700685 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
686 // that to reduce spam and confusion.
687 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700688 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800689 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700690 }
Spencer Low5200c662015-07-30 23:07:55 -0700691 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800692 result = -1;
693 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700694 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800695}
696
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700697static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700698 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800699 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700700 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700701 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
702 // that to reduce spam and confusion.
703 if (err != WSAEWOULDBLOCK) {
704 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800705 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700706 }
Spencer Low5200c662015-07-30 23:07:55 -0700707 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800708 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700709 } else {
710 // According to https://code.google.com/p/chromium/issues/detail?id=27870
711 // Winsock Layered Service Providers may cause this.
Josh Gao116aa0a2018-04-05 17:55:25 -0700712 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
713 << result << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800714 }
715 return result;
716}
717
Josh Gao116aa0a2018-04-05 17:55:25 -0700718// Make sure that adb_iovec is compatible with WSABUF.
719static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
720static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
721static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
722
723static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
724static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
725
726static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
727 if (iovcnt <= 0) {
728 errno = EINVAL;
729 return -1;
730 }
731
732 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
733 DWORD bytes_written = 0;
734 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
735 if (result == SOCKET_ERROR) {
736 const DWORD err = WSAGetLastError();
737 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
738 // that to reduce spam and confusion.
739 if (err != WSAEWOULDBLOCK) {
740 D("send fd %d failed: %s", _fh_to_int(f),
741 android::base::SystemErrorCodeToString(err).c_str());
742 }
743 _socket_set_errno(err);
Josh Gao5ae4a902019-08-07 18:26:47 -0700744 return -1;
Josh Gao116aa0a2018-04-05 17:55:25 -0700745 }
746 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
747 return static_cast<int>(bytes_written);
748}
749
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700750static intptr_t _fh_socket_get_os_handle(FH f) {
751 return f->u.socket;
752}
753
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800754/**************************************************************************/
755/**************************************************************************/
756/***** *****/
757/***** replacement for libs/cutils/socket_xxxx.c *****/
758/***** *****/
759/**************************************************************************/
760/**************************************************************************/
761
Spencer Low14022c22018-08-10 16:20:57 -0700762static void _init_winsock() {
Josh Gao2e93df22018-04-05 18:10:03 -0700763 static std::once_flag once;
764 std::call_once(once, []() {
765 WSADATA wsaData;
766 int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800767 if (rc != 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700768 LOG(FATAL) << "could not initialize Winsock: "
769 << android::base::SystemErrorCodeToString(rc);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800770 }
Spencer Low87e97ee2015-08-12 18:19:16 -0700771
772 // Note that we do not call atexit() to register WSACleanup to be called
773 // at normal process termination because:
774 // 1) When exit() is called, there are still threads actively using
775 // Winsock because we don't cleanly shutdown all threads, so it
776 // doesn't make sense to call WSACleanup() and may cause problems
777 // with those threads.
778 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
779 // calls WSACleanup() which tries to unload a DLL, which tries to
780 // grab the LoaderLock. This conflicts with the device_poll_thread
781 // which holds the LoaderLock because AdbWinApi.dll calls
782 // setupapi.dll which tries to load wintrust.dll which tries to load
783 // crypt32.dll which calls atexit() which tries to acquire the C
784 // Runtime lock that the other thread holds.
Josh Gao2e93df22018-04-05 18:10:03 -0700785 });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800786}
787
Spencer Low677fb432015-09-29 15:05:29 -0700788// Map a socket type to an explicit socket protocol instead of using the socket
789// protocol of 0. Explicit socket protocols are used by most apps and we should
790// do the same to reduce the chance of exercising uncommon code-paths that might
791// have problems or that might load different Winsock service providers that
792// have problems.
793static int GetSocketProtocolFromSocketType(int type) {
794 switch (type) {
795 case SOCK_STREAM:
796 return IPPROTO_TCP;
797 case SOCK_DGRAM:
798 return IPPROTO_UDP;
799 default:
800 LOG(FATAL) << "Unknown socket type: " << type;
801 return 0;
802 }
803}
804
Spencer Low5200c662015-07-30 23:07:55 -0700805int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800806 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800807 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800808
Josh Gao6487e742016-02-18 13:43:55 -0800809 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700810 if (!f) {
811 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800812 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700813 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800814
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800815 memset(&addr, 0, sizeof(addr));
816 addr.sin_family = AF_INET;
817 addr.sin_port = htons(port);
818 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
819
Spencer Low677fb432015-09-29 15:05:29 -0700820 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800821 if (s == INVALID_SOCKET) {
822 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700823 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800824 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700825 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800826 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700827 return -1;
828 }
829 f->fh_socket = s;
830
Josh Gao6487e742016-02-18 13:43:55 -0800831 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700832 // Save err just in case inet_ntoa() or ntohs() changes the last error.
833 const DWORD err = WSAGetLastError();
834 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800835 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
836 android::base::SystemErrorCodeToString(err).c_str());
837 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
838 error->c_str());
839 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800840 return -1;
841 }
842
Spencer Low5200c662015-07-30 23:07:55 -0700843 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800844 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
845 port);
846 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700847 f.release();
848 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800849}
850
Spencer Low5200c662015-07-30 23:07:55 -0700851// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800852static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800854 SOCKET s;
855 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800856
Josh Gao6487e742016-02-18 13:43:55 -0800857 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800858 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700859 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800860 return -1;
861 }
862
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800863 memset(&addr, 0, sizeof(addr));
864 addr.sin_family = AF_INET;
865 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700866 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800867
Spencer Low5200c662015-07-30 23:07:55 -0700868 // TODO: Consider using dual-stack socket that can simultaneously listen on
869 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700870 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700871 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800872 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700873 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800874 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700875 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800876 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700877 return -1;
878 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800879
880 f->fh_socket = s;
881
Spencer Lowbf7c6052015-08-11 16:45:32 -0700882 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
883 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800884 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800885 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
886 const DWORD err = WSAGetLastError();
887 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
888 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700889 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800890 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700891 return -1;
892 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800893
Josh Gao6487e742016-02-18 13:43:55 -0800894 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700895 // Save err just in case inet_ntoa() or ntohs() changes the last error.
896 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800897 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
898 ntohs(addr.sin_port),
899 android::base::SystemErrorCodeToString(err).c_str());
900 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
901 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800902 return -1;
903 }
904 if (type == SOCK_STREAM) {
Josh Gaobf243a62018-03-20 14:25:03 -0700905 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800906 const DWORD err = WSAGetLastError();
907 *error = android::base::StringPrintf(
908 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
909 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
910 error->c_str());
911 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800912 return -1;
913 }
914 }
Spencer Low5200c662015-07-30 23:07:55 -0700915 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800916 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
917 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
918 port);
919 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700920 f.release();
921 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800922}
923
Callum Ryan8539cb32019-10-31 07:21:42 -0700924int network_loopback_server(int port, int type, std::string* error, bool prefer_ipv4) {
925 // TODO implement IPv6 support on windows
Spencer Low5200c662015-07-30 23:07:55 -0700926 return _network_server(port, type, INADDR_LOOPBACK, error);
927}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800928
Spencer Low5200c662015-07-30 23:07:55 -0700929int network_inaddr_any_server(int port, int type, std::string* error) {
930 return _network_server(port, type, INADDR_ANY, error);
931}
932
933int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
934 unique_fh f(_fh_alloc(&_fh_socket_class));
935 if (!f) {
936 *error = strerror(errno);
937 return -1;
938 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800939
Spencer Low5200c662015-07-30 23:07:55 -0700940 struct addrinfo hints;
941 memset(&hints, 0, sizeof(hints));
942 hints.ai_family = AF_UNSPEC;
943 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700944 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700945
946 char port_str[16];
947 snprintf(port_str, sizeof(port_str), "%d", port);
948
949 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700950
951#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800952// TODO: When the Android SDK tools increases the Windows system
953// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700954#else
Josh Gao6487e742016-02-18 13:43:55 -0800955// Otherwise, keep using getaddrinfo(), or do runtime API detection
956// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700957#endif
Spencer Low5200c662015-07-30 23:07:55 -0700958 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800959 const DWORD err = WSAGetLastError();
960 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
961 host.c_str(), port_str,
962 android::base::SystemErrorCodeToString(err).c_str());
963
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700964 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800965 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966 return -1;
967 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700968 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700969 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800970
Spencer Low5200c662015-07-30 23:07:55 -0700971 // TODO: Try all the addresses if there's more than one? This just uses
972 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
973 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800974 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
975 if (s == INVALID_SOCKET) {
976 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700977 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800978 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700979 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800980 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800981 return -1;
982 }
983 f->fh_socket = s;
984
Spencer Low5200c662015-07-30 23:07:55 -0700985 // TODO: Implement timeouts for Windows. Seems like the default in theory
986 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800987 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700988 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800989 const DWORD err = WSAGetLastError();
990 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
991 android::base::SystemErrorCodeToString(err).c_str());
992 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
993 port_str, error->c_str());
994 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 return -1;
996 }
997
Spencer Low5200c662015-07-30 23:07:55 -0700998 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800999 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
1000 port);
1001 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
1002 fd);
Spencer Low5200c662015-07-30 23:07:55 -07001003 f.release();
1004 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001005}
1006
Josh Gao64a63ac2018-04-05 18:09:02 -07001007int adb_register_socket(SOCKET s) {
1008 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001009 f->fh_socket = s;
1010 return _fh_to_int(f);
1011}
1012
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001013#undef accept
Josh Gao27241a72019-04-25 14:04:57 -07001014int adb_socket_accept(borrowed_fd serverfd, struct sockaddr* addr, socklen_t* addrlen) {
Josh Gao64a63ac2018-04-05 18:09:02 -07001015 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001016
Josh Gao64a63ac2018-04-05 18:09:02 -07001017 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001018 D("adb_socket_accept: invalid fd %d", serverfd.get());
Spencer Low5200c662015-07-30 23:07:55 -07001019 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001020 return -1;
1021 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001022
Josh Gao64a63ac2018-04-05 18:09:02 -07001023 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001024 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001025 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1026 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001027 return -1;
1028 }
1029
Josh Gao64a63ac2018-04-05 18:09:02 -07001030 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001031 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001032 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001033 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd.get()
Josh Gao64a63ac2018-04-05 18:09:02 -07001034 << " failed: " + android::base::SystemErrorCodeToString(err);
1035 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001036 return -1;
1037 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001038
Spencer Low5200c662015-07-30 23:07:55 -07001039 const int fd = _fh_to_int(fh.get());
Josh Gao64a63ac2018-04-05 18:09:02 -07001040 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
Josh Gao27241a72019-04-25 14:04:57 -07001041 D("adb_socket_accept on fd %d returns fd %d", serverfd.get(), fd);
Spencer Low5200c662015-07-30 23:07:55 -07001042 fh.release();
Josh Gao64a63ac2018-04-05 18:09:02 -07001043 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001044}
1045
Josh Gao27241a72019-04-25 14:04:57 -07001046int adb_setsockopt(borrowed_fd fd, int level, int optname, const void* optval, socklen_t optlen) {
Josh Gao64a63ac2018-04-05 18:09:02 -07001047 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001048
Josh Gao64a63ac2018-04-05 18:09:02 -07001049 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001050 D("adb_setsockopt: invalid fd %d", fd.get());
Spencer Low5200c662015-07-30 23:07:55 -07001051 errno = EBADF;
1052 return -1;
1053 }
Spencer Low677fb432015-09-29 15:05:29 -07001054
1055 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1056 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1057 // auto-tuning.
1058
Josh Gao64a63ac2018-04-05 18:09:02 -07001059 int result =
1060 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1061 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001062 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001063 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd.get(), level,
Josh Gao64a63ac2018-04-05 18:09:02 -07001064 optname, android::base::SystemErrorCodeToString(err).c_str());
1065 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -07001066 result = -1;
1067 }
1068 return result;
1069}
1070
Josh Gao27241a72019-04-25 14:04:57 -07001071static int adb_getsockname(borrowed_fd fd, struct sockaddr* sockaddr, socklen_t* optlen) {
Josh Gao3777d2e2016-02-16 17:34:53 -08001072 FH fh = _fh_from_int(fd, __func__);
1073
1074 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001075 D("adb_getsockname: invalid fd %d", fd.get());
Josh Gao3777d2e2016-02-16 17:34:53 -08001076 errno = EBADF;
1077 return -1;
1078 }
1079
Josh Gao3726a012017-03-30 13:04:35 -07001080 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001081 if (result == SOCKET_ERROR) {
1082 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001083 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd.get(),
Josh Gao3777d2e2016-02-16 17:34:53 -08001084 android::base::SystemErrorCodeToString(err).c_str());
1085 _socket_set_errno(err);
1086 result = -1;
1087 }
1088 return result;
1089}
Spencer Low5200c662015-07-30 23:07:55 -07001090
Josh Gao27241a72019-04-25 14:04:57 -07001091int adb_socket_get_local_port(borrowed_fd fd) {
David Purselleaae97e2016-04-07 11:25:48 -07001092 sockaddr_storage addr_storage;
1093 socklen_t addr_len = sizeof(addr_storage);
1094
1095 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1096 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1097 return -1;
1098 }
1099
1100 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1101 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1102 errno = ECONNABORTED;
1103 return -1;
1104 }
1105
1106 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1107}
1108
Josh Gao27241a72019-04-25 14:04:57 -07001109int adb_shutdown(borrowed_fd fd, int direction) {
Josh Gao2e1e7892018-03-23 13:03:28 -07001110 FH f = _fh_from_int(fd, __func__);
Spencer Low5200c662015-07-30 23:07:55 -07001111
1112 if (!f || f->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001113 D("adb_shutdown: invalid fd %d", fd.get());
Spencer Low5200c662015-07-30 23:07:55 -07001114 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001115 return -1;
1116 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001117
Josh Gao2e1e7892018-03-23 13:03:28 -07001118 D("adb_shutdown: %s", f->name);
1119 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001120 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001121 D("socket shutdown fd %d failed: %s", fd.get(),
David Pursell5f787ed2016-01-27 08:52:53 -08001122 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001123 _socket_set_errno(err);
1124 return -1;
1125 }
1126 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001127}
1128
Josh Gao3777d2e2016-02-16 17:34:53 -08001129// Emulate socketpair(2) by binding and connecting to a socket.
1130int adb_socketpair(int sv[2]) {
1131 int server = -1;
1132 int client = -1;
1133 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001134 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001135 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001136
Callum Ryan8539cb32019-10-31 07:21:42 -07001137 server = network_loopback_server(0, SOCK_STREAM, &error, true);
Josh Gao3777d2e2016-02-16 17:34:53 -08001138 if (server < 0) {
1139 D("adb_socketpair: failed to create server: %s", error.c_str());
1140 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001141 }
1142
David Purselleaae97e2016-04-07 11:25:48 -07001143 local_port = adb_socket_get_local_port(server);
1144 if (local_port < 0) {
1145 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001146 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001147 }
David Purselleaae97e2016-04-07 11:25:48 -07001148 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001149
David Purselleaae97e2016-04-07 11:25:48 -07001150 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001151 if (client < 0) {
1152 D("adb_socketpair: failed to connect client: %s", error.c_str());
1153 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154 }
1155
Josh Gao3726a012017-03-30 13:04:35 -07001156 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gao3777d2e2016-02-16 17:34:53 -08001157 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001158 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001159 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001160 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001161 adb_close(server);
1162 sv[0] = client;
1163 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001164 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001165
Josh Gao3777d2e2016-02-16 17:34:53 -08001166fail:
1167 if (server >= 0) {
1168 adb_close(server);
1169 }
1170 if (client >= 0) {
1171 adb_close(client);
1172 }
1173 if (accepted >= 0) {
1174 adb_close(accepted);
1175 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001176 return -1;
1177}
1178
Josh Gao27241a72019-04-25 14:04:57 -07001179bool set_file_block_mode(borrowed_fd fd, bool block) {
Josh Gao3777d2e2016-02-16 17:34:53 -08001180 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001181
Josh Gao3777d2e2016-02-16 17:34:53 -08001182 if (!fh || !fh->used) {
1183 errno = EBADF;
Josh Gao27241a72019-04-25 14:04:57 -07001184 D("Setting nonblocking on bad file descriptor %d", fd.get());
Josh Gao3777d2e2016-02-16 17:34:53 -08001185 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001186 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001187
Josh Gao3777d2e2016-02-16 17:34:53 -08001188 if (fh->clazz == &_fh_socket_class) {
1189 u_long x = !block;
1190 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001191 int error = WSAGetLastError();
1192 _socket_set_errno(error);
Josh Gao27241a72019-04-25 14:04:57 -07001193 D("Setting %d nonblocking failed (%d)", fd.get(), error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001194 return false;
1195 }
1196 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001197 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001198 errno = ENOTSOCK;
Josh Gao27241a72019-04-25 14:04:57 -07001199 D("Setting nonblocking on non-socket %d", fd.get());
Josh Gao3777d2e2016-02-16 17:34:53 -08001200 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001201 }
1202}
1203
Josh Gao27241a72019-04-25 14:04:57 -07001204bool set_tcp_keepalive(borrowed_fd fd, int interval_sec) {
David Pursellbfd95032016-02-22 14:27:23 -08001205 FH fh = _fh_from_int(fd, __func__);
1206
1207 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001208 D("set_tcp_keepalive(%d) failed: invalid fd", fd.get());
David Pursellbfd95032016-02-22 14:27:23 -08001209 errno = EBADF;
1210 return false;
1211 }
1212
1213 tcp_keepalive keepalive;
1214 keepalive.onoff = (interval_sec > 0);
1215 keepalive.keepalivetime = interval_sec * 1000;
1216 keepalive.keepaliveinterval = interval_sec * 1000;
1217
1218 DWORD bytes_returned = 0;
1219 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1220 &bytes_returned, nullptr, nullptr) != 0) {
1221 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001222 D("set_tcp_keepalive(%d) failed: %s", fd.get(),
David Pursellbfd95032016-02-22 14:27:23 -08001223 android::base::SystemErrorCodeToString(err).c_str());
1224 _socket_set_errno(err);
1225 return false;
1226 }
1227
1228 return true;
1229}
1230
Spencer Low50184062015-03-01 15:06:21 -08001231/**************************************************************************/
1232/**************************************************************************/
1233/***** *****/
1234/***** Console Window Terminal Emulation *****/
1235/***** *****/
1236/**************************************************************************/
1237/**************************************************************************/
1238
1239// This reads input from a Win32 console window and translates it into Unix
1240// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1241// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1242// is emulated instead of xterm because it is probably more popular than xterm:
1243// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1244// supports modern fonts, etc. It seems best to emulate the terminal that most
1245// Android developers use because they'll fix apps (the shell, etc.) to keep
1246// working with that terminal's emulation.
1247//
1248// The point of this emulation is not to be perfect or to solve all issues with
1249// console windows on Windows, but to be better than the original code which
1250// just called read() (which called ReadFile(), which called ReadConsoleA())
1251// which did not support Ctrl-C, tab completion, shell input line editing
1252// keys, server echo, and more.
1253//
1254// This implementation reconfigures the console with SetConsoleMode(), then
1255// calls ReadConsoleInput() to get raw input which it remaps to Unix
1256// terminal-style sequences which is returned via unix_read() which is used
1257// by the 'adb shell' command.
1258//
1259// Code organization:
1260//
David Pursellc5b8ad82015-10-28 14:29:51 -07001261// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001262// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1263// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1264// * _console_read() is the main code of the emulation.
1265
David Pursellc5b8ad82015-10-28 14:29:51 -07001266// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1267// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1268// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
Josh Gao27241a72019-04-25 14:04:57 -07001269static HANDLE _get_console_handle(borrowed_fd fd, DWORD* mode = nullptr) {
David Pursellc5b8ad82015-10-28 14:29:51 -07001270 // First check isatty(); this is very fast and eliminates most non-console
1271 // FDs, but returns 1 for both consoles and character devices like NUL.
1272#pragma push_macro("isatty")
1273#undef isatty
Josh Gao27241a72019-04-25 14:04:57 -07001274 if (!isatty(fd.get())) {
David Pursellc5b8ad82015-10-28 14:29:51 -07001275 return nullptr;
1276 }
1277#pragma pop_macro("isatty")
1278
1279 // To differentiate between character devices and consoles we need to get
1280 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1281 // GENERIC_READ permissions.
Josh Gao27241a72019-04-25 14:04:57 -07001282 const intptr_t intptr_handle = _get_osfhandle(fd.get());
David Pursellc5b8ad82015-10-28 14:29:51 -07001283 if (intptr_handle == -1) {
1284 return nullptr;
1285 }
1286 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1287 DWORD temp_mode = 0;
1288 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1289 return nullptr;
1290 }
1291
1292 return handle;
1293}
1294
1295// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1296static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001297 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1298 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001299 const int fd = fileno(stream);
1300 if (fd < 0) {
1301 return nullptr;
1302 }
1303 return _get_console_handle(fd);
1304}
1305
Josh Gao27241a72019-04-25 14:04:57 -07001306int unix_isatty(borrowed_fd fd) {
David Pursellc5b8ad82015-10-28 14:29:51 -07001307 return _get_console_handle(fd) ? 1 : 0;
1308}
Spencer Low50184062015-03-01 15:06:21 -08001309
Spencer Low32762f42015-11-10 19:17:16 -08001310// Get the next KEY_EVENT_RECORD that should be processed.
1311static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001312 for (;;) {
1313 DWORD read_count = 0;
1314 memset(input_record, 0, sizeof(*input_record));
1315 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001316 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001317 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001318 errno = EIO;
1319 return false;
1320 }
1321
1322 if (read_count == 0) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001323 LOG(FATAL) << "ReadConsoleInputA returned 0";
Spencer Low50184062015-03-01 15:06:21 -08001324 }
1325
1326 if (read_count != 1) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001327 LOG(FATAL) << "ReadConsoleInputA did not return one input record";
Spencer Low50184062015-03-01 15:06:21 -08001328 }
1329
Spencer Low2e02dc62015-11-07 17:34:39 -08001330 // If the console window is resized, emulate SIGWINCH by breaking out
1331 // of read() with errno == EINTR. Note that there is no event on
1332 // vertical resize because we don't give the console our own custom
1333 // screen buffer (with CreateConsoleScreenBuffer() +
1334 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1335 // supports scrollback, but doesn't seem to raise an event for vertical
1336 // window resize.
1337 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1338 errno = EINTR;
1339 return false;
1340 }
1341
Spencer Low50184062015-03-01 15:06:21 -08001342 if ((input_record->EventType == KEY_EVENT) &&
1343 (input_record->Event.KeyEvent.bKeyDown)) {
1344 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -07001345 LOG(FATAL) << "ReadConsoleInputA returned a key event with zero repeat count";
Spencer Low50184062015-03-01 15:06:21 -08001346 }
1347
1348 // Got an interesting INPUT_RECORD, so return
1349 return true;
1350 }
1351 }
1352}
1353
Spencer Low50184062015-03-01 15:06:21 -08001354static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1355 return (control_key_state & SHIFT_PRESSED) != 0;
1356}
1357
1358static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1359 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1360}
1361
1362static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1363 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1364}
1365
1366static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1367 return (control_key_state & NUMLOCK_ON) != 0;
1368}
1369
1370static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1371 return (control_key_state & CAPSLOCK_ON) != 0;
1372}
1373
1374static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1375 return (control_key_state & ENHANCED_KEY) != 0;
1376}
1377
1378// Constants from MSDN for ToAscii().
1379static const BYTE TOASCII_KEY_OFF = 0x00;
1380static const BYTE TOASCII_KEY_DOWN = 0x80;
1381static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1382
1383// Given a key event, ignore a modifier key and return the character that was
1384// entered without the modifier. Writes to *ch and returns the number of bytes
1385// written.
1386static size_t _get_char_ignoring_modifier(char* const ch,
1387 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1388 const WORD modifier) {
1389 // If there is no character from Windows, try ignoring the specified
1390 // modifier and look for a character. Note that if AltGr is being used,
1391 // there will be a character from Windows.
1392 if (key_event->uChar.AsciiChar == '\0') {
1393 // Note that we read the control key state from the passed in argument
1394 // instead of from key_event since the argument has been normalized.
1395 if (((modifier == VK_SHIFT) &&
1396 _is_shift_pressed(control_key_state)) ||
1397 ((modifier == VK_CONTROL) &&
1398 _is_ctrl_pressed(control_key_state)) ||
1399 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1400
1401 BYTE key_state[256] = {0};
1402 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1403 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1404 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1405 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1406 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1407 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1408 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1409 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1410
1411 // cause this modifier to be ignored
1412 key_state[modifier] = TOASCII_KEY_OFF;
1413
1414 WORD translated = 0;
1415 if (ToAscii(key_event->wVirtualKeyCode,
1416 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1417 // Ignoring the modifier, we found a character.
1418 *ch = (CHAR)translated;
1419 return 1;
1420 }
1421 }
1422 }
1423
1424 // Just use whatever Windows told us originally.
1425 *ch = key_event->uChar.AsciiChar;
1426
1427 // If the character from Windows is NULL, return a size of zero.
1428 return (*ch == '\0') ? 0 : 1;
1429}
1430
1431// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1432// but taking into account the shift key. This is because for a sequence like
1433// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1434// we want to find the character ')'.
1435//
1436// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1437// because it is the default key-sequence to switch the input language.
1438// This is configurable in the Region and Language control panel.
1439static __inline__ size_t _get_non_control_char(char* const ch,
1440 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1441 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1442 VK_CONTROL);
1443}
1444
1445// Get without Alt.
1446static __inline__ size_t _get_non_alt_char(char* const ch,
1447 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1448 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1449 VK_MENU);
1450}
1451
1452// Ignore the control key, find the character from Windows, and apply any
1453// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1454// *pch and returns number of bytes written.
1455static size_t _get_control_character(char* const pch,
1456 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1457 const size_t len = _get_non_control_char(pch, key_event,
1458 control_key_state);
1459
1460 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1461 char ch = *pch;
1462 switch (ch) {
1463 case '2':
1464 case '@':
1465 case '`':
1466 ch = '\0';
1467 break;
1468 case '3':
1469 case '[':
1470 case '{':
1471 ch = '\x1b';
1472 break;
1473 case '4':
1474 case '\\':
1475 case '|':
1476 ch = '\x1c';
1477 break;
1478 case '5':
1479 case ']':
1480 case '}':
1481 ch = '\x1d';
1482 break;
1483 case '6':
1484 case '^':
1485 case '~':
1486 ch = '\x1e';
1487 break;
1488 case '7':
1489 case '-':
1490 case '_':
1491 ch = '\x1f';
1492 break;
1493 case '8':
1494 ch = '\x7f';
1495 break;
1496 case '/':
1497 if (!_is_alt_pressed(control_key_state)) {
1498 ch = '\x1f';
1499 }
1500 break;
1501 case '?':
1502 if (!_is_alt_pressed(control_key_state)) {
1503 ch = '\x7f';
1504 }
1505 break;
1506 }
1507 *pch = ch;
1508 }
1509
1510 return len;
1511}
1512
1513static DWORD _normalize_altgr_control_key_state(
1514 const KEY_EVENT_RECORD* const key_event) {
1515 DWORD control_key_state = key_event->dwControlKeyState;
1516
1517 // If we're in an AltGr situation where the AltGr key is down (depending on
1518 // the keyboard layout, that might be the physical right alt key which
1519 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1520 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1521 // a character (which indicates that there was an AltGr mapping), then act
1522 // as if alt and control are not really down for the purposes of modifiers.
1523 // This makes it so that if the user with, say, a German keyboard layout
1524 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1525 // output the key and we don't see the Alt and Ctrl keys.
1526 if (_is_ctrl_pressed(control_key_state) &&
1527 _is_alt_pressed(control_key_state)
1528 && (key_event->uChar.AsciiChar != '\0')) {
1529 // Try to remove as few bits as possible to improve our chances of
1530 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1531 // Left-Alt + Right-Ctrl + AltGr.
1532 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1533 // Remove Right-Alt.
1534 control_key_state &= ~RIGHT_ALT_PRESSED;
1535 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1536 // pressed, Left-Ctrl is almost always set, except if the user
1537 // presses Right-Ctrl, then AltGr (in that specific order) for
1538 // whatever reason. At any rate, make sure the bit is not set.
1539 control_key_state &= ~LEFT_CTRL_PRESSED;
1540 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1541 // Remove Left-Alt.
1542 control_key_state &= ~LEFT_ALT_PRESSED;
1543 // Whichever Ctrl key is down, remove it from the state. We only
1544 // remove one key, to improve our chances of detecting the
1545 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1546 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1547 // Remove Left-Ctrl.
1548 control_key_state &= ~LEFT_CTRL_PRESSED;
1549 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1550 // Remove Right-Ctrl.
1551 control_key_state &= ~RIGHT_CTRL_PRESSED;
1552 }
1553 }
1554
1555 // Note that this logic isn't 100% perfect because Windows doesn't
1556 // allow us to detect all combinations because a physical AltGr key
1557 // press shows up as two bits, plus some combinations are ambiguous
1558 // about what is actually physically pressed.
1559 }
1560
1561 return control_key_state;
1562}
1563
1564// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1565// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1566// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1567// appropriately.
1568static DWORD _normalize_keypad_control_key_state(const WORD vk,
1569 const DWORD control_key_state) {
1570 if (!_is_numlock_on(control_key_state)) {
1571 return control_key_state;
1572 }
1573 if (!_is_enhanced_key(control_key_state)) {
1574 switch (vk) {
1575 case VK_INSERT: // 0
1576 case VK_DELETE: // .
1577 case VK_END: // 1
1578 case VK_DOWN: // 2
1579 case VK_NEXT: // 3
1580 case VK_LEFT: // 4
1581 case VK_CLEAR: // 5
1582 case VK_RIGHT: // 6
1583 case VK_HOME: // 7
1584 case VK_UP: // 8
1585 case VK_PRIOR: // 9
1586 return control_key_state | SHIFT_PRESSED;
1587 }
1588 }
1589
1590 return control_key_state;
1591}
1592
1593static const char* _get_keypad_sequence(const DWORD control_key_state,
1594 const char* const normal, const char* const shifted) {
1595 if (_is_shift_pressed(control_key_state)) {
1596 // Shift is pressed and NumLock is off
1597 return shifted;
1598 } else {
1599 // Shift is not pressed and NumLock is off, or,
1600 // Shift is pressed and NumLock is on, in which case we want the
1601 // NumLock and Shift to neutralize each other, thus, we want the normal
1602 // sequence.
1603 return normal;
1604 }
1605 // If Shift is not pressed and NumLock is on, a different virtual key code
1606 // is returned by Windows, which can be taken care of by a different case
1607 // statement in _console_read().
1608}
1609
1610// Write sequence to buf and return the number of bytes written.
1611static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1612 DWORD control_key_state, const char* const normal) {
1613 // Copy the base sequence into buf.
1614 const size_t len = strlen(normal);
1615 memcpy(buf, normal, len);
1616
1617 int code = 0;
1618
1619 control_key_state = _normalize_keypad_control_key_state(vk,
1620 control_key_state);
1621
1622 if (_is_shift_pressed(control_key_state)) {
1623 code |= 0x1;
1624 }
1625 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1626 code |= 0x2;
1627 }
1628 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1629 code |= 0x4;
1630 }
1631 // If some modifier was held down, then we need to insert the modifier code
1632 if (code != 0) {
1633 if (len == 0) {
1634 // Should be impossible because caller should pass a string of
1635 // non-zero length.
1636 return 0;
1637 }
1638 size_t index = len - 1;
1639 const char lastChar = buf[index];
1640 if (lastChar != '~') {
1641 buf[index++] = '1';
1642 }
1643 buf[index++] = ';'; // modifier separator
1644 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1645 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1646 buf[index++] = '1' + code;
1647 buf[index++] = lastChar; // move ~ (or other last char) to the end
1648 return index;
1649 }
1650 return len;
1651}
1652
1653// Write sequence to buf and return the number of bytes written.
1654static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1655 const DWORD control_key_state, const char* const normal,
1656 const char shifted) {
1657 if (_is_shift_pressed(control_key_state)) {
1658 // Shift is pressed and NumLock is off
1659 if (shifted != '\0') {
1660 buf[0] = shifted;
1661 return sizeof(buf[0]);
1662 } else {
1663 return 0;
1664 }
1665 } else {
1666 // Shift is not pressed and NumLock is off, or,
1667 // Shift is pressed and NumLock is on, in which case we want the
1668 // NumLock and Shift to neutralize each other, thus, we want the normal
1669 // sequence.
1670 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1671 }
1672 // If Shift is not pressed and NumLock is on, a different virtual key code
1673 // is returned by Windows, which can be taken care of by a different case
1674 // statement in _console_read().
1675}
1676
1677// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1678// Standard German. Figure this out at runtime so we know what to output for
1679// Shift-VK_DELETE.
1680static char _get_decimal_char() {
1681 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1682}
1683
1684// Prefix the len bytes in buf with the escape character, and then return the
1685// new buffer length.
Josh Gao27241a72019-04-25 14:04:57 -07001686static size_t _escape_prefix(char* const buf, const size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08001687 // If nothing to prefix, don't do anything. We might be called with
1688 // len == 0, if alt was held down with a dead key which produced nothing.
1689 if (len == 0) {
1690 return 0;
1691 }
1692
1693 memmove(&buf[1], buf, len);
1694 buf[0] = '\x1b';
1695 return len + 1;
1696}
1697
Spencer Low32762f42015-11-10 19:17:16 -08001698// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001699static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001700
1701// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1702// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001703static int _console_read(const HANDLE console, void* buf, size_t len) {
1704 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001705 // Read of zero bytes should not block waiting for something from the console.
1706 if (len == 0) {
1707 return 0;
1708 }
1709
1710 // Flush as much as possible from input buffer.
1711 if (!g_console_input_buffer.empty()) {
1712 const int bytes_read = std::min(len, g_console_input_buffer.size());
1713 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1714 const auto begin = g_console_input_buffer.begin();
1715 g_console_input_buffer.erase(begin, begin + bytes_read);
1716 return bytes_read;
1717 }
1718
1719 // Read from the actual console. This may block until input.
1720 INPUT_RECORD input_record;
1721 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001722 return -1;
1723 }
1724
Spencer Low32762f42015-11-10 19:17:16 -08001725 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001726 const WORD vk = key_event->wVirtualKeyCode;
1727 const CHAR ch = key_event->uChar.AsciiChar;
1728 const DWORD control_key_state = _normalize_altgr_control_key_state(
1729 key_event);
1730
1731 // The following emulation code should write the output sequence to
1732 // either seqstr or to seqbuf and seqbuflen.
Yi Kongaed415c2018-07-13 18:15:16 -07001733 const char* seqstr = nullptr; // NULL terminated C-string
Spencer Low50184062015-03-01 15:06:21 -08001734 // Enough space for max sequence string below, plus modifiers and/or
1735 // escape prefix.
1736 char seqbuf[16];
1737 size_t seqbuflen = 0; // Space used in seqbuf.
1738
1739#define MATCH(vk, normal) \
1740 case (vk): \
1741 { \
1742 seqstr = (normal); \
1743 } \
1744 break;
1745
1746 // Modifier keys should affect the output sequence.
1747#define MATCH_MODIFIER(vk, normal) \
1748 case (vk): \
1749 { \
1750 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1751 control_key_state, (normal)); \
1752 } \
1753 break;
1754
1755 // The shift key should affect the output sequence.
1756#define MATCH_KEYPAD(vk, normal, shifted) \
1757 case (vk): \
1758 { \
1759 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1760 (shifted)); \
1761 } \
1762 break;
1763
1764 // The shift key and other modifier keys should affect the output
1765 // sequence.
1766#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1767 case (vk): \
1768 { \
1769 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1770 control_key_state, (normal), (shifted)); \
1771 } \
1772 break;
1773
1774#define ESC "\x1b"
1775#define CSI ESC "["
1776#define SS3 ESC "O"
1777
1778 // Only support normal mode, not application mode.
1779
1780 // Enhanced keys:
1781 // * 6-pack: insert, delete, home, end, page up, page down
1782 // * cursor keys: up, down, right, left
1783 // * keypad: divide, enter
1784 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1785 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1786 if (_is_enhanced_key(control_key_state)) {
1787 switch (vk) {
1788 case VK_RETURN: // Enter key on keypad
1789 if (_is_ctrl_pressed(control_key_state)) {
1790 seqstr = "\n";
1791 } else {
1792 seqstr = "\r";
1793 }
1794 break;
1795
1796 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1797 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1798
1799 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1800 // will be fixed soon to match xterm which sends CSI "F" and
1801 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1802 MATCH(VK_END, CSI "F");
1803 MATCH(VK_HOME, CSI "H");
1804
1805 MATCH_MODIFIER(VK_LEFT, CSI "D");
1806 MATCH_MODIFIER(VK_UP, CSI "A");
1807 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1808 MATCH_MODIFIER(VK_DOWN, CSI "B");
1809
1810 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1811 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1812
1813 MATCH(VK_DIVIDE, "/");
1814 }
1815 } else { // Non-enhanced keys:
1816 switch (vk) {
1817 case VK_BACK: // backspace
1818 if (_is_alt_pressed(control_key_state)) {
1819 seqstr = ESC "\x7f";
1820 } else {
1821 seqstr = "\x7f";
1822 }
1823 break;
1824
1825 case VK_TAB:
1826 if (_is_shift_pressed(control_key_state)) {
1827 seqstr = CSI "Z";
1828 } else {
1829 seqstr = "\t";
1830 }
1831 break;
1832
1833 // Number 5 key in keypad when NumLock is off, or if NumLock is
1834 // on and Shift is down.
1835 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1836
1837 case VK_RETURN: // Enter key on main keyboard
1838 if (_is_alt_pressed(control_key_state)) {
1839 seqstr = ESC "\n";
1840 } else if (_is_ctrl_pressed(control_key_state)) {
1841 seqstr = "\n";
1842 } else {
1843 seqstr = "\r";
1844 }
1845 break;
1846
1847 // VK_ESCAPE: Don't do any special handling. The OS uses many
1848 // of the sequences with Escape and many of the remaining
1849 // sequences don't produce bKeyDown messages, only !bKeyDown
1850 // for whatever reason.
1851
1852 case VK_SPACE:
1853 if (_is_alt_pressed(control_key_state)) {
1854 seqstr = ESC " ";
1855 } else if (_is_ctrl_pressed(control_key_state)) {
1856 seqbuf[0] = '\0'; // NULL char
1857 seqbuflen = 1;
1858 } else {
1859 seqstr = " ";
1860 }
1861 break;
1862
1863 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1864 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1865
1866 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1867 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1868
1869 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1870 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1871 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1872 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1873
1874 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1875 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1876 _get_decimal_char());
1877
1878 case 0x30: // 0
1879 case 0x31: // 1
1880 case 0x39: // 9
1881 case VK_OEM_1: // ;:
1882 case VK_OEM_PLUS: // =+
1883 case VK_OEM_COMMA: // ,<
1884 case VK_OEM_PERIOD: // .>
1885 case VK_OEM_7: // '"
1886 case VK_OEM_102: // depends on keyboard, could be <> or \|
1887 case VK_OEM_2: // /?
1888 case VK_OEM_3: // `~
1889 case VK_OEM_4: // [{
1890 case VK_OEM_5: // \|
1891 case VK_OEM_6: // ]}
1892 {
1893 seqbuflen = _get_control_character(seqbuf, key_event,
1894 control_key_state);
1895
1896 if (_is_alt_pressed(control_key_state)) {
1897 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1898 }
1899 }
1900 break;
1901
1902 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001903 case 0x33: // 3
1904 case 0x34: // 4
1905 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001906 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001907 case 0x37: // 7
1908 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001909 case VK_OEM_MINUS: // -_
1910 {
1911 seqbuflen = _get_control_character(seqbuf, key_event,
1912 control_key_state);
1913
1914 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1915 // prefix with escape.
1916 if (_is_alt_pressed(control_key_state) &&
1917 !(_is_ctrl_pressed(control_key_state) &&
1918 !_is_shift_pressed(control_key_state))) {
1919 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1920 }
1921 }
1922 break;
1923
Spencer Low50184062015-03-01 15:06:21 -08001924 case 0x41: // a
1925 case 0x42: // b
1926 case 0x43: // c
1927 case 0x44: // d
1928 case 0x45: // e
1929 case 0x46: // f
1930 case 0x47: // g
1931 case 0x48: // h
1932 case 0x49: // i
1933 case 0x4a: // j
1934 case 0x4b: // k
1935 case 0x4c: // l
1936 case 0x4d: // m
1937 case 0x4e: // n
1938 case 0x4f: // o
1939 case 0x50: // p
1940 case 0x51: // q
1941 case 0x52: // r
1942 case 0x53: // s
1943 case 0x54: // t
1944 case 0x55: // u
1945 case 0x56: // v
1946 case 0x57: // w
1947 case 0x58: // x
1948 case 0x59: // y
1949 case 0x5a: // z
1950 {
1951 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1952 control_key_state);
1953
1954 // If Alt is pressed, then prefix with escape.
1955 if (_is_alt_pressed(control_key_state)) {
1956 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1957 }
1958 }
1959 break;
1960
1961 // These virtual key codes are generated by the keys on the
1962 // keypad *when NumLock is on* and *Shift is up*.
1963 MATCH(VK_NUMPAD0, "0");
1964 MATCH(VK_NUMPAD1, "1");
1965 MATCH(VK_NUMPAD2, "2");
1966 MATCH(VK_NUMPAD3, "3");
1967 MATCH(VK_NUMPAD4, "4");
1968 MATCH(VK_NUMPAD5, "5");
1969 MATCH(VK_NUMPAD6, "6");
1970 MATCH(VK_NUMPAD7, "7");
1971 MATCH(VK_NUMPAD8, "8");
1972 MATCH(VK_NUMPAD9, "9");
1973
1974 MATCH(VK_MULTIPLY, "*");
1975 MATCH(VK_ADD, "+");
1976 MATCH(VK_SUBTRACT, "-");
1977 // VK_DECIMAL is generated by the . key on the keypad *when
1978 // NumLock is on* and *Shift is up* and the sequence is not
1979 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1980 // Windows Security screen to come up).
1981 case VK_DECIMAL:
1982 // U.S. English uses '.', Germany German uses ','.
1983 seqbuflen = _get_non_control_char(seqbuf, key_event,
1984 control_key_state);
1985 break;
1986
1987 MATCH_MODIFIER(VK_F1, SS3 "P");
1988 MATCH_MODIFIER(VK_F2, SS3 "Q");
1989 MATCH_MODIFIER(VK_F3, SS3 "R");
1990 MATCH_MODIFIER(VK_F4, SS3 "S");
1991 MATCH_MODIFIER(VK_F5, CSI "15~");
1992 MATCH_MODIFIER(VK_F6, CSI "17~");
1993 MATCH_MODIFIER(VK_F7, CSI "18~");
1994 MATCH_MODIFIER(VK_F8, CSI "19~");
1995 MATCH_MODIFIER(VK_F9, CSI "20~");
1996 MATCH_MODIFIER(VK_F10, CSI "21~");
1997 MATCH_MODIFIER(VK_F11, CSI "23~");
1998 MATCH_MODIFIER(VK_F12, CSI "24~");
1999
2000 MATCH_MODIFIER(VK_F13, CSI "25~");
2001 MATCH_MODIFIER(VK_F14, CSI "26~");
2002 MATCH_MODIFIER(VK_F15, CSI "28~");
2003 MATCH_MODIFIER(VK_F16, CSI "29~");
2004 MATCH_MODIFIER(VK_F17, CSI "31~");
2005 MATCH_MODIFIER(VK_F18, CSI "32~");
2006 MATCH_MODIFIER(VK_F19, CSI "33~");
2007 MATCH_MODIFIER(VK_F20, CSI "34~");
2008
2009 // MATCH_MODIFIER(VK_F21, ???);
2010 // MATCH_MODIFIER(VK_F22, ???);
2011 // MATCH_MODIFIER(VK_F23, ???);
2012 // MATCH_MODIFIER(VK_F24, ???);
2013 }
2014 }
2015
2016#undef MATCH
2017#undef MATCH_MODIFIER
2018#undef MATCH_KEYPAD
2019#undef MATCH_MODIFIER_KEYPAD
2020#undef ESC
2021#undef CSI
2022#undef SS3
2023
2024 const char* out;
2025 size_t outlen;
2026
2027 // Check for output in any of:
2028 // * seqstr is set (and strlen can be used to determine the length).
2029 // * seqbuf and seqbuflen are set
2030 // Fallback to ch from Windows.
Yi Kongaed415c2018-07-13 18:15:16 -07002031 if (seqstr != nullptr) {
Spencer Low50184062015-03-01 15:06:21 -08002032 out = seqstr;
2033 outlen = strlen(seqstr);
2034 } else if (seqbuflen > 0) {
2035 out = seqbuf;
2036 outlen = seqbuflen;
2037 } else if (ch != '\0') {
2038 // Use whatever Windows told us it is.
2039 seqbuf[0] = ch;
2040 seqbuflen = 1;
2041 out = seqbuf;
2042 outlen = seqbuflen;
2043 } else {
2044 // No special handling for the virtual key code and Windows isn't
2045 // telling us a character code, then we don't know how to translate
2046 // the key press.
2047 //
2048 // Consume the input and 'continue' to cause us to get a new key
2049 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002050 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002051 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002052 continue;
2053 }
2054
Spencer Low32762f42015-11-10 19:17:16 -08002055 // put output wRepeatCount times into g_console_input_buffer
2056 while (key_event->wRepeatCount-- > 0) {
2057 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002058 }
2059
Spencer Low32762f42015-11-10 19:17:16 -08002060 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002061 }
2062}
2063
2064static DWORD _old_console_mode; // previous GetConsoleMode() result
2065static HANDLE _console_handle; // when set, console mode should be restored
2066
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002067void stdin_raw_init() {
2068 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002069 if (in == nullptr) {
2070 return;
2071 }
Spencer Low50184062015-03-01 15:06:21 -08002072
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002073 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2074 // calling the process Ctrl-C routine (configured by
2075 // SetConsoleCtrlHandler()).
2076 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2077 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2078 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002079 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2080 ENABLE_LINE_INPUT |
2081 ENABLE_ECHO_INPUT);
2082 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2083 new_console_mode |= ENABLE_WINDOW_INPUT;
2084
2085 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002086 // This really should not fail.
2087 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002088 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002089 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002090
2091 // Once this is set, it means that stdin has been configured for
2092 // reading from and that the old console mode should be restored later.
2093 _console_handle = in;
2094
2095 // Note that we don't need to configure C Runtime line-ending
2096 // translation because _console_read() does not call the C Runtime to
2097 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002098}
2099
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002100void stdin_raw_restore() {
Yi Kongaed415c2018-07-13 18:15:16 -07002101 if (_console_handle != nullptr) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002102 const HANDLE in = _console_handle;
Yi Kongaed415c2018-07-13 18:15:16 -07002103 _console_handle = nullptr; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002104
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002105 if (!SetConsoleMode(in, _old_console_mode)) {
2106 // This really should not fail.
2107 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002108 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002109 }
2110 }
2111}
2112
Spencer Low2e02dc62015-11-07 17:34:39 -08002113// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
Josh Gao27241a72019-04-25 14:04:57 -07002114int unix_read_interruptible(borrowed_fd fd, void* buf, size_t len) {
Yi Kongaed415c2018-07-13 18:15:16 -07002115 if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) {
Spencer Low50184062015-03-01 15:06:21 -08002116 // If it is a request to read from stdin, and stdin_raw_init() has been
2117 // called, and it successfully configured the console, then read from
2118 // the console using Win32 console APIs and partially emulate a unix
2119 // terminal.
2120 return _console_read(_console_handle, buf, len);
2121 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002122 // On older versions of Windows (definitely 7, definitely not 10),
2123 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002124 // we need to limit the read size.
2125 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002126 len = 4096;
2127 }
Spencer Low50184062015-03-01 15:06:21 -08002128 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002129 // can do LF/CR translation (which is overridable with _setmode()).
2130 // Undefine the macro that is set in sysdeps.h which bans calls to
2131 // plain read() in favor of unix_read() or adb_read().
2132#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002133#undef read
Josh Gao27241a72019-04-25 14:04:57 -07002134 return read(fd.get(), buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002135#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002136 }
2137}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002138
2139/**************************************************************************/
2140/**************************************************************************/
2141/***** *****/
2142/***** Unicode support *****/
2143/***** *****/
2144/**************************************************************************/
2145/**************************************************************************/
2146
2147// This implements support for using files with Unicode filenames and for
2148// outputting Unicode text to a Win32 console window. This is inspired from
2149// http://utf8everywhere.org/.
2150//
2151// Background
2152// ----------
2153//
2154// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2155// filenames to APIs such as open(). This works because filenames are largely
2156// opaque 'cookies' (perhaps excluding path separators).
2157//
2158// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2159// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2160// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2161// CreateFile() API is really just a macro that adds the W/A based on whether
2162// the UNICODE preprocessor symbol is defined).
2163//
2164// Options
2165// -------
2166//
2167// Thus, to write a portable program, there are a few options:
2168//
2169// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2170// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2171// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2172// open() API.
2173//
2174// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2175// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2176// potentially touching a lot of code.
2177//
2178// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2179// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2180// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2181// or C Runtime API.
2182//
2183// The Choice
2184// ----------
2185//
Spencer Lowd21dc822015-11-12 15:20:15 -08002186// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2187// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002188// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002189// args that are passed to main() at the beginning of program startup. We also use
2190// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002191// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2192//
2193// Unicode console output
2194// ----------------------
2195//
2196// The way to output Unicode to a Win32 console window is to call
2197// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002198// such as Lucida Console or Consolas, and in the case of East Asian languages
2199// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2200// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2201// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002202//
2203// The problem is getting the C Runtime to make fprintf and related APIs call
2204// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2205// promising, but the various modes have issues:
2206//
2207// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2208// UTF-16 do not display properly.
2209// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2210// totally wrong.
2211// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2212// handler to be called (upon a later I/O call), aborting the process.
2213// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2214// to output nothing.
2215//
2216// So the only solution is to write our own adb_fprintf() that converts UTF-8
2217// to UTF-16 and then calls WriteConsoleW().
2218
2219
Spencer Lowcf4ff642015-05-11 01:08:48 -07002220// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2221// be passed to main().
2222NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2223 narrow_args = new char*[argc + 1];
2224
2225 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002226 std::string arg_narrow;
2227 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
Elliott Hughes4679a392018-10-19 13:59:44 -07002228 PLOG(FATAL) << "cannot convert argument from UTF-16 to UTF-8";
Spencer Lowd21dc822015-11-12 15:20:15 -08002229 }
2230 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002231 }
2232 narrow_args[argc] = nullptr; // terminate
2233}
2234
2235NarrowArgs::~NarrowArgs() {
2236 if (narrow_args != nullptr) {
2237 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2238 free(*argp);
2239 }
2240 delete[] narrow_args;
2241 narrow_args = nullptr;
2242 }
2243}
2244
Josh Gao0f29cbc2018-12-12 16:12:28 -08002245int unix_open(std::string_view path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002246 std::wstring path_wide;
Josh Gao0f29cbc2018-12-12 16:12:28 -08002247 if (!android::base::UTF8ToWide(path.data(), path.size(), &path_wide)) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002248 return -1;
2249 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002250 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002251 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002252 } else {
Josh Gao0f29cbc2018-12-12 16:12:28 -08002253 int mode;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002254 va_list args;
2255 va_start(args, options);
2256 mode = va_arg(args, int);
2257 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002258 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002259 }
2260}
2261
Spencer Lowcf4ff642015-05-11 01:08:48 -07002262// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002263DIR* adb_opendir(const char* path) {
2264 std::wstring path_wide;
2265 if (!android::base::UTF8ToWide(path, &path_wide)) {
2266 return nullptr;
2267 }
2268
Spencer Lowcf4ff642015-05-11 01:08:48 -07002269 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2270 // the fields, but right now all the callers treat the structure as
2271 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002272 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002273}
2274
2275// Version of readdir() that returns UTF-8 paths.
2276struct dirent* adb_readdir(DIR* dir) {
2277 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2278 struct _wdirent* const went = _wreaddir(wdir);
2279 if (went == nullptr) {
2280 return nullptr;
2281 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002282
Spencer Lowcf4ff642015-05-11 01:08:48 -07002283 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002284 std::string name_utf8;
2285 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2286 return nullptr;
2287 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002288
2289 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2290 // space for UTF-16 wchar_t's) with UTF-8 char's.
2291 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2292
2293 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2294 // Name too big to fit in existing buffer.
2295 errno = ENOMEM;
2296 return nullptr;
2297 }
2298
2299 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2300 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2301 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2302 // bigger than the caller expects because they expect a dirent structure
2303 // which has a smaller d_name field. Ignore this since the caller should be
2304 // resilient.
2305
2306 // Rewrite the UTF-16 d_name field to UTF-8.
2307 strcpy(ent->d_name, name_utf8.c_str());
2308
2309 return ent;
2310}
2311
2312// Version of closedir() to go with our version of adb_opendir().
2313int adb_closedir(DIR* dir) {
2314 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2315}
2316
2317// Version of unlink() that takes a UTF-8 path.
2318int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002319 std::wstring wpath;
2320 if (!android::base::UTF8ToWide(path, &wpath)) {
2321 return -1;
2322 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002323
2324 int rc = _wunlink(wpath.c_str());
2325
2326 if (rc == -1 && errno == EACCES) {
2327 /* unlink returns EACCES when the file is read-only, so we first */
2328 /* try to make it writable, then unlink again... */
2329 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2330 if (rc == 0)
2331 rc = _wunlink(wpath.c_str());
2332 }
2333 return rc;
2334}
2335
2336// Version of mkdir() that takes a UTF-8 path.
2337int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002338 std::wstring path_wide;
2339 if (!android::base::UTF8ToWide(path, &path_wide)) {
2340 return -1;
2341 }
2342
2343 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002344}
2345
Joshua Duongd85f5c02019-11-20 14:18:43 -08002346int adb_rename(const char* oldpath, const char* newpath) {
2347 std::wstring oldpath_wide, newpath_wide;
2348 if (!android::base::UTF8ToWide(oldpath, &oldpath_wide)) {
2349 return -1;
2350 }
2351 if (!android::base::UTF8ToWide(newpath, &newpath_wide)) {
2352 return -1;
2353 }
2354
2355 // MSDN just says the return value is non-zero on failure, make sure it
2356 // returns -1 on failure so that it behaves the same as other systems.
2357 return _wrename(oldpath_wide.c_str(), newpath_wide.c_str()) ? -1 : 0;
2358}
2359
Spencer Lowcf4ff642015-05-11 01:08:48 -07002360// Version of utime() that takes a UTF-8 path.
2361int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002362 std::wstring path_wide;
2363 if (!android::base::UTF8ToWide(path, &path_wide)) {
2364 return -1;
2365 }
2366
Spencer Lowcf4ff642015-05-11 01:08:48 -07002367 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2368 "utimbuf and _utimbuf should be the same size because they both "
2369 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002370 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002371}
2372
2373// Version of chmod() that takes a UTF-8 path.
2374int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002375 std::wstring path_wide;
2376 if (!android::base::UTF8ToWide(path, &path_wide)) {
2377 return -1;
2378 }
2379
2380 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002381}
2382
Spencer Lowa30b79a2015-11-15 16:29:36 -08002383// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2384static inline size_t utf8_codepoint_len(uint8_t ch) {
2385 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2386}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002387
Spencer Lowa30b79a2015-11-15 16:29:36 -08002388namespace internal {
2389
2390// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2391// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2392// remaining_bytes.
2393size_t ParseCompleteUTF8(const char* const first, const char* const last,
2394 std::vector<char>* const remaining_bytes) {
2395 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2396 // Current_after points one byte past the current byte to be examined.
2397 for (const char* current_after = last; current_after != first; --current_after) {
2398 const char* const current = current_after - 1;
2399 const char ch = *current;
2400 const char kHighBit = 0x80u;
2401 const char kTwoHighestBits = 0xC0u;
2402 if ((ch & kHighBit) == 0) { // high bit not set
2403 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2404 // bytes with no leading byte, so return the entire buffer.
2405 break;
2406 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2407 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2408 const size_t bytes_available = last - current;
2409 if (bytes_available < utf8_codepoint_len(ch)) {
2410 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2411 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2412 // to remaining_bytes.
2413 remaining_bytes->insert(remaining_bytes->end(), current, last);
2414 return current - first;
2415 } else {
2416 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2417 // trailing bytes with no lead byte, so return the entire buffer.
2418 break;
2419 }
2420 } else {
2421 // Trailing byte, so keep going backwards looking for the lead byte.
2422 }
2423 }
2424
2425 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2426 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2427 // so that they can be processed.
2428 return last - first;
2429}
2430
2431}
2432
2433// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2434// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2435// This matches the behavior of Linux.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002436
2437// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2438static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2439 HANDLE console) {
Josh Gao0cd3ae12016-09-21 12:37:10 -07002440 static std::mutex& console_output_buffer_lock = *new std::mutex();
2441 static auto& console_output_buffer = *new std::vector<char>();
2442
Spencer Lowa30b79a2015-11-15 16:29:36 -08002443 const int saved_errno = errno;
2444 std::vector<char> combined_buffer;
2445
2446 // Complete UTF-8 sequences that should be immediately written to the console.
2447 const char* utf8;
2448 size_t utf8_size;
2449
Josh Gao0cd3ae12016-09-21 12:37:10 -07002450 {
2451 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2452 if (console_output_buffer.empty()) {
2453 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2454 // common case with plain ASCII), parse buf directly.
2455 utf8 = buf;
2456 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2457 } else {
2458 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2459 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2460 // combined_buffer, then parse it all together.
2461 combined_buffer.swap(console_output_buffer);
2462 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002463
Josh Gao0cd3ae12016-09-21 12:37:10 -07002464 utf8 = combined_buffer.data();
2465 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2466 &console_output_buffer);
2467 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002468 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002469
2470 std::wstring utf16;
2471
2472 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2473 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2474 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002475 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002476 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002477
2478 // Note that this does not do \n => \r\n translation because that
2479 // doesn't seem necessary for the Windows console. For the Windows
2480 // console \r moves to the beginning of the line and \n moves to a new
2481 // line.
2482
2483 // Flush any stream buffering so that our output is afterwards which
2484 // makes sense because our call is afterwards.
2485 (void)fflush(stream);
2486
2487 // Write UTF-16 to the console.
2488 DWORD written = 0;
Yi Kongaed415c2018-07-13 18:15:16 -07002489 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002490 errno = EIO;
2491 return -1;
2492 }
2493
Spencer Lowa30b79a2015-11-15 16:29:36 -08002494 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2495 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2496 // matches the Linux behavior.
2497 errno = saved_errno;
2498 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002499}
2500
2501// Function prototype because attributes cannot be placed on func definitions.
Elliott Hughesd8a4c602018-06-26 13:06:15 -07002502static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap)
2503 __attribute__((__format__(__printf__, 3, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002504
2505// Internal function to format a UTF-8 string and write it to a Win32 console.
2506// Returns -1 on error.
2507static int _console_vfprintf(const HANDLE console, FILE* stream,
2508 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002509 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002510 std::string output_utf8;
2511
2512 // Format the string.
2513 // This could throw std::bad_alloc.
2514 android::base::StringAppendV(&output_utf8, format, ap);
2515
Spencer Lowa30b79a2015-11-15 16:29:36 -08002516 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2517 console);
2518 if (result != -1) {
2519 errno = saved_errno;
2520 } else {
2521 // If -1 was returned, errno has been set.
2522 }
2523 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002524}
2525
2526// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2527// Windows console.
2528int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2529 const HANDLE console = _get_console_handle(stream);
2530
2531 // If there is an associated Win32 console, write to it specially,
2532 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002533 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002534 return _console_vfprintf(console, stream, format, ap);
2535 } else {
2536 // If vfprintf is a macro, undefine it, so we can call the real
2537 // C Runtime API.
2538#pragma push_macro("vfprintf")
2539#undef vfprintf
2540 return vfprintf(stream, format, ap);
2541#pragma pop_macro("vfprintf")
2542 }
2543}
2544
Spencer Lowa30b79a2015-11-15 16:29:36 -08002545// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2546int adb_vprintf(const char *format, va_list ap) {
2547 return adb_vfprintf(stdout, format, ap);
2548}
2549
Spencer Lowcf4ff642015-05-11 01:08:48 -07002550// Version of fprintf() that takes UTF-8 and can write Unicode to a
2551// Windows console.
2552int adb_fprintf(FILE *stream, const char *format, ...) {
2553 va_list ap;
2554 va_start(ap, format);
2555 const int result = adb_vfprintf(stream, format, ap);
2556 va_end(ap);
2557
2558 return result;
2559}
2560
2561// Version of printf() that takes UTF-8 and can write Unicode to a
2562// Windows console.
2563int adb_printf(const char *format, ...) {
2564 va_list ap;
2565 va_start(ap, format);
2566 const int result = adb_vfprintf(stdout, format, ap);
2567 va_end(ap);
2568
2569 return result;
2570}
2571
2572// Version of fputs() that takes UTF-8 and can write Unicode to a
2573// Windows console.
2574int adb_fputs(const char* buf, FILE* stream) {
2575 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2576 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002577 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002578 return adb_fprintf(stream, "%s", buf);
2579}
2580
2581// Version of fputc() that takes UTF-8 and can write Unicode to a
2582// Windows console.
2583int adb_fputc(int ch, FILE* stream) {
2584 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002585 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002586 return EOF;
2587 }
2588 // For success, fputc returns the char, cast to unsigned char, then to int.
2589 return static_cast<unsigned char>(ch);
2590}
2591
Spencer Lowa30b79a2015-11-15 16:29:36 -08002592// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2593int adb_putchar(int ch) {
2594 return adb_fputc(ch, stdout);
2595}
2596
2597// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2598int adb_puts(const char* buf) {
2599 // adb_printf returns -1 on error, which is conveniently the same as EOF
2600 // which puts (and hence adb_puts) should return on error.
2601 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2602 return adb_printf("%s\n", buf);
2603}
2604
Spencer Lowcf4ff642015-05-11 01:08:48 -07002605// Internal function to write UTF-8 to a Win32 console. Returns the number of
2606// items (of length size) written. On error, returns a short item count or 0.
2607static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2608 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002609 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2610 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002611 if (result == -1) {
2612 return 0;
2613 }
2614 return result / size;
2615}
2616
2617// Version of fwrite() that takes UTF-8 and can write Unicode to a
2618// Windows console.
2619size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2620 const HANDLE console = _get_console_handle(stream);
2621
2622 // If there is an associated Win32 console, write to it specially,
2623 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002624 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002625 return _console_fwrite(ptr, size, nmemb, stream, console);
2626 } else {
2627 // If fwrite is a macro, undefine it, so we can call the real
2628 // C Runtime API.
2629#pragma push_macro("fwrite")
2630#undef fwrite
2631 return fwrite(ptr, size, nmemb, stream);
2632#pragma pop_macro("fwrite")
2633 }
2634}
2635
2636// Version of fopen() that takes a UTF-8 filename and can access a file with
2637// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002638FILE* adb_fopen(const char* path, const char* mode) {
2639 std::wstring path_wide;
2640 if (!android::base::UTF8ToWide(path, &path_wide)) {
2641 return nullptr;
2642 }
2643
2644 std::wstring mode_wide;
2645 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2646 return nullptr;
2647 }
2648
2649 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002650}
2651
Spencer Lowe6ae5732015-09-08 17:13:04 -07002652// Return a lowercase version of the argument. Uses C Runtime tolower() on
2653// each byte which is not UTF-8 aware, and theoretically uses the current C
2654// Runtime locale (which in practice is not changed, so this becomes a ASCII
2655// conversion).
2656static std::string ToLower(const std::string& anycase) {
2657 // copy string
2658 std::string str(anycase);
2659 // transform the copy
2660 std::transform(str.begin(), str.end(), str.begin(), tolower);
2661 return str;
2662}
2663
2664extern "C" int main(int argc, char** argv);
2665
2666// Link with -municode to cause this wmain() to be used as the program
2667// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2668// regular main() with UTF-8 args.
2669extern "C" int wmain(int argc, wchar_t **argv) {
2670 // Convert args from UTF-16 to UTF-8 and pass that to main().
2671 NarrowArgs narrow_args(argc, argv);
Josh Gaoe72c44b2019-06-10 12:48:34 -07002672
2673 // Avoid destructing NarrowArgs: argv might have been mutated to point to string literals.
2674 _exit(main(argc, narrow_args.data()));
Spencer Lowe6ae5732015-09-08 17:13:04 -07002675}
2676
Spencer Lowcf4ff642015-05-11 01:08:48 -07002677// Shadow UTF-8 environment variable name/value pairs that are created from
Spencer Low14022c22018-08-10 16:20:57 -07002678// _wenviron by _init_env(). Note that this is not currently updated if putenv, setenv, unsetenv are
2679// called. Note that no thread synchronization is done, but we're called early enough in
Spencer Lowe347c1d2015-08-02 18:13:54 -07002680// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002681static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002682
Spencer Low14022c22018-08-10 16:20:57 -07002683// Setup shadow UTF-8 environment variables.
2684static void _init_env() {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002685 // If some name/value pairs exist, then we've already done the setup below.
2686 if (g_environ_utf8.size() != 0) {
2687 return;
2688 }
2689
Spencer Lowe6ae5732015-09-08 17:13:04 -07002690 if (_wenviron == nullptr) {
2691 // If _wenviron is null, then -municode probably wasn't used. That
2692 // linker flag will cause the entry point to setup _wenviron. It will
2693 // also require an implementation of wmain() (which we provide above).
Elliott Hughes4679a392018-10-19 13:59:44 -07002694 LOG(FATAL) << "_wenviron is not set, did you link with -municode?";
Spencer Lowe6ae5732015-09-08 17:13:04 -07002695 }
2696
Spencer Lowcf4ff642015-05-11 01:08:48 -07002697 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2698 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2699 // to use the D() macro here because that tracing only works if the
2700 // ADB_TRACE environment variable is setup, but that env var can't be read
2701 // until this code completes.
2702 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2703 wchar_t* const equal = wcschr(*env, L'=');
2704 if (equal == nullptr) {
2705 // Malformed environment variable with no equal sign. Shouldn't
2706 // really happen, but we should be resilient to this.
2707 continue;
2708 }
2709
Spencer Lowd21dc822015-11-12 15:20:15 -08002710 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2711 // var because the program might never even read this particular variable.
2712 std::string name_utf8;
2713 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2714 continue;
2715 }
2716
Spencer Lowe6ae5732015-09-08 17:13:04 -07002717 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002718 name_utf8 = ToLower(name_utf8);
2719
2720 std::string value_utf8;
2721 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2722 continue;
2723 }
2724
2725 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002726
Spencer Lowe6ae5732015-09-08 17:13:04 -07002727 // Don't overwrite a previus env var with the same name. In reality,
2728 // the system probably won't let two env vars with the same name exist
2729 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002730 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002731 }
2732}
2733
2734// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002735// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002736char* adb_getenv(const char* name) {
Spencer Lowe6ae5732015-09-08 17:13:04 -07002737 // Case-insensitive search by searching for lowercase name in a map of
2738 // lowercase names.
2739 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002740 if (it == g_environ_utf8.end()) {
2741 return nullptr;
2742 }
2743
2744 return it->second;
2745}
2746
2747// Version of getcwd() that returns the current working directory in UTF-8.
2748char* adb_getcwd(char* buf, int size) {
2749 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2750 if (wbuf == nullptr) {
2751 return nullptr;
2752 }
2753
Spencer Lowd21dc822015-11-12 15:20:15 -08002754 std::string buf_utf8;
2755 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002756 free(wbuf);
2757 wbuf = nullptr;
2758
Spencer Lowd21dc822015-11-12 15:20:15 -08002759 if (!narrow_result) {
2760 return nullptr;
2761 }
2762
Spencer Lowcf4ff642015-05-11 01:08:48 -07002763 // If size was specified, make sure all the chars will fit.
2764 if (size != 0) {
2765 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2766 errno = ERANGE;
2767 return nullptr;
2768 }
2769 }
2770
2771 // If buf was not specified, allocate storage.
2772 if (buf == nullptr) {
2773 if (size == 0) {
2774 size = buf_utf8.length() + 1;
2775 }
2776 buf = reinterpret_cast<char*>(malloc(size));
2777 if (buf == nullptr) {
2778 return nullptr;
2779 }
2780 }
2781
2782 // Destination buffer was allocated with enough space, or we've already
2783 // checked an existing buffer size for enough space.
2784 strcpy(buf, buf_utf8.c_str());
2785
2786 return buf;
2787}
Spencer Low50beee32018-09-03 16:03:22 -07002788
Alex Buynytskyy96ff54b2020-02-13 06:52:04 -08002789void enable_inherit(borrowed_fd fd) {
2790 auto osh = adb_get_os_handle(fd);
2791 const auto h = reinterpret_cast<HANDLE>(osh);
2792 ::SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
2793}
2794
2795void disable_inherit(borrowed_fd fd) {
2796 auto osh = adb_get_os_handle(fd);
2797 const auto h = reinterpret_cast<HANDLE>(osh);
2798 ::SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0);
2799}
2800
2801Process adb_launch_process(std::string_view executable, std::vector<std::string> args,
2802 std::initializer_list<int> fds_to_inherit) {
2803 std::wstring wexe;
2804 if (!android::base::UTF8ToWide(executable.data(), executable.size(), &wexe)) {
2805 return Process();
2806 }
2807
2808 std::wstring wargs = L"\"" + wexe + L"\"";
2809 std::wstring warg;
2810 for (auto arg : args) {
2811 warg.clear();
2812 if (!android::base::UTF8ToWide(arg.data(), arg.size(), &warg)) {
2813 return Process();
2814 }
2815 wargs += L" \"";
2816 wargs += warg;
2817 wargs += L'\"';
2818 }
2819
2820 STARTUPINFOW sinfo = {sizeof(sinfo)};
2821 PROCESS_INFORMATION pinfo = {};
2822
2823 // TODO: use the Vista+ API to pass the list of inherited handles explicitly;
2824 // see http://blogs.msdn.com/b/oldnewthing/archive/2011/12/16/10248328.aspx
2825 for (auto fd : fds_to_inherit) {
2826 enable_inherit(fd);
2827 }
2828 const auto created = CreateProcessW(wexe.c_str(), wargs.data(),
2829 nullptr, // process attributes
2830 nullptr, // thread attributes
2831 fds_to_inherit.size() > 0, // inherit any handles?
2832 0, // flags
2833 nullptr, // environment
2834 nullptr, // current directory
2835 &sinfo, // startup info
2836 &pinfo);
2837 for (auto fd : fds_to_inherit) {
2838 disable_inherit(fd);
2839 }
2840
2841 if (!created) {
2842 return Process();
2843 }
2844
2845 ::CloseHandle(pinfo.hThread);
2846 return Process(pinfo.hProcess);
2847}
2848
Spencer Low50beee32018-09-03 16:03:22 -07002849// The SetThreadDescription API was brought in version 1607 of Windows 10.
2850typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);
2851
2852// Based on PlatformThread::SetName() from
2853// https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc
2854int adb_thread_setname(const std::string& name) {
2855 // The SetThreadDescription API works even if no debugger is attached.
2856 auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(
2857 ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
2858 if (set_thread_description_func) {
2859 std::wstring name_wide;
2860 if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) {
2861 return errno;
2862 }
2863 set_thread_description_func(::GetCurrentThread(), name_wide.c_str());
2864 }
2865
2866 // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions.
2867 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017
2868
2869 return 0;
2870}
Spencer Low14022c22018-08-10 16:20:57 -07002871
2872#if !defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2873#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
2874#endif
2875
2876#if !defined(DISABLE_NEWLINE_AUTO_RETURN)
2877#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
2878#endif
2879
2880static void _init_console() {
2881 DWORD old_out_console_mode;
2882
2883 const HANDLE out = _get_console_handle(STDOUT_FILENO, &old_out_console_mode);
2884 if (out == nullptr) {
2885 return;
2886 }
2887
2888 // Try to use ENABLE_VIRTUAL_TERMINAL_PROCESSING on the output console to process virtual
2889 // terminal sequences on newer versions of Windows 10 and later.
2890 // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
2891 // On older OSes that don't support the flag, SetConsoleMode() will return an error.
2892 // ENABLE_VIRTUAL_TERMINAL_PROCESSING also solves a problem where the last column of the
2893 // console cannot be overwritten.
2894 //
2895 // Note that we don't use DISABLE_NEWLINE_AUTO_RETURN because it doesn't seem to be necessary.
2896 // If we use DISABLE_NEWLINE_AUTO_RETURN, _console_write_utf8() would need to be modified to
2897 // translate \n to \r\n.
2898 if (!SetConsoleMode(out, old_out_console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
2899 return;
2900 }
2901
2902 // If SetConsoleMode() succeeded, the console supports virtual terminal processing, so we
2903 // should set the TERM env var to match so that it will be propagated to adbd on devices.
2904 //
2905 // Below's direct manipulation of env vars and not g_environ_utf8 assumes that _init_env() has
2906 // not yet been called. If this fails, _init_env() should be called after _init_console().
2907 if (g_environ_utf8.size() > 0) {
2908 LOG(FATAL) << "environment variables have already been converted to UTF-8";
2909 }
2910
2911#pragma push_macro("getenv")
2912#undef getenv
2913#pragma push_macro("putenv")
2914#undef putenv
2915 if (getenv("TERM") == nullptr) {
2916 // This is the same TERM value used by Gnome Terminal and the version of ssh included with
2917 // Windows.
2918 putenv("TERM=xterm-256color");
2919 }
2920#pragma pop_macro("putenv")
2921#pragma pop_macro("getenv")
2922}
2923
2924static bool _init_sysdeps() {
2925 // _init_console() depends on _init_env() not being called yet.
2926 _init_console();
2927 _init_env();
2928 _init_winsock();
2929 return true;
2930}
2931
2932static bool _sysdeps_init = _init_sysdeps();