blob: 1af7bf6694ffb799728988bd99e1d3fd5df08745 [file] [log] [blame]
Dan Albert33134262015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070030#include <mutex>
Spencer Low5200c662015-07-30 23:07:55 -070031#include <string>
Josh Gao0f29cbc2018-12-12 16:12:28 -080032#include <string_view>
Spencer Lowcf4ff642015-05-11 01:08:48 -070033#include <unordered_map>
Josh Gao3777d2e2016-02-16 17:34:53 -080034#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070035
Elliott Hughesd48dbd82015-07-24 11:35:40 -070036#include <cutils/sockets.h>
37
David Pursell5f787ed2016-01-27 08:52:53 -080038#include <android-base/errors.h>
Elliott Hughes4679a392018-10-19 13:59:44 -070039#include <android-base/file.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080040#include <android-base/logging.h>
Josh Gao116aa0a2018-04-05 17:55:25 -070041#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080042#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
44#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070045
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046#include "adb.h"
Josh Gao3777d2e2016-02-16 17:34:53 -080047#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080048
Josh Gao116aa0a2018-04-05 17:55:25 -070049#include "sysdeps/uio.h"
50
Elliott Hughesa2f2e562015-04-16 16:47:02 -070051/* forward declarations */
52
53typedef const struct FHClassRec_* FHClass;
54typedef struct FHRec_* FH;
Elliott Hughesa2f2e562015-04-16 16:47:02 -070055
56typedef struct FHClassRec_ {
57 void (*_fh_init)(FH);
58 int (*_fh_close)(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070059 int64_t (*_fh_lseek)(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070060 int (*_fh_read)(FH, void*, int);
61 int (*_fh_write)(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070062 int (*_fh_writev)(FH, const adb_iovec*, int);
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070063 intptr_t (*_fh_get_os_handle)(FH);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070064} FHClassRec;
65
66static void _fh_file_init(FH);
67static int _fh_file_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070068static int64_t _fh_file_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070069static int _fh_file_read(FH, void*, int);
70static int _fh_file_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070071static int _fh_file_writev(FH, const adb_iovec*, int);
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070072static intptr_t _fh_file_get_os_handle(FH f);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070073
74static const FHClassRec _fh_file_class = {
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070075 _fh_file_init, _fh_file_close, _fh_file_lseek, _fh_file_read,
76 _fh_file_write, _fh_file_writev, _fh_file_get_os_handle,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070077};
78
79static void _fh_socket_init(FH);
80static int _fh_socket_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070081static int64_t _fh_socket_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070082static int _fh_socket_read(FH, void*, int);
83static int _fh_socket_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070084static int _fh_socket_writev(FH, const adb_iovec*, int);
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070085static intptr_t _fh_socket_get_os_handle(FH f);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070086
87static const FHClassRec _fh_socket_class = {
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -070088 _fh_socket_init, _fh_socket_close, _fh_socket_lseek, _fh_socket_read,
89 _fh_socket_write, _fh_socket_writev, _fh_socket_get_os_handle,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070090};
91
Pirama Arumuga Nainar29e3dd82018-08-08 10:33:24 -070092#if defined(assert)
93#undef assert
94#endif
95
Spencer Low2122c7a2015-08-26 18:46:09 -070096void handle_deleter::operator()(HANDLE h) {
97 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
98 // implying that NULL is a valid handle, but this is probably impossible.
99 // Other APIs like CreateEvent() are documented to return NULL on error,
100 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
101 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
102 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
103 // only need to check for INVALID_HANDLE_VALUE.
104 if (h != INVALID_HANDLE_VALUE) {
105 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700106 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800107 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700108 }
109 }
110}
111
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800112/**************************************************************************/
113/**************************************************************************/
114/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800115/***** common file descriptor handling *****/
116/***** *****/
117/**************************************************************************/
118/**************************************************************************/
119
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800120typedef struct FHRec_
121{
122 FHClass clazz;
123 int used;
124 int eof;
125 union {
126 HANDLE handle;
127 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800128 } u;
129
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800130 char name[32];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800131} FHRec;
132
133#define fh_handle u.handle
134#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800135
Josh Gaob6232b92016-02-17 16:45:39 -0800136#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700137#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800138
Josh Gao0cd3ae12016-09-21 12:37:10 -0700139static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800140static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700141static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800142
Josh Gao27241a72019-04-25 14:04:57 -0700143static FH _fh_from_int(borrowed_fd bfd, const char* func) {
144 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800145
Josh Gao27241a72019-04-25 14:04:57 -0700146 int fd = bfd.get();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800147 fd -= WIN32_FH_BASE;
148
Spencer Lowc3211552015-07-24 15:38:19 -0700149 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Josh Gao27241a72019-04-25 14:04:57 -0700150 D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800151 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700152 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800153 }
154
155 f = &_win32_fhs[fd];
156
157 if (f->used == 0) {
Josh Gao27241a72019-04-25 14:04:57 -0700158 D("_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, func);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800159 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700160 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800161 }
162
163 return f;
164}
165
Josh Gao27241a72019-04-25 14:04:57 -0700166static int _fh_to_int(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800167 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
168 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
169
170 return -1;
171}
172
Josh Gao27241a72019-04-25 14:04:57 -0700173static FH _fh_alloc(FHClass clazz) {
174 FH f = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800175
Josh Gao0cd3ae12016-09-21 12:37:10 -0700176 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800177
Josh Gaob6232b92016-02-17 16:45:39 -0800178 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
Yi Kongaed415c2018-07-13 18:15:16 -0700179 if (_win32_fhs[i].clazz == nullptr) {
Josh Gaob6232b92016-02-17 16:45:39 -0800180 f = &_win32_fhs[i];
181 _win32_fh_next = i + 1;
Josh Gao0cd3ae12016-09-21 12:37:10 -0700182 f->clazz = clazz;
183 f->used = 1;
184 f->eof = 0;
185 f->name[0] = '\0';
186 clazz->_fh_init(f);
187 return f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188 }
189 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700190
191 D("_fh_alloc: no more free file descriptors");
192 errno = EMFILE; // Too many open files
193 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800194}
195
Josh Gao27241a72019-04-25 14:04:57 -0700196static int _fh_close(FH f) {
Spencer Lowc3211552015-07-24 15:38:19 -0700197 // Use lock so that closing only happens once and so that _fh_alloc can't
198 // allocate a FH that we're in the middle of closing.
Josh Gao0cd3ae12016-09-21 12:37:10 -0700199 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800200
201 int offset = f - _win32_fhs;
202 if (_win32_fh_next > offset) {
203 _win32_fh_next = offset;
204 }
205
Spencer Lowc3211552015-07-24 15:38:19 -0700206 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800207 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700208 f->name[0] = '\0';
209 f->eof = 0;
210 f->used = 0;
Yi Kongaed415c2018-07-13 18:15:16 -0700211 f->clazz = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800212 }
213 return 0;
214}
215
Spencer Low5200c662015-07-30 23:07:55 -0700216// Deleter for unique_fh.
217class fh_deleter {
218 public:
219 void operator()(struct FHRec_* fh) {
220 // We're called from a destructor and destructors should not overwrite
221 // errno because callers may do:
222 // errno = EBLAH;
223 // return -1; // calls destructor, which should not overwrite errno
224 const int saved_errno = errno;
225 _fh_close(fh);
226 errno = saved_errno;
227 }
228};
229
230// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
231typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
232
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800233/**************************************************************************/
234/**************************************************************************/
235/***** *****/
236/***** file-based descriptor handling *****/
237/***** *****/
238/**************************************************************************/
239/**************************************************************************/
240
Josh Gao116aa0a2018-04-05 17:55:25 -0700241static void _fh_file_init(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242 f->fh_handle = INVALID_HANDLE_VALUE;
243}
244
Josh Gao116aa0a2018-04-05 17:55:25 -0700245static int _fh_file_close(FH f) {
246 CloseHandle(f->fh_handle);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800247 f->fh_handle = INVALID_HANDLE_VALUE;
248 return 0;
249}
250
Josh Gao116aa0a2018-04-05 17:55:25 -0700251static int _fh_file_read(FH f, void* buf, int len) {
252 DWORD read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800253
Yi Kongaed415c2018-07-13 18:15:16 -0700254 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700255 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800256 errno = EIO;
257 return -1;
258 } else if (read_bytes < (DWORD)len) {
259 f->eof = 1;
260 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700261 return read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262}
263
Josh Gao116aa0a2018-04-05 17:55:25 -0700264static int _fh_file_write(FH f, const void* buf, int len) {
265 DWORD wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800266
Yi Kongaed415c2018-07-13 18:15:16 -0700267 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700268 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800269 errno = EIO;
270 return -1;
271 } else if (wrote_bytes < (DWORD)len) {
272 f->eof = 1;
273 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700274 return wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800275}
276
Josh Gao116aa0a2018-04-05 17:55:25 -0700277static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
278 if (iovcnt <= 0) {
279 errno = EINVAL;
280 return -1;
281 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800282
Josh Gao116aa0a2018-04-05 17:55:25 -0700283 DWORD wrote_bytes = 0;
284
285 for (int i = 0; i < iovcnt; ++i) {
286 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
287 if (rc == -1) {
288 return wrote_bytes > 0 ? wrote_bytes : -1;
289 } else if (rc == 0) {
290 return wrote_bytes;
291 }
292
293 wrote_bytes += rc;
294
295 if (static_cast<size_t>(rc) < iov[i].iov_len) {
296 return wrote_bytes;
297 }
298 }
299
300 return wrote_bytes;
301}
302
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700303static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700304 DWORD method;
Josh Gao116aa0a2018-04-05 17:55:25 -0700305 switch (origin) {
306 case SEEK_SET:
307 method = FILE_BEGIN;
308 break;
309 case SEEK_CUR:
310 method = FILE_CURRENT;
311 break;
312 case SEEK_END:
313 method = FILE_END;
314 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800315 default:
316 errno = EINVAL;
317 return -1;
318 }
319
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700320 LARGE_INTEGER li = {.QuadPart = pos};
321 if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800322 errno = EIO;
323 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800324 }
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700325 f->eof = 0;
326 return li.QuadPart;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800327}
328
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700329static intptr_t _fh_file_get_os_handle(FH f) {
330 return reinterpret_cast<intptr_t>(f->u.handle);
331}
332
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800333/**************************************************************************/
334/**************************************************************************/
335/***** *****/
336/***** file-based descriptor handling *****/
337/***** *****/
338/**************************************************************************/
339/**************************************************************************/
340
Josh Gao64a63ac2018-04-05 18:09:02 -0700341int adb_open(const char* path, int options) {
342 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800343
Josh Gao64a63ac2018-04-05 18:09:02 -0700344 DWORD desiredAccess = 0;
345 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800346
Josh Gao4b019a52019-02-07 14:13:39 -0800347 // CreateFileW is inherently O_CLOEXEC by default.
348 options &= ~O_CLOEXEC;
349
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800350 switch (options) {
351 case O_RDONLY:
352 desiredAccess = GENERIC_READ;
353 break;
354 case O_WRONLY:
355 desiredAccess = GENERIC_WRITE;
356 break;
357 case O_RDWR:
358 desiredAccess = GENERIC_READ | GENERIC_WRITE;
359 break;
360 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700361 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800362 errno = EINVAL;
363 return -1;
364 }
365
Josh Gao64a63ac2018-04-05 18:09:02 -0700366 f = _fh_alloc(&_fh_file_class);
367 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800368 return -1;
369 }
370
Spencer Lowd21dc822015-11-12 15:20:15 -0800371 std::wstring path_wide;
372 if (!android::base::UTF8ToWide(path, &path_wide)) {
373 return -1;
374 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700375 f->fh_handle =
Yi Kongaed415c2018-07-13 18:15:16 -0700376 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800377
Josh Gao64a63ac2018-04-05 18:09:02 -0700378 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700379 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800380 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700381 D("adb_open: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700382 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800383 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700384 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800385 errno = ENOENT;
386 return -1;
387
388 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700389 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800390 errno = ENOTDIR;
391 return -1;
392
393 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800394 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800395 errno = ENOENT;
396 return -1;
397 }
398 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800399
Josh Gao64a63ac2018-04-05 18:09:02 -0700400 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
401 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800402 return _fh_to_int(f);
403}
404
405/* ignore mode on Win32 */
Josh Gao64a63ac2018-04-05 18:09:02 -0700406int adb_creat(const char* path, int mode) {
407 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800408
Josh Gao64a63ac2018-04-05 18:09:02 -0700409 f = _fh_alloc(&_fh_file_class);
410 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800411 return -1;
412 }
413
Spencer Lowd21dc822015-11-12 15:20:15 -0800414 std::wstring path_wide;
415 if (!android::base::UTF8ToWide(path, &path_wide)) {
416 return -1;
417 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700418 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
Yi Kongaed415c2018-07-13 18:15:16 -0700419 nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800420
Josh Gao64a63ac2018-04-05 18:09:02 -0700421 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700422 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800423 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700424 D("adb_creat: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700425 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800426 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700427 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800428 errno = ENOENT;
429 return -1;
430
431 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700432 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800433 errno = ENOTDIR;
434 return -1;
435
436 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800437 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800438 errno = ENOENT;
439 return -1;
440 }
441 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700442 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
443 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800444 return _fh_to_int(f);
445}
446
Josh Gao27241a72019-04-25 14:04:57 -0700447int adb_read(borrowed_fd fd, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700448 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800449
Yi Kongaed415c2018-07-13 18:15:16 -0700450 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700451 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452 return -1;
453 }
454
Josh Gao116aa0a2018-04-05 17:55:25 -0700455 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456}
457
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700458int adb_pread(borrowed_fd fd, void* buf, int len, off64_t offset) {
459 OVERLAPPED overlapped = {};
460 overlapped.Offset = static_cast<DWORD>(offset);
461 overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
462 DWORD bytes_read;
463 if (!::ReadFile(adb_get_os_handle(fd), buf, static_cast<DWORD>(len), &bytes_read,
464 &overlapped)) {
465 D("adb_pread: could not read %d bytes from FD %d", len, fd.get());
466 switch (::GetLastError()) {
467 case ERROR_IO_PENDING:
468 errno = EAGAIN;
469 return -1;
470 default:
471 errno = EINVAL;
472 return -1;
473 }
474 }
475 return static_cast<int>(bytes_read);
476}
477
Josh Gao27241a72019-04-25 14:04:57 -0700478int adb_write(borrowed_fd fd, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700479 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800480
Yi Kongaed415c2018-07-13 18:15:16 -0700481 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700482 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800483 return -1;
484 }
485
486 return f->clazz->_fh_write(f, buf, len);
487}
488
Josh Gao27241a72019-04-25 14:04:57 -0700489ssize_t adb_writev(borrowed_fd fd, const adb_iovec* iov, int iovcnt) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700490 FH f = _fh_from_int(fd, __func__);
491
Yi Kongaed415c2018-07-13 18:15:16 -0700492 if (f == nullptr) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700493 errno = EBADF;
494 return -1;
495 }
496
497 return f->clazz->_fh_writev(f, iov, iovcnt);
498}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700500int adb_pwrite(borrowed_fd fd, const void* buf, int len, off64_t offset) {
501 OVERLAPPED params = {};
502 params.Offset = static_cast<DWORD>(offset);
503 params.OffsetHigh = static_cast<DWORD>(offset >> 32);
504 DWORD bytes_written = 0;
505 if (!::WriteFile(adb_get_os_handle(fd), buf, len, &bytes_written, &params)) {
506 D("adb_pwrite: could not write %d bytes to FD %d", len, fd.get());
507 switch (::GetLastError()) {
508 case ERROR_IO_PENDING:
509 errno = EAGAIN;
510 return -1;
511 default:
512 errno = EINVAL;
513 return -1;
514 }
515 }
516 return static_cast<int>(bytes_written);
517}
518
Josh Gao27241a72019-04-25 14:04:57 -0700519int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where) {
Josh Gao64a63ac2018-04-05 18:09:02 -0700520 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800521 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700522 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800523 return -1;
524 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525 return f->clazz->_fh_lseek(f, pos, where);
526}
527
Josh Gao64a63ac2018-04-05 18:09:02 -0700528int adb_close(int fd) {
529 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800530
531 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700532 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800533 return -1;
534 }
535
Josh Gao64a63ac2018-04-05 18:09:02 -0700536 D("adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800537 _fh_close(f);
538 return 0;
539}
540
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700541HANDLE adb_get_os_handle(borrowed_fd fd) {
542 FH f = _fh_from_int(fd, __func__);
543
544 if (!f) {
545 errno = EBADF;
546 return nullptr;
547 }
548
549 D("adb_get_os_handle: %s", f->name);
550 const intptr_t intptr_handle = f->clazz->_fh_get_os_handle(f);
551 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
552 return handle;
553}
554
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800555/**************************************************************************/
556/**************************************************************************/
557/***** *****/
558/***** socket-based file descriptors *****/
559/***** *****/
560/**************************************************************************/
561/**************************************************************************/
562
Spencer Lowf055c192015-01-25 14:40:16 -0800563#undef setsockopt
564
Spencer Low5200c662015-07-30 23:07:55 -0700565static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700566 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
567 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gaoa3577e12016-12-05 13:24:48 -0800568 // are mapped to strings by adb_strerror().
Spencer Low5200c662015-07-30 23:07:55 -0700569 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800570 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700571 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
572 // case WSAEINTR: errno = EINTR; break;
573 case WSAEFAULT: errno = EFAULT; break;
574 case WSAEINVAL: errno = EINVAL; break;
575 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700576 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
577 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
578 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800579 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700580 case WSAENOTSOCK: errno = ENOTSOCK; break;
581 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
582 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
583 case WSAENETDOWN: errno = ENETDOWN; break;
584 case WSAENETRESET: errno = ENETRESET; break;
585 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
586 // to use EPIPE for these situations and there are some callers that look
587 // for EPIPE.
588 case WSAECONNABORTED: errno = EPIPE; break;
589 case WSAECONNRESET: errno = ECONNRESET; break;
590 case WSAENOBUFS: errno = ENOBUFS; break;
591 case WSAENOTCONN: errno = ENOTCONN; break;
592 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
593 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
594 // considerations: Reportedly send() can return zero on timeout, and POSIX
595 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
596 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
597 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800598 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700600 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700601 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602 }
603}
604
Josh Gao3777d2e2016-02-16 17:34:53 -0800605extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
606 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
607 int skipped = 0;
608 std::vector<WSAPOLLFD> sockets;
609 std::vector<adb_pollfd*> original;
Josh Gao05fb45b2018-03-29 12:34:28 -0700610
Josh Gao3777d2e2016-02-16 17:34:53 -0800611 for (size_t i = 0; i < nfds; ++i) {
612 FH fh = _fh_from_int(fds[i].fd, __func__);
613 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
614 D("adb_poll received bad FD %d", fds[i].fd);
615 fds[i].revents = POLLNVAL;
616 ++skipped;
617 } else {
618 WSAPOLLFD wsapollfd = {
619 .fd = fh->u.socket,
620 .events = static_cast<short>(fds[i].events)
621 };
622 sockets.push_back(wsapollfd);
623 original.push_back(&fds[i]);
624 }
Spencer Low5200c662015-07-30 23:07:55 -0700625 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800626
627 if (sockets.empty()) {
628 return skipped;
629 }
630
Josh Gao05fb45b2018-03-29 12:34:28 -0700631 // If we have any invalid FDs in our FD set, make sure to return immediately.
632 if (skipped > 0) {
633 timeout = 0;
634 }
635
Josh Gao3777d2e2016-02-16 17:34:53 -0800636 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
637 if (result == SOCKET_ERROR) {
638 _socket_set_errno(WSAGetLastError());
639 return -1;
640 }
641
642 // Map the results back onto the original set.
643 for (size_t i = 0; i < sockets.size(); ++i) {
644 original[i]->revents = sockets[i].revents;
645 }
646
Josh Gao05fb45b2018-03-29 12:34:28 -0700647 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gao3777d2e2016-02-16 17:34:53 -0800648 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
649 // to do. Ignore its result and calculate the proper return value.
650 result = 0;
651 for (size_t i = 0; i < nfds; ++i) {
652 if (fds[i].revents != 0) {
653 ++result;
654 }
655 }
656 return result;
657}
658
659static void _fh_socket_init(FH f) {
660 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800661}
662
Josh Gao116aa0a2018-04-05 17:55:25 -0700663static int _fh_socket_close(FH f) {
Spencer Low5200c662015-07-30 23:07:55 -0700664 if (f->fh_socket != INVALID_SOCKET) {
Spencer Low5200c662015-07-30 23:07:55 -0700665 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800666 // Don't set errno here, since adb_close will ignore it.
667 const DWORD err = WSAGetLastError();
668 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700669 }
670 f->fh_socket = INVALID_SOCKET;
671 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800672 return 0;
673}
674
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700675static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800676 errno = EPIPE;
677 return -1;
678}
679
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700680static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700681 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800682 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700683 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700684 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
685 // that to reduce spam and confusion.
686 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700687 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800688 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700689 }
Spencer Low5200c662015-07-30 23:07:55 -0700690 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800691 result = -1;
692 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700693 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800694}
695
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700696static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700697 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800698 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700699 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700700 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
701 // that to reduce spam and confusion.
702 if (err != WSAEWOULDBLOCK) {
703 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800704 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700705 }
Spencer Low5200c662015-07-30 23:07:55 -0700706 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800707 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700708 } else {
709 // According to https://code.google.com/p/chromium/issues/detail?id=27870
710 // Winsock Layered Service Providers may cause this.
Josh Gao116aa0a2018-04-05 17:55:25 -0700711 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
712 << result << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800713 }
714 return result;
715}
716
Josh Gao116aa0a2018-04-05 17:55:25 -0700717// Make sure that adb_iovec is compatible with WSABUF.
718static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
719static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
720static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
721
722static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
723static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
724
725static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
726 if (iovcnt <= 0) {
727 errno = EINVAL;
728 return -1;
729 }
730
731 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
732 DWORD bytes_written = 0;
733 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
734 if (result == SOCKET_ERROR) {
735 const DWORD err = WSAGetLastError();
736 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
737 // that to reduce spam and confusion.
738 if (err != WSAEWOULDBLOCK) {
739 D("send fd %d failed: %s", _fh_to_int(f),
740 android::base::SystemErrorCodeToString(err).c_str());
741 }
742 _socket_set_errno(err);
743 result = -1;
744 }
745 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
746 return static_cast<int>(bytes_written);
747}
748
Yurii Zubrytskyi709dfc32019-07-10 17:59:34 -0700749static intptr_t _fh_socket_get_os_handle(FH f) {
750 return f->u.socket;
751}
752
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800753/**************************************************************************/
754/**************************************************************************/
755/***** *****/
756/***** replacement for libs/cutils/socket_xxxx.c *****/
757/***** *****/
758/**************************************************************************/
759/**************************************************************************/
760
Spencer Low14022c22018-08-10 16:20:57 -0700761static void _init_winsock() {
Josh Gao2e93df22018-04-05 18:10:03 -0700762 static std::once_flag once;
763 std::call_once(once, []() {
764 WSADATA wsaData;
765 int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766 if (rc != 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700767 LOG(FATAL) << "could not initialize Winsock: "
768 << android::base::SystemErrorCodeToString(rc);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800769 }
Spencer Low87e97ee2015-08-12 18:19:16 -0700770
771 // Note that we do not call atexit() to register WSACleanup to be called
772 // at normal process termination because:
773 // 1) When exit() is called, there are still threads actively using
774 // Winsock because we don't cleanly shutdown all threads, so it
775 // doesn't make sense to call WSACleanup() and may cause problems
776 // with those threads.
777 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
778 // calls WSACleanup() which tries to unload a DLL, which tries to
779 // grab the LoaderLock. This conflicts with the device_poll_thread
780 // which holds the LoaderLock because AdbWinApi.dll calls
781 // setupapi.dll which tries to load wintrust.dll which tries to load
782 // crypt32.dll which calls atexit() which tries to acquire the C
783 // Runtime lock that the other thread holds.
Josh Gao2e93df22018-04-05 18:10:03 -0700784 });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800785}
786
Spencer Low677fb432015-09-29 15:05:29 -0700787// Map a socket type to an explicit socket protocol instead of using the socket
788// protocol of 0. Explicit socket protocols are used by most apps and we should
789// do the same to reduce the chance of exercising uncommon code-paths that might
790// have problems or that might load different Winsock service providers that
791// have problems.
792static int GetSocketProtocolFromSocketType(int type) {
793 switch (type) {
794 case SOCK_STREAM:
795 return IPPROTO_TCP;
796 case SOCK_DGRAM:
797 return IPPROTO_UDP;
798 default:
799 LOG(FATAL) << "Unknown socket type: " << type;
800 return 0;
801 }
802}
803
Spencer Low5200c662015-07-30 23:07:55 -0700804int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800805 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800806 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800807
Josh Gao6487e742016-02-18 13:43:55 -0800808 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700809 if (!f) {
810 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800811 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700812 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800813
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800814 memset(&addr, 0, sizeof(addr));
815 addr.sin_family = AF_INET;
816 addr.sin_port = htons(port);
817 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
818
Spencer Low677fb432015-09-29 15:05:29 -0700819 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800820 if (s == INVALID_SOCKET) {
821 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700822 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800823 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700824 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800825 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700826 return -1;
827 }
828 f->fh_socket = s;
829
Josh Gao6487e742016-02-18 13:43:55 -0800830 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700831 // Save err just in case inet_ntoa() or ntohs() changes the last error.
832 const DWORD err = WSAGetLastError();
833 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800834 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
835 android::base::SystemErrorCodeToString(err).c_str());
836 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
837 error->c_str());
838 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800839 return -1;
840 }
841
Spencer Low5200c662015-07-30 23:07:55 -0700842 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800843 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
844 port);
845 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700846 f.release();
847 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848}
849
Spencer Low5200c662015-07-30 23:07:55 -0700850// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800851static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800852 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800853 SOCKET s;
854 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800855
Josh Gao6487e742016-02-18 13:43:55 -0800856 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800857 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700858 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800859 return -1;
860 }
861
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800862 memset(&addr, 0, sizeof(addr));
863 addr.sin_family = AF_INET;
864 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700865 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800866
Spencer Low5200c662015-07-30 23:07:55 -0700867 // TODO: Consider using dual-stack socket that can simultaneously listen on
868 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700869 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700870 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800871 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700872 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800873 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700874 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800875 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700876 return -1;
877 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800878
879 f->fh_socket = s;
880
Spencer Lowbf7c6052015-08-11 16:45:32 -0700881 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
882 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800883 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800884 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
885 const DWORD err = WSAGetLastError();
886 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
887 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700888 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800889 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700890 return -1;
891 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800892
Josh Gao6487e742016-02-18 13:43:55 -0800893 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700894 // Save err just in case inet_ntoa() or ntohs() changes the last error.
895 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800896 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
897 ntohs(addr.sin_port),
898 android::base::SystemErrorCodeToString(err).c_str());
899 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
900 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800901 return -1;
902 }
903 if (type == SOCK_STREAM) {
Josh Gaobf243a62018-03-20 14:25:03 -0700904 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800905 const DWORD err = WSAGetLastError();
906 *error = android::base::StringPrintf(
907 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
908 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
909 error->c_str());
910 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800911 return -1;
912 }
913 }
Spencer Low5200c662015-07-30 23:07:55 -0700914 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800915 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
916 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
917 port);
918 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700919 f.release();
920 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800921}
922
Spencer Low5200c662015-07-30 23:07:55 -0700923int network_loopback_server(int port, int type, std::string* error) {
924 return _network_server(port, type, INADDR_LOOPBACK, error);
925}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800926
Spencer Low5200c662015-07-30 23:07:55 -0700927int network_inaddr_any_server(int port, int type, std::string* error) {
928 return _network_server(port, type, INADDR_ANY, error);
929}
930
931int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
932 unique_fh f(_fh_alloc(&_fh_socket_class));
933 if (!f) {
934 *error = strerror(errno);
935 return -1;
936 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800937
Spencer Low5200c662015-07-30 23:07:55 -0700938 struct addrinfo hints;
939 memset(&hints, 0, sizeof(hints));
940 hints.ai_family = AF_UNSPEC;
941 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700942 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700943
944 char port_str[16];
945 snprintf(port_str, sizeof(port_str), "%d", port);
946
947 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700948
949#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800950// TODO: When the Android SDK tools increases the Windows system
951// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700952#else
Josh Gao6487e742016-02-18 13:43:55 -0800953// Otherwise, keep using getaddrinfo(), or do runtime API detection
954// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700955#endif
Spencer Low5200c662015-07-30 23:07:55 -0700956 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800957 const DWORD err = WSAGetLastError();
958 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
959 host.c_str(), port_str,
960 android::base::SystemErrorCodeToString(err).c_str());
961
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700962 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800963 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800964 return -1;
965 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700966 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700967 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800968
Spencer Low5200c662015-07-30 23:07:55 -0700969 // TODO: Try all the addresses if there's more than one? This just uses
970 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
971 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800972 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
973 if (s == INVALID_SOCKET) {
974 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700975 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800976 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700977 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800978 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800979 return -1;
980 }
981 f->fh_socket = s;
982
Spencer Low5200c662015-07-30 23:07:55 -0700983 // TODO: Implement timeouts for Windows. Seems like the default in theory
984 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800985 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700986 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800987 const DWORD err = WSAGetLastError();
988 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
989 android::base::SystemErrorCodeToString(err).c_str());
990 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
991 port_str, error->c_str());
992 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800993 return -1;
994 }
995
Spencer Low5200c662015-07-30 23:07:55 -0700996 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800997 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
998 port);
999 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
1000 fd);
Spencer Low5200c662015-07-30 23:07:55 -07001001 f.release();
1002 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001003}
1004
Josh Gao64a63ac2018-04-05 18:09:02 -07001005int adb_register_socket(SOCKET s) {
1006 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001007 f->fh_socket = s;
1008 return _fh_to_int(f);
1009}
1010
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001011#undef accept
Josh Gao27241a72019-04-25 14:04:57 -07001012int adb_socket_accept(borrowed_fd serverfd, struct sockaddr* addr, socklen_t* addrlen) {
Josh Gao64a63ac2018-04-05 18:09:02 -07001013 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001014
Josh Gao64a63ac2018-04-05 18:09:02 -07001015 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001016 D("adb_socket_accept: invalid fd %d", serverfd.get());
Spencer Low5200c662015-07-30 23:07:55 -07001017 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001018 return -1;
1019 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001020
Josh Gao64a63ac2018-04-05 18:09:02 -07001021 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001022 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -07001023 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
1024 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001025 return -1;
1026 }
1027
Josh Gao64a63ac2018-04-05 18:09:02 -07001028 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001029 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001030 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001031 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd.get()
Josh Gao64a63ac2018-04-05 18:09:02 -07001032 << " failed: " + android::base::SystemErrorCodeToString(err);
1033 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001034 return -1;
1035 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001036
Spencer Low5200c662015-07-30 23:07:55 -07001037 const int fd = _fh_to_int(fh.get());
Josh Gao64a63ac2018-04-05 18:09:02 -07001038 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
Josh Gao27241a72019-04-25 14:04:57 -07001039 D("adb_socket_accept on fd %d returns fd %d", serverfd.get(), fd);
Spencer Low5200c662015-07-30 23:07:55 -07001040 fh.release();
Josh Gao64a63ac2018-04-05 18:09:02 -07001041 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001042}
1043
Josh Gao27241a72019-04-25 14:04:57 -07001044int adb_setsockopt(borrowed_fd fd, int level, int optname, const void* optval, socklen_t optlen) {
Josh Gao64a63ac2018-04-05 18:09:02 -07001045 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001046
Josh Gao64a63ac2018-04-05 18:09:02 -07001047 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001048 D("adb_setsockopt: invalid fd %d", fd.get());
Spencer Low5200c662015-07-30 23:07:55 -07001049 errno = EBADF;
1050 return -1;
1051 }
Spencer Low677fb432015-09-29 15:05:29 -07001052
1053 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1054 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1055 // auto-tuning.
1056
Josh Gao64a63ac2018-04-05 18:09:02 -07001057 int result =
1058 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1059 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001060 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001061 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd.get(), level,
Josh Gao64a63ac2018-04-05 18:09:02 -07001062 optname, android::base::SystemErrorCodeToString(err).c_str());
1063 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -07001064 result = -1;
1065 }
1066 return result;
1067}
1068
Josh Gao27241a72019-04-25 14:04:57 -07001069static int adb_getsockname(borrowed_fd fd, struct sockaddr* sockaddr, socklen_t* optlen) {
Josh Gao3777d2e2016-02-16 17:34:53 -08001070 FH fh = _fh_from_int(fd, __func__);
1071
1072 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001073 D("adb_getsockname: invalid fd %d", fd.get());
Josh Gao3777d2e2016-02-16 17:34:53 -08001074 errno = EBADF;
1075 return -1;
1076 }
1077
Josh Gao3726a012017-03-30 13:04:35 -07001078 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001079 if (result == SOCKET_ERROR) {
1080 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001081 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd.get(),
Josh Gao3777d2e2016-02-16 17:34:53 -08001082 android::base::SystemErrorCodeToString(err).c_str());
1083 _socket_set_errno(err);
1084 result = -1;
1085 }
1086 return result;
1087}
Spencer Low5200c662015-07-30 23:07:55 -07001088
Josh Gao27241a72019-04-25 14:04:57 -07001089int adb_socket_get_local_port(borrowed_fd fd) {
David Purselleaae97e2016-04-07 11:25:48 -07001090 sockaddr_storage addr_storage;
1091 socklen_t addr_len = sizeof(addr_storage);
1092
1093 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1094 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1095 return -1;
1096 }
1097
1098 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1099 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1100 errno = ECONNABORTED;
1101 return -1;
1102 }
1103
1104 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1105}
1106
Josh Gao27241a72019-04-25 14:04:57 -07001107int adb_shutdown(borrowed_fd fd, int direction) {
Josh Gao2e1e7892018-03-23 13:03:28 -07001108 FH f = _fh_from_int(fd, __func__);
Spencer Low5200c662015-07-30 23:07:55 -07001109
1110 if (!f || f->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001111 D("adb_shutdown: invalid fd %d", fd.get());
Spencer Low5200c662015-07-30 23:07:55 -07001112 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001113 return -1;
1114 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001115
Josh Gao2e1e7892018-03-23 13:03:28 -07001116 D("adb_shutdown: %s", f->name);
1117 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001118 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001119 D("socket shutdown fd %d failed: %s", fd.get(),
David Pursell5f787ed2016-01-27 08:52:53 -08001120 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001121 _socket_set_errno(err);
1122 return -1;
1123 }
1124 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001125}
1126
Josh Gao3777d2e2016-02-16 17:34:53 -08001127// Emulate socketpair(2) by binding and connecting to a socket.
1128int adb_socketpair(int sv[2]) {
1129 int server = -1;
1130 int client = -1;
1131 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001132 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001133 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001134
Josh Gao3777d2e2016-02-16 17:34:53 -08001135 server = network_loopback_server(0, SOCK_STREAM, &error);
1136 if (server < 0) {
1137 D("adb_socketpair: failed to create server: %s", error.c_str());
1138 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001139 }
1140
David Purselleaae97e2016-04-07 11:25:48 -07001141 local_port = adb_socket_get_local_port(server);
1142 if (local_port < 0) {
1143 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001144 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001145 }
David Purselleaae97e2016-04-07 11:25:48 -07001146 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001147
David Purselleaae97e2016-04-07 11:25:48 -07001148 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001149 if (client < 0) {
1150 D("adb_socketpair: failed to connect client: %s", error.c_str());
1151 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001152 }
1153
Josh Gao3726a012017-03-30 13:04:35 -07001154 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gao3777d2e2016-02-16 17:34:53 -08001155 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001156 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001157 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001158 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001159 adb_close(server);
1160 sv[0] = client;
1161 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001162 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001163
Josh Gao3777d2e2016-02-16 17:34:53 -08001164fail:
1165 if (server >= 0) {
1166 adb_close(server);
1167 }
1168 if (client >= 0) {
1169 adb_close(client);
1170 }
1171 if (accepted >= 0) {
1172 adb_close(accepted);
1173 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001174 return -1;
1175}
1176
Josh Gao27241a72019-04-25 14:04:57 -07001177bool set_file_block_mode(borrowed_fd fd, bool block) {
Josh Gao3777d2e2016-02-16 17:34:53 -08001178 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001179
Josh Gao3777d2e2016-02-16 17:34:53 -08001180 if (!fh || !fh->used) {
1181 errno = EBADF;
Josh Gao27241a72019-04-25 14:04:57 -07001182 D("Setting nonblocking on bad file descriptor %d", fd.get());
Josh Gao3777d2e2016-02-16 17:34:53 -08001183 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001184 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185
Josh Gao3777d2e2016-02-16 17:34:53 -08001186 if (fh->clazz == &_fh_socket_class) {
1187 u_long x = !block;
1188 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001189 int error = WSAGetLastError();
1190 _socket_set_errno(error);
Josh Gao27241a72019-04-25 14:04:57 -07001191 D("Setting %d nonblocking failed (%d)", fd.get(), error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001192 return false;
1193 }
1194 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001195 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001196 errno = ENOTSOCK;
Josh Gao27241a72019-04-25 14:04:57 -07001197 D("Setting nonblocking on non-socket %d", fd.get());
Josh Gao3777d2e2016-02-16 17:34:53 -08001198 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001199 }
1200}
1201
Josh Gao27241a72019-04-25 14:04:57 -07001202bool set_tcp_keepalive(borrowed_fd fd, int interval_sec) {
David Pursellbfd95032016-02-22 14:27:23 -08001203 FH fh = _fh_from_int(fd, __func__);
1204
1205 if (!fh || fh->clazz != &_fh_socket_class) {
Josh Gao27241a72019-04-25 14:04:57 -07001206 D("set_tcp_keepalive(%d) failed: invalid fd", fd.get());
David Pursellbfd95032016-02-22 14:27:23 -08001207 errno = EBADF;
1208 return false;
1209 }
1210
1211 tcp_keepalive keepalive;
1212 keepalive.onoff = (interval_sec > 0);
1213 keepalive.keepalivetime = interval_sec * 1000;
1214 keepalive.keepaliveinterval = interval_sec * 1000;
1215
1216 DWORD bytes_returned = 0;
1217 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1218 &bytes_returned, nullptr, nullptr) != 0) {
1219 const DWORD err = WSAGetLastError();
Josh Gao27241a72019-04-25 14:04:57 -07001220 D("set_tcp_keepalive(%d) failed: %s", fd.get(),
David Pursellbfd95032016-02-22 14:27:23 -08001221 android::base::SystemErrorCodeToString(err).c_str());
1222 _socket_set_errno(err);
1223 return false;
1224 }
1225
1226 return true;
1227}
1228
Spencer Low50184062015-03-01 15:06:21 -08001229/**************************************************************************/
1230/**************************************************************************/
1231/***** *****/
1232/***** Console Window Terminal Emulation *****/
1233/***** *****/
1234/**************************************************************************/
1235/**************************************************************************/
1236
1237// This reads input from a Win32 console window and translates it into Unix
1238// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1239// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1240// is emulated instead of xterm because it is probably more popular than xterm:
1241// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1242// supports modern fonts, etc. It seems best to emulate the terminal that most
1243// Android developers use because they'll fix apps (the shell, etc.) to keep
1244// working with that terminal's emulation.
1245//
1246// The point of this emulation is not to be perfect or to solve all issues with
1247// console windows on Windows, but to be better than the original code which
1248// just called read() (which called ReadFile(), which called ReadConsoleA())
1249// which did not support Ctrl-C, tab completion, shell input line editing
1250// keys, server echo, and more.
1251//
1252// This implementation reconfigures the console with SetConsoleMode(), then
1253// calls ReadConsoleInput() to get raw input which it remaps to Unix
1254// terminal-style sequences which is returned via unix_read() which is used
1255// by the 'adb shell' command.
1256//
1257// Code organization:
1258//
David Pursellc5b8ad82015-10-28 14:29:51 -07001259// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001260// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1261// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1262// * _console_read() is the main code of the emulation.
1263
David Pursellc5b8ad82015-10-28 14:29:51 -07001264// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1265// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1266// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
Josh Gao27241a72019-04-25 14:04:57 -07001267static HANDLE _get_console_handle(borrowed_fd fd, DWORD* mode = nullptr) {
David Pursellc5b8ad82015-10-28 14:29:51 -07001268 // First check isatty(); this is very fast and eliminates most non-console
1269 // FDs, but returns 1 for both consoles and character devices like NUL.
1270#pragma push_macro("isatty")
1271#undef isatty
Josh Gao27241a72019-04-25 14:04:57 -07001272 if (!isatty(fd.get())) {
David Pursellc5b8ad82015-10-28 14:29:51 -07001273 return nullptr;
1274 }
1275#pragma pop_macro("isatty")
1276
1277 // To differentiate between character devices and consoles we need to get
1278 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1279 // GENERIC_READ permissions.
Josh Gao27241a72019-04-25 14:04:57 -07001280 const intptr_t intptr_handle = _get_osfhandle(fd.get());
David Pursellc5b8ad82015-10-28 14:29:51 -07001281 if (intptr_handle == -1) {
1282 return nullptr;
1283 }
1284 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1285 DWORD temp_mode = 0;
1286 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1287 return nullptr;
1288 }
1289
1290 return handle;
1291}
1292
1293// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1294static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001295 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1296 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001297 const int fd = fileno(stream);
1298 if (fd < 0) {
1299 return nullptr;
1300 }
1301 return _get_console_handle(fd);
1302}
1303
Josh Gao27241a72019-04-25 14:04:57 -07001304int unix_isatty(borrowed_fd fd) {
David Pursellc5b8ad82015-10-28 14:29:51 -07001305 return _get_console_handle(fd) ? 1 : 0;
1306}
Spencer Low50184062015-03-01 15:06:21 -08001307
Spencer Low32762f42015-11-10 19:17:16 -08001308// Get the next KEY_EVENT_RECORD that should be processed.
1309static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001310 for (;;) {
1311 DWORD read_count = 0;
1312 memset(input_record, 0, sizeof(*input_record));
1313 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001314 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001315 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001316 errno = EIO;
1317 return false;
1318 }
1319
1320 if (read_count == 0) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001321 LOG(FATAL) << "ReadConsoleInputA returned 0";
Spencer Low50184062015-03-01 15:06:21 -08001322 }
1323
1324 if (read_count != 1) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001325 LOG(FATAL) << "ReadConsoleInputA did not return one input record";
Spencer Low50184062015-03-01 15:06:21 -08001326 }
1327
Spencer Low2e02dc62015-11-07 17:34:39 -08001328 // If the console window is resized, emulate SIGWINCH by breaking out
1329 // of read() with errno == EINTR. Note that there is no event on
1330 // vertical resize because we don't give the console our own custom
1331 // screen buffer (with CreateConsoleScreenBuffer() +
1332 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1333 // supports scrollback, but doesn't seem to raise an event for vertical
1334 // window resize.
1335 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1336 errno = EINTR;
1337 return false;
1338 }
1339
Spencer Low50184062015-03-01 15:06:21 -08001340 if ((input_record->EventType == KEY_EVENT) &&
1341 (input_record->Event.KeyEvent.bKeyDown)) {
1342 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -07001343 LOG(FATAL) << "ReadConsoleInputA returned a key event with zero repeat count";
Spencer Low50184062015-03-01 15:06:21 -08001344 }
1345
1346 // Got an interesting INPUT_RECORD, so return
1347 return true;
1348 }
1349 }
1350}
1351
Spencer Low50184062015-03-01 15:06:21 -08001352static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1353 return (control_key_state & SHIFT_PRESSED) != 0;
1354}
1355
1356static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1357 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1358}
1359
1360static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1361 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1362}
1363
1364static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1365 return (control_key_state & NUMLOCK_ON) != 0;
1366}
1367
1368static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1369 return (control_key_state & CAPSLOCK_ON) != 0;
1370}
1371
1372static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1373 return (control_key_state & ENHANCED_KEY) != 0;
1374}
1375
1376// Constants from MSDN for ToAscii().
1377static const BYTE TOASCII_KEY_OFF = 0x00;
1378static const BYTE TOASCII_KEY_DOWN = 0x80;
1379static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1380
1381// Given a key event, ignore a modifier key and return the character that was
1382// entered without the modifier. Writes to *ch and returns the number of bytes
1383// written.
1384static size_t _get_char_ignoring_modifier(char* const ch,
1385 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1386 const WORD modifier) {
1387 // If there is no character from Windows, try ignoring the specified
1388 // modifier and look for a character. Note that if AltGr is being used,
1389 // there will be a character from Windows.
1390 if (key_event->uChar.AsciiChar == '\0') {
1391 // Note that we read the control key state from the passed in argument
1392 // instead of from key_event since the argument has been normalized.
1393 if (((modifier == VK_SHIFT) &&
1394 _is_shift_pressed(control_key_state)) ||
1395 ((modifier == VK_CONTROL) &&
1396 _is_ctrl_pressed(control_key_state)) ||
1397 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1398
1399 BYTE key_state[256] = {0};
1400 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1401 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1402 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1403 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1404 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1405 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1406 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1407 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1408
1409 // cause this modifier to be ignored
1410 key_state[modifier] = TOASCII_KEY_OFF;
1411
1412 WORD translated = 0;
1413 if (ToAscii(key_event->wVirtualKeyCode,
1414 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1415 // Ignoring the modifier, we found a character.
1416 *ch = (CHAR)translated;
1417 return 1;
1418 }
1419 }
1420 }
1421
1422 // Just use whatever Windows told us originally.
1423 *ch = key_event->uChar.AsciiChar;
1424
1425 // If the character from Windows is NULL, return a size of zero.
1426 return (*ch == '\0') ? 0 : 1;
1427}
1428
1429// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1430// but taking into account the shift key. This is because for a sequence like
1431// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1432// we want to find the character ')'.
1433//
1434// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1435// because it is the default key-sequence to switch the input language.
1436// This is configurable in the Region and Language control panel.
1437static __inline__ size_t _get_non_control_char(char* const ch,
1438 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1439 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1440 VK_CONTROL);
1441}
1442
1443// Get without Alt.
1444static __inline__ size_t _get_non_alt_char(char* const ch,
1445 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1446 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1447 VK_MENU);
1448}
1449
1450// Ignore the control key, find the character from Windows, and apply any
1451// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1452// *pch and returns number of bytes written.
1453static size_t _get_control_character(char* const pch,
1454 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1455 const size_t len = _get_non_control_char(pch, key_event,
1456 control_key_state);
1457
1458 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1459 char ch = *pch;
1460 switch (ch) {
1461 case '2':
1462 case '@':
1463 case '`':
1464 ch = '\0';
1465 break;
1466 case '3':
1467 case '[':
1468 case '{':
1469 ch = '\x1b';
1470 break;
1471 case '4':
1472 case '\\':
1473 case '|':
1474 ch = '\x1c';
1475 break;
1476 case '5':
1477 case ']':
1478 case '}':
1479 ch = '\x1d';
1480 break;
1481 case '6':
1482 case '^':
1483 case '~':
1484 ch = '\x1e';
1485 break;
1486 case '7':
1487 case '-':
1488 case '_':
1489 ch = '\x1f';
1490 break;
1491 case '8':
1492 ch = '\x7f';
1493 break;
1494 case '/':
1495 if (!_is_alt_pressed(control_key_state)) {
1496 ch = '\x1f';
1497 }
1498 break;
1499 case '?':
1500 if (!_is_alt_pressed(control_key_state)) {
1501 ch = '\x7f';
1502 }
1503 break;
1504 }
1505 *pch = ch;
1506 }
1507
1508 return len;
1509}
1510
1511static DWORD _normalize_altgr_control_key_state(
1512 const KEY_EVENT_RECORD* const key_event) {
1513 DWORD control_key_state = key_event->dwControlKeyState;
1514
1515 // If we're in an AltGr situation where the AltGr key is down (depending on
1516 // the keyboard layout, that might be the physical right alt key which
1517 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1518 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1519 // a character (which indicates that there was an AltGr mapping), then act
1520 // as if alt and control are not really down for the purposes of modifiers.
1521 // This makes it so that if the user with, say, a German keyboard layout
1522 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1523 // output the key and we don't see the Alt and Ctrl keys.
1524 if (_is_ctrl_pressed(control_key_state) &&
1525 _is_alt_pressed(control_key_state)
1526 && (key_event->uChar.AsciiChar != '\0')) {
1527 // Try to remove as few bits as possible to improve our chances of
1528 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1529 // Left-Alt + Right-Ctrl + AltGr.
1530 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1531 // Remove Right-Alt.
1532 control_key_state &= ~RIGHT_ALT_PRESSED;
1533 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1534 // pressed, Left-Ctrl is almost always set, except if the user
1535 // presses Right-Ctrl, then AltGr (in that specific order) for
1536 // whatever reason. At any rate, make sure the bit is not set.
1537 control_key_state &= ~LEFT_CTRL_PRESSED;
1538 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1539 // Remove Left-Alt.
1540 control_key_state &= ~LEFT_ALT_PRESSED;
1541 // Whichever Ctrl key is down, remove it from the state. We only
1542 // remove one key, to improve our chances of detecting the
1543 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1544 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1545 // Remove Left-Ctrl.
1546 control_key_state &= ~LEFT_CTRL_PRESSED;
1547 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1548 // Remove Right-Ctrl.
1549 control_key_state &= ~RIGHT_CTRL_PRESSED;
1550 }
1551 }
1552
1553 // Note that this logic isn't 100% perfect because Windows doesn't
1554 // allow us to detect all combinations because a physical AltGr key
1555 // press shows up as two bits, plus some combinations are ambiguous
1556 // about what is actually physically pressed.
1557 }
1558
1559 return control_key_state;
1560}
1561
1562// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1563// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1564// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1565// appropriately.
1566static DWORD _normalize_keypad_control_key_state(const WORD vk,
1567 const DWORD control_key_state) {
1568 if (!_is_numlock_on(control_key_state)) {
1569 return control_key_state;
1570 }
1571 if (!_is_enhanced_key(control_key_state)) {
1572 switch (vk) {
1573 case VK_INSERT: // 0
1574 case VK_DELETE: // .
1575 case VK_END: // 1
1576 case VK_DOWN: // 2
1577 case VK_NEXT: // 3
1578 case VK_LEFT: // 4
1579 case VK_CLEAR: // 5
1580 case VK_RIGHT: // 6
1581 case VK_HOME: // 7
1582 case VK_UP: // 8
1583 case VK_PRIOR: // 9
1584 return control_key_state | SHIFT_PRESSED;
1585 }
1586 }
1587
1588 return control_key_state;
1589}
1590
1591static const char* _get_keypad_sequence(const DWORD control_key_state,
1592 const char* const normal, const char* const shifted) {
1593 if (_is_shift_pressed(control_key_state)) {
1594 // Shift is pressed and NumLock is off
1595 return shifted;
1596 } else {
1597 // Shift is not pressed and NumLock is off, or,
1598 // Shift is pressed and NumLock is on, in which case we want the
1599 // NumLock and Shift to neutralize each other, thus, we want the normal
1600 // sequence.
1601 return normal;
1602 }
1603 // If Shift is not pressed and NumLock is on, a different virtual key code
1604 // is returned by Windows, which can be taken care of by a different case
1605 // statement in _console_read().
1606}
1607
1608// Write sequence to buf and return the number of bytes written.
1609static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1610 DWORD control_key_state, const char* const normal) {
1611 // Copy the base sequence into buf.
1612 const size_t len = strlen(normal);
1613 memcpy(buf, normal, len);
1614
1615 int code = 0;
1616
1617 control_key_state = _normalize_keypad_control_key_state(vk,
1618 control_key_state);
1619
1620 if (_is_shift_pressed(control_key_state)) {
1621 code |= 0x1;
1622 }
1623 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1624 code |= 0x2;
1625 }
1626 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1627 code |= 0x4;
1628 }
1629 // If some modifier was held down, then we need to insert the modifier code
1630 if (code != 0) {
1631 if (len == 0) {
1632 // Should be impossible because caller should pass a string of
1633 // non-zero length.
1634 return 0;
1635 }
1636 size_t index = len - 1;
1637 const char lastChar = buf[index];
1638 if (lastChar != '~') {
1639 buf[index++] = '1';
1640 }
1641 buf[index++] = ';'; // modifier separator
1642 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1643 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1644 buf[index++] = '1' + code;
1645 buf[index++] = lastChar; // move ~ (or other last char) to the end
1646 return index;
1647 }
1648 return len;
1649}
1650
1651// Write sequence to buf and return the number of bytes written.
1652static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1653 const DWORD control_key_state, const char* const normal,
1654 const char shifted) {
1655 if (_is_shift_pressed(control_key_state)) {
1656 // Shift is pressed and NumLock is off
1657 if (shifted != '\0') {
1658 buf[0] = shifted;
1659 return sizeof(buf[0]);
1660 } else {
1661 return 0;
1662 }
1663 } else {
1664 // Shift is not pressed and NumLock is off, or,
1665 // Shift is pressed and NumLock is on, in which case we want the
1666 // NumLock and Shift to neutralize each other, thus, we want the normal
1667 // sequence.
1668 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1669 }
1670 // If Shift is not pressed and NumLock is on, a different virtual key code
1671 // is returned by Windows, which can be taken care of by a different case
1672 // statement in _console_read().
1673}
1674
1675// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1676// Standard German. Figure this out at runtime so we know what to output for
1677// Shift-VK_DELETE.
1678static char _get_decimal_char() {
1679 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1680}
1681
1682// Prefix the len bytes in buf with the escape character, and then return the
1683// new buffer length.
Josh Gao27241a72019-04-25 14:04:57 -07001684static size_t _escape_prefix(char* const buf, const size_t len) {
Spencer Low50184062015-03-01 15:06:21 -08001685 // If nothing to prefix, don't do anything. We might be called with
1686 // len == 0, if alt was held down with a dead key which produced nothing.
1687 if (len == 0) {
1688 return 0;
1689 }
1690
1691 memmove(&buf[1], buf, len);
1692 buf[0] = '\x1b';
1693 return len + 1;
1694}
1695
Spencer Low32762f42015-11-10 19:17:16 -08001696// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001697static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001698
1699// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1700// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001701static int _console_read(const HANDLE console, void* buf, size_t len) {
1702 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001703 // Read of zero bytes should not block waiting for something from the console.
1704 if (len == 0) {
1705 return 0;
1706 }
1707
1708 // Flush as much as possible from input buffer.
1709 if (!g_console_input_buffer.empty()) {
1710 const int bytes_read = std::min(len, g_console_input_buffer.size());
1711 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1712 const auto begin = g_console_input_buffer.begin();
1713 g_console_input_buffer.erase(begin, begin + bytes_read);
1714 return bytes_read;
1715 }
1716
1717 // Read from the actual console. This may block until input.
1718 INPUT_RECORD input_record;
1719 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001720 return -1;
1721 }
1722
Spencer Low32762f42015-11-10 19:17:16 -08001723 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001724 const WORD vk = key_event->wVirtualKeyCode;
1725 const CHAR ch = key_event->uChar.AsciiChar;
1726 const DWORD control_key_state = _normalize_altgr_control_key_state(
1727 key_event);
1728
1729 // The following emulation code should write the output sequence to
1730 // either seqstr or to seqbuf and seqbuflen.
Yi Kongaed415c2018-07-13 18:15:16 -07001731 const char* seqstr = nullptr; // NULL terminated C-string
Spencer Low50184062015-03-01 15:06:21 -08001732 // Enough space for max sequence string below, plus modifiers and/or
1733 // escape prefix.
1734 char seqbuf[16];
1735 size_t seqbuflen = 0; // Space used in seqbuf.
1736
1737#define MATCH(vk, normal) \
1738 case (vk): \
1739 { \
1740 seqstr = (normal); \
1741 } \
1742 break;
1743
1744 // Modifier keys should affect the output sequence.
1745#define MATCH_MODIFIER(vk, normal) \
1746 case (vk): \
1747 { \
1748 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1749 control_key_state, (normal)); \
1750 } \
1751 break;
1752
1753 // The shift key should affect the output sequence.
1754#define MATCH_KEYPAD(vk, normal, shifted) \
1755 case (vk): \
1756 { \
1757 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1758 (shifted)); \
1759 } \
1760 break;
1761
1762 // The shift key and other modifier keys should affect the output
1763 // sequence.
1764#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1765 case (vk): \
1766 { \
1767 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1768 control_key_state, (normal), (shifted)); \
1769 } \
1770 break;
1771
1772#define ESC "\x1b"
1773#define CSI ESC "["
1774#define SS3 ESC "O"
1775
1776 // Only support normal mode, not application mode.
1777
1778 // Enhanced keys:
1779 // * 6-pack: insert, delete, home, end, page up, page down
1780 // * cursor keys: up, down, right, left
1781 // * keypad: divide, enter
1782 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1783 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1784 if (_is_enhanced_key(control_key_state)) {
1785 switch (vk) {
1786 case VK_RETURN: // Enter key on keypad
1787 if (_is_ctrl_pressed(control_key_state)) {
1788 seqstr = "\n";
1789 } else {
1790 seqstr = "\r";
1791 }
1792 break;
1793
1794 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1795 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1796
1797 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1798 // will be fixed soon to match xterm which sends CSI "F" and
1799 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1800 MATCH(VK_END, CSI "F");
1801 MATCH(VK_HOME, CSI "H");
1802
1803 MATCH_MODIFIER(VK_LEFT, CSI "D");
1804 MATCH_MODIFIER(VK_UP, CSI "A");
1805 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1806 MATCH_MODIFIER(VK_DOWN, CSI "B");
1807
1808 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1809 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1810
1811 MATCH(VK_DIVIDE, "/");
1812 }
1813 } else { // Non-enhanced keys:
1814 switch (vk) {
1815 case VK_BACK: // backspace
1816 if (_is_alt_pressed(control_key_state)) {
1817 seqstr = ESC "\x7f";
1818 } else {
1819 seqstr = "\x7f";
1820 }
1821 break;
1822
1823 case VK_TAB:
1824 if (_is_shift_pressed(control_key_state)) {
1825 seqstr = CSI "Z";
1826 } else {
1827 seqstr = "\t";
1828 }
1829 break;
1830
1831 // Number 5 key in keypad when NumLock is off, or if NumLock is
1832 // on and Shift is down.
1833 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1834
1835 case VK_RETURN: // Enter key on main keyboard
1836 if (_is_alt_pressed(control_key_state)) {
1837 seqstr = ESC "\n";
1838 } else if (_is_ctrl_pressed(control_key_state)) {
1839 seqstr = "\n";
1840 } else {
1841 seqstr = "\r";
1842 }
1843 break;
1844
1845 // VK_ESCAPE: Don't do any special handling. The OS uses many
1846 // of the sequences with Escape and many of the remaining
1847 // sequences don't produce bKeyDown messages, only !bKeyDown
1848 // for whatever reason.
1849
1850 case VK_SPACE:
1851 if (_is_alt_pressed(control_key_state)) {
1852 seqstr = ESC " ";
1853 } else if (_is_ctrl_pressed(control_key_state)) {
1854 seqbuf[0] = '\0'; // NULL char
1855 seqbuflen = 1;
1856 } else {
1857 seqstr = " ";
1858 }
1859 break;
1860
1861 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1862 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1863
1864 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1865 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1866
1867 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1868 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1869 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1870 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1871
1872 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1873 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1874 _get_decimal_char());
1875
1876 case 0x30: // 0
1877 case 0x31: // 1
1878 case 0x39: // 9
1879 case VK_OEM_1: // ;:
1880 case VK_OEM_PLUS: // =+
1881 case VK_OEM_COMMA: // ,<
1882 case VK_OEM_PERIOD: // .>
1883 case VK_OEM_7: // '"
1884 case VK_OEM_102: // depends on keyboard, could be <> or \|
1885 case VK_OEM_2: // /?
1886 case VK_OEM_3: // `~
1887 case VK_OEM_4: // [{
1888 case VK_OEM_5: // \|
1889 case VK_OEM_6: // ]}
1890 {
1891 seqbuflen = _get_control_character(seqbuf, key_event,
1892 control_key_state);
1893
1894 if (_is_alt_pressed(control_key_state)) {
1895 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1896 }
1897 }
1898 break;
1899
1900 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001901 case 0x33: // 3
1902 case 0x34: // 4
1903 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001904 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001905 case 0x37: // 7
1906 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001907 case VK_OEM_MINUS: // -_
1908 {
1909 seqbuflen = _get_control_character(seqbuf, key_event,
1910 control_key_state);
1911
1912 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1913 // prefix with escape.
1914 if (_is_alt_pressed(control_key_state) &&
1915 !(_is_ctrl_pressed(control_key_state) &&
1916 !_is_shift_pressed(control_key_state))) {
1917 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1918 }
1919 }
1920 break;
1921
Spencer Low50184062015-03-01 15:06:21 -08001922 case 0x41: // a
1923 case 0x42: // b
1924 case 0x43: // c
1925 case 0x44: // d
1926 case 0x45: // e
1927 case 0x46: // f
1928 case 0x47: // g
1929 case 0x48: // h
1930 case 0x49: // i
1931 case 0x4a: // j
1932 case 0x4b: // k
1933 case 0x4c: // l
1934 case 0x4d: // m
1935 case 0x4e: // n
1936 case 0x4f: // o
1937 case 0x50: // p
1938 case 0x51: // q
1939 case 0x52: // r
1940 case 0x53: // s
1941 case 0x54: // t
1942 case 0x55: // u
1943 case 0x56: // v
1944 case 0x57: // w
1945 case 0x58: // x
1946 case 0x59: // y
1947 case 0x5a: // z
1948 {
1949 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1950 control_key_state);
1951
1952 // If Alt is pressed, then prefix with escape.
1953 if (_is_alt_pressed(control_key_state)) {
1954 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1955 }
1956 }
1957 break;
1958
1959 // These virtual key codes are generated by the keys on the
1960 // keypad *when NumLock is on* and *Shift is up*.
1961 MATCH(VK_NUMPAD0, "0");
1962 MATCH(VK_NUMPAD1, "1");
1963 MATCH(VK_NUMPAD2, "2");
1964 MATCH(VK_NUMPAD3, "3");
1965 MATCH(VK_NUMPAD4, "4");
1966 MATCH(VK_NUMPAD5, "5");
1967 MATCH(VK_NUMPAD6, "6");
1968 MATCH(VK_NUMPAD7, "7");
1969 MATCH(VK_NUMPAD8, "8");
1970 MATCH(VK_NUMPAD9, "9");
1971
1972 MATCH(VK_MULTIPLY, "*");
1973 MATCH(VK_ADD, "+");
1974 MATCH(VK_SUBTRACT, "-");
1975 // VK_DECIMAL is generated by the . key on the keypad *when
1976 // NumLock is on* and *Shift is up* and the sequence is not
1977 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1978 // Windows Security screen to come up).
1979 case VK_DECIMAL:
1980 // U.S. English uses '.', Germany German uses ','.
1981 seqbuflen = _get_non_control_char(seqbuf, key_event,
1982 control_key_state);
1983 break;
1984
1985 MATCH_MODIFIER(VK_F1, SS3 "P");
1986 MATCH_MODIFIER(VK_F2, SS3 "Q");
1987 MATCH_MODIFIER(VK_F3, SS3 "R");
1988 MATCH_MODIFIER(VK_F4, SS3 "S");
1989 MATCH_MODIFIER(VK_F5, CSI "15~");
1990 MATCH_MODIFIER(VK_F6, CSI "17~");
1991 MATCH_MODIFIER(VK_F7, CSI "18~");
1992 MATCH_MODIFIER(VK_F8, CSI "19~");
1993 MATCH_MODIFIER(VK_F9, CSI "20~");
1994 MATCH_MODIFIER(VK_F10, CSI "21~");
1995 MATCH_MODIFIER(VK_F11, CSI "23~");
1996 MATCH_MODIFIER(VK_F12, CSI "24~");
1997
1998 MATCH_MODIFIER(VK_F13, CSI "25~");
1999 MATCH_MODIFIER(VK_F14, CSI "26~");
2000 MATCH_MODIFIER(VK_F15, CSI "28~");
2001 MATCH_MODIFIER(VK_F16, CSI "29~");
2002 MATCH_MODIFIER(VK_F17, CSI "31~");
2003 MATCH_MODIFIER(VK_F18, CSI "32~");
2004 MATCH_MODIFIER(VK_F19, CSI "33~");
2005 MATCH_MODIFIER(VK_F20, CSI "34~");
2006
2007 // MATCH_MODIFIER(VK_F21, ???);
2008 // MATCH_MODIFIER(VK_F22, ???);
2009 // MATCH_MODIFIER(VK_F23, ???);
2010 // MATCH_MODIFIER(VK_F24, ???);
2011 }
2012 }
2013
2014#undef MATCH
2015#undef MATCH_MODIFIER
2016#undef MATCH_KEYPAD
2017#undef MATCH_MODIFIER_KEYPAD
2018#undef ESC
2019#undef CSI
2020#undef SS3
2021
2022 const char* out;
2023 size_t outlen;
2024
2025 // Check for output in any of:
2026 // * seqstr is set (and strlen can be used to determine the length).
2027 // * seqbuf and seqbuflen are set
2028 // Fallback to ch from Windows.
Yi Kongaed415c2018-07-13 18:15:16 -07002029 if (seqstr != nullptr) {
Spencer Low50184062015-03-01 15:06:21 -08002030 out = seqstr;
2031 outlen = strlen(seqstr);
2032 } else if (seqbuflen > 0) {
2033 out = seqbuf;
2034 outlen = seqbuflen;
2035 } else if (ch != '\0') {
2036 // Use whatever Windows told us it is.
2037 seqbuf[0] = ch;
2038 seqbuflen = 1;
2039 out = seqbuf;
2040 outlen = seqbuflen;
2041 } else {
2042 // No special handling for the virtual key code and Windows isn't
2043 // telling us a character code, then we don't know how to translate
2044 // the key press.
2045 //
2046 // Consume the input and 'continue' to cause us to get a new key
2047 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002048 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002049 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002050 continue;
2051 }
2052
Spencer Low32762f42015-11-10 19:17:16 -08002053 // put output wRepeatCount times into g_console_input_buffer
2054 while (key_event->wRepeatCount-- > 0) {
2055 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002056 }
2057
Spencer Low32762f42015-11-10 19:17:16 -08002058 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002059 }
2060}
2061
2062static DWORD _old_console_mode; // previous GetConsoleMode() result
2063static HANDLE _console_handle; // when set, console mode should be restored
2064
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002065void stdin_raw_init() {
2066 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002067 if (in == nullptr) {
2068 return;
2069 }
Spencer Low50184062015-03-01 15:06:21 -08002070
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002071 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2072 // calling the process Ctrl-C routine (configured by
2073 // SetConsoleCtrlHandler()).
2074 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2075 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2076 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002077 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2078 ENABLE_LINE_INPUT |
2079 ENABLE_ECHO_INPUT);
2080 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2081 new_console_mode |= ENABLE_WINDOW_INPUT;
2082
2083 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002084 // This really should not fail.
2085 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002086 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002087 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002088
2089 // Once this is set, it means that stdin has been configured for
2090 // reading from and that the old console mode should be restored later.
2091 _console_handle = in;
2092
2093 // Note that we don't need to configure C Runtime line-ending
2094 // translation because _console_read() does not call the C Runtime to
2095 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002096}
2097
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002098void stdin_raw_restore() {
Yi Kongaed415c2018-07-13 18:15:16 -07002099 if (_console_handle != nullptr) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002100 const HANDLE in = _console_handle;
Yi Kongaed415c2018-07-13 18:15:16 -07002101 _console_handle = nullptr; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002102
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002103 if (!SetConsoleMode(in, _old_console_mode)) {
2104 // This really should not fail.
2105 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002106 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002107 }
2108 }
2109}
2110
Spencer Low2e02dc62015-11-07 17:34:39 -08002111// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
Josh Gao27241a72019-04-25 14:04:57 -07002112int unix_read_interruptible(borrowed_fd fd, void* buf, size_t len) {
Yi Kongaed415c2018-07-13 18:15:16 -07002113 if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) {
Spencer Low50184062015-03-01 15:06:21 -08002114 // If it is a request to read from stdin, and stdin_raw_init() has been
2115 // called, and it successfully configured the console, then read from
2116 // the console using Win32 console APIs and partially emulate a unix
2117 // terminal.
2118 return _console_read(_console_handle, buf, len);
2119 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002120 // On older versions of Windows (definitely 7, definitely not 10),
2121 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002122 // we need to limit the read size.
2123 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002124 len = 4096;
2125 }
Spencer Low50184062015-03-01 15:06:21 -08002126 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002127 // can do LF/CR translation (which is overridable with _setmode()).
2128 // Undefine the macro that is set in sysdeps.h which bans calls to
2129 // plain read() in favor of unix_read() or adb_read().
2130#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002131#undef read
Josh Gao27241a72019-04-25 14:04:57 -07002132 return read(fd.get(), buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002133#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002134 }
2135}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002136
2137/**************************************************************************/
2138/**************************************************************************/
2139/***** *****/
2140/***** Unicode support *****/
2141/***** *****/
2142/**************************************************************************/
2143/**************************************************************************/
2144
2145// This implements support for using files with Unicode filenames and for
2146// outputting Unicode text to a Win32 console window. This is inspired from
2147// http://utf8everywhere.org/.
2148//
2149// Background
2150// ----------
2151//
2152// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2153// filenames to APIs such as open(). This works because filenames are largely
2154// opaque 'cookies' (perhaps excluding path separators).
2155//
2156// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2157// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2158// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2159// CreateFile() API is really just a macro that adds the W/A based on whether
2160// the UNICODE preprocessor symbol is defined).
2161//
2162// Options
2163// -------
2164//
2165// Thus, to write a portable program, there are a few options:
2166//
2167// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2168// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2169// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2170// open() API.
2171//
2172// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2173// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2174// potentially touching a lot of code.
2175//
2176// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2177// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2178// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2179// or C Runtime API.
2180//
2181// The Choice
2182// ----------
2183//
Spencer Lowd21dc822015-11-12 15:20:15 -08002184// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2185// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002186// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002187// args that are passed to main() at the beginning of program startup. We also use
2188// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002189// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2190//
2191// Unicode console output
2192// ----------------------
2193//
2194// The way to output Unicode to a Win32 console window is to call
2195// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002196// such as Lucida Console or Consolas, and in the case of East Asian languages
2197// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2198// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2199// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002200//
2201// The problem is getting the C Runtime to make fprintf and related APIs call
2202// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2203// promising, but the various modes have issues:
2204//
2205// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2206// UTF-16 do not display properly.
2207// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2208// totally wrong.
2209// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2210// handler to be called (upon a later I/O call), aborting the process.
2211// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2212// to output nothing.
2213//
2214// So the only solution is to write our own adb_fprintf() that converts UTF-8
2215// to UTF-16 and then calls WriteConsoleW().
2216
2217
Spencer Lowcf4ff642015-05-11 01:08:48 -07002218// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2219// be passed to main().
2220NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2221 narrow_args = new char*[argc + 1];
2222
2223 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002224 std::string arg_narrow;
2225 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
Elliott Hughes4679a392018-10-19 13:59:44 -07002226 PLOG(FATAL) << "cannot convert argument from UTF-16 to UTF-8";
Spencer Lowd21dc822015-11-12 15:20:15 -08002227 }
2228 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002229 }
2230 narrow_args[argc] = nullptr; // terminate
2231}
2232
2233NarrowArgs::~NarrowArgs() {
2234 if (narrow_args != nullptr) {
2235 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2236 free(*argp);
2237 }
2238 delete[] narrow_args;
2239 narrow_args = nullptr;
2240 }
2241}
2242
Josh Gao0f29cbc2018-12-12 16:12:28 -08002243int unix_open(std::string_view path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002244 std::wstring path_wide;
Josh Gao0f29cbc2018-12-12 16:12:28 -08002245 if (!android::base::UTF8ToWide(path.data(), path.size(), &path_wide)) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002246 return -1;
2247 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002248 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002249 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002250 } else {
Josh Gao0f29cbc2018-12-12 16:12:28 -08002251 int mode;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002252 va_list args;
2253 va_start(args, options);
2254 mode = va_arg(args, int);
2255 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002256 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002257 }
2258}
2259
Spencer Lowcf4ff642015-05-11 01:08:48 -07002260// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002261DIR* adb_opendir(const char* path) {
2262 std::wstring path_wide;
2263 if (!android::base::UTF8ToWide(path, &path_wide)) {
2264 return nullptr;
2265 }
2266
Spencer Lowcf4ff642015-05-11 01:08:48 -07002267 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2268 // the fields, but right now all the callers treat the structure as
2269 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002270 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002271}
2272
2273// Version of readdir() that returns UTF-8 paths.
2274struct dirent* adb_readdir(DIR* dir) {
2275 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2276 struct _wdirent* const went = _wreaddir(wdir);
2277 if (went == nullptr) {
2278 return nullptr;
2279 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002280
Spencer Lowcf4ff642015-05-11 01:08:48 -07002281 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002282 std::string name_utf8;
2283 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2284 return nullptr;
2285 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002286
2287 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2288 // space for UTF-16 wchar_t's) with UTF-8 char's.
2289 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2290
2291 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2292 // Name too big to fit in existing buffer.
2293 errno = ENOMEM;
2294 return nullptr;
2295 }
2296
2297 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2298 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2299 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2300 // bigger than the caller expects because they expect a dirent structure
2301 // which has a smaller d_name field. Ignore this since the caller should be
2302 // resilient.
2303
2304 // Rewrite the UTF-16 d_name field to UTF-8.
2305 strcpy(ent->d_name, name_utf8.c_str());
2306
2307 return ent;
2308}
2309
2310// Version of closedir() to go with our version of adb_opendir().
2311int adb_closedir(DIR* dir) {
2312 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2313}
2314
2315// Version of unlink() that takes a UTF-8 path.
2316int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002317 std::wstring wpath;
2318 if (!android::base::UTF8ToWide(path, &wpath)) {
2319 return -1;
2320 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002321
2322 int rc = _wunlink(wpath.c_str());
2323
2324 if (rc == -1 && errno == EACCES) {
2325 /* unlink returns EACCES when the file is read-only, so we first */
2326 /* try to make it writable, then unlink again... */
2327 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2328 if (rc == 0)
2329 rc = _wunlink(wpath.c_str());
2330 }
2331 return rc;
2332}
2333
2334// Version of mkdir() that takes a UTF-8 path.
2335int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002336 std::wstring path_wide;
2337 if (!android::base::UTF8ToWide(path, &path_wide)) {
2338 return -1;
2339 }
2340
2341 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002342}
2343
2344// Version of utime() that takes a UTF-8 path.
2345int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002346 std::wstring path_wide;
2347 if (!android::base::UTF8ToWide(path, &path_wide)) {
2348 return -1;
2349 }
2350
Spencer Lowcf4ff642015-05-11 01:08:48 -07002351 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2352 "utimbuf and _utimbuf should be the same size because they both "
2353 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002354 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002355}
2356
2357// Version of chmod() that takes a UTF-8 path.
2358int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002359 std::wstring path_wide;
2360 if (!android::base::UTF8ToWide(path, &path_wide)) {
2361 return -1;
2362 }
2363
2364 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002365}
2366
Spencer Lowa30b79a2015-11-15 16:29:36 -08002367// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2368static inline size_t utf8_codepoint_len(uint8_t ch) {
2369 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2370}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002371
Spencer Lowa30b79a2015-11-15 16:29:36 -08002372namespace internal {
2373
2374// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2375// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2376// remaining_bytes.
2377size_t ParseCompleteUTF8(const char* const first, const char* const last,
2378 std::vector<char>* const remaining_bytes) {
2379 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2380 // Current_after points one byte past the current byte to be examined.
2381 for (const char* current_after = last; current_after != first; --current_after) {
2382 const char* const current = current_after - 1;
2383 const char ch = *current;
2384 const char kHighBit = 0x80u;
2385 const char kTwoHighestBits = 0xC0u;
2386 if ((ch & kHighBit) == 0) { // high bit not set
2387 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2388 // bytes with no leading byte, so return the entire buffer.
2389 break;
2390 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2391 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2392 const size_t bytes_available = last - current;
2393 if (bytes_available < utf8_codepoint_len(ch)) {
2394 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2395 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2396 // to remaining_bytes.
2397 remaining_bytes->insert(remaining_bytes->end(), current, last);
2398 return current - first;
2399 } else {
2400 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2401 // trailing bytes with no lead byte, so return the entire buffer.
2402 break;
2403 }
2404 } else {
2405 // Trailing byte, so keep going backwards looking for the lead byte.
2406 }
2407 }
2408
2409 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2410 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2411 // so that they can be processed.
2412 return last - first;
2413}
2414
2415}
2416
2417// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2418// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2419// This matches the behavior of Linux.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002420
2421// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2422static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2423 HANDLE console) {
Josh Gao0cd3ae12016-09-21 12:37:10 -07002424 static std::mutex& console_output_buffer_lock = *new std::mutex();
2425 static auto& console_output_buffer = *new std::vector<char>();
2426
Spencer Lowa30b79a2015-11-15 16:29:36 -08002427 const int saved_errno = errno;
2428 std::vector<char> combined_buffer;
2429
2430 // Complete UTF-8 sequences that should be immediately written to the console.
2431 const char* utf8;
2432 size_t utf8_size;
2433
Josh Gao0cd3ae12016-09-21 12:37:10 -07002434 {
2435 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2436 if (console_output_buffer.empty()) {
2437 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2438 // common case with plain ASCII), parse buf directly.
2439 utf8 = buf;
2440 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2441 } else {
2442 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2443 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2444 // combined_buffer, then parse it all together.
2445 combined_buffer.swap(console_output_buffer);
2446 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002447
Josh Gao0cd3ae12016-09-21 12:37:10 -07002448 utf8 = combined_buffer.data();
2449 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2450 &console_output_buffer);
2451 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002452 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002453
2454 std::wstring utf16;
2455
2456 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2457 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2458 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002459 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002460 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002461
2462 // Note that this does not do \n => \r\n translation because that
2463 // doesn't seem necessary for the Windows console. For the Windows
2464 // console \r moves to the beginning of the line and \n moves to a new
2465 // line.
2466
2467 // Flush any stream buffering so that our output is afterwards which
2468 // makes sense because our call is afterwards.
2469 (void)fflush(stream);
2470
2471 // Write UTF-16 to the console.
2472 DWORD written = 0;
Yi Kongaed415c2018-07-13 18:15:16 -07002473 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002474 errno = EIO;
2475 return -1;
2476 }
2477
Spencer Lowa30b79a2015-11-15 16:29:36 -08002478 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2479 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2480 // matches the Linux behavior.
2481 errno = saved_errno;
2482 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002483}
2484
2485// Function prototype because attributes cannot be placed on func definitions.
Elliott Hughesd8a4c602018-06-26 13:06:15 -07002486static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap)
2487 __attribute__((__format__(__printf__, 3, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002488
2489// Internal function to format a UTF-8 string and write it to a Win32 console.
2490// Returns -1 on error.
2491static int _console_vfprintf(const HANDLE console, FILE* stream,
2492 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002493 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002494 std::string output_utf8;
2495
2496 // Format the string.
2497 // This could throw std::bad_alloc.
2498 android::base::StringAppendV(&output_utf8, format, ap);
2499
Spencer Lowa30b79a2015-11-15 16:29:36 -08002500 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2501 console);
2502 if (result != -1) {
2503 errno = saved_errno;
2504 } else {
2505 // If -1 was returned, errno has been set.
2506 }
2507 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002508}
2509
2510// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2511// Windows console.
2512int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2513 const HANDLE console = _get_console_handle(stream);
2514
2515 // If there is an associated Win32 console, write to it specially,
2516 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002517 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002518 return _console_vfprintf(console, stream, format, ap);
2519 } else {
2520 // If vfprintf is a macro, undefine it, so we can call the real
2521 // C Runtime API.
2522#pragma push_macro("vfprintf")
2523#undef vfprintf
2524 return vfprintf(stream, format, ap);
2525#pragma pop_macro("vfprintf")
2526 }
2527}
2528
Spencer Lowa30b79a2015-11-15 16:29:36 -08002529// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2530int adb_vprintf(const char *format, va_list ap) {
2531 return adb_vfprintf(stdout, format, ap);
2532}
2533
Spencer Lowcf4ff642015-05-11 01:08:48 -07002534// Version of fprintf() that takes UTF-8 and can write Unicode to a
2535// Windows console.
2536int adb_fprintf(FILE *stream, const char *format, ...) {
2537 va_list ap;
2538 va_start(ap, format);
2539 const int result = adb_vfprintf(stream, format, ap);
2540 va_end(ap);
2541
2542 return result;
2543}
2544
2545// Version of printf() that takes UTF-8 and can write Unicode to a
2546// Windows console.
2547int adb_printf(const char *format, ...) {
2548 va_list ap;
2549 va_start(ap, format);
2550 const int result = adb_vfprintf(stdout, format, ap);
2551 va_end(ap);
2552
2553 return result;
2554}
2555
2556// Version of fputs() that takes UTF-8 and can write Unicode to a
2557// Windows console.
2558int adb_fputs(const char* buf, FILE* stream) {
2559 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2560 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002561 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002562 return adb_fprintf(stream, "%s", buf);
2563}
2564
2565// Version of fputc() that takes UTF-8 and can write Unicode to a
2566// Windows console.
2567int adb_fputc(int ch, FILE* stream) {
2568 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002569 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002570 return EOF;
2571 }
2572 // For success, fputc returns the char, cast to unsigned char, then to int.
2573 return static_cast<unsigned char>(ch);
2574}
2575
Spencer Lowa30b79a2015-11-15 16:29:36 -08002576// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2577int adb_putchar(int ch) {
2578 return adb_fputc(ch, stdout);
2579}
2580
2581// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2582int adb_puts(const char* buf) {
2583 // adb_printf returns -1 on error, which is conveniently the same as EOF
2584 // which puts (and hence adb_puts) should return on error.
2585 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2586 return adb_printf("%s\n", buf);
2587}
2588
Spencer Lowcf4ff642015-05-11 01:08:48 -07002589// Internal function to write UTF-8 to a Win32 console. Returns the number of
2590// items (of length size) written. On error, returns a short item count or 0.
2591static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2592 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002593 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2594 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002595 if (result == -1) {
2596 return 0;
2597 }
2598 return result / size;
2599}
2600
2601// Version of fwrite() that takes UTF-8 and can write Unicode to a
2602// Windows console.
2603size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2604 const HANDLE console = _get_console_handle(stream);
2605
2606 // If there is an associated Win32 console, write to it specially,
2607 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002608 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002609 return _console_fwrite(ptr, size, nmemb, stream, console);
2610 } else {
2611 // If fwrite is a macro, undefine it, so we can call the real
2612 // C Runtime API.
2613#pragma push_macro("fwrite")
2614#undef fwrite
2615 return fwrite(ptr, size, nmemb, stream);
2616#pragma pop_macro("fwrite")
2617 }
2618}
2619
2620// Version of fopen() that takes a UTF-8 filename and can access a file with
2621// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002622FILE* adb_fopen(const char* path, const char* mode) {
2623 std::wstring path_wide;
2624 if (!android::base::UTF8ToWide(path, &path_wide)) {
2625 return nullptr;
2626 }
2627
2628 std::wstring mode_wide;
2629 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2630 return nullptr;
2631 }
2632
2633 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002634}
2635
Spencer Lowe6ae5732015-09-08 17:13:04 -07002636// Return a lowercase version of the argument. Uses C Runtime tolower() on
2637// each byte which is not UTF-8 aware, and theoretically uses the current C
2638// Runtime locale (which in practice is not changed, so this becomes a ASCII
2639// conversion).
2640static std::string ToLower(const std::string& anycase) {
2641 // copy string
2642 std::string str(anycase);
2643 // transform the copy
2644 std::transform(str.begin(), str.end(), str.begin(), tolower);
2645 return str;
2646}
2647
2648extern "C" int main(int argc, char** argv);
2649
2650// Link with -municode to cause this wmain() to be used as the program
2651// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2652// regular main() with UTF-8 args.
2653extern "C" int wmain(int argc, wchar_t **argv) {
2654 // Convert args from UTF-16 to UTF-8 and pass that to main().
2655 NarrowArgs narrow_args(argc, argv);
Josh Gaoe72c44b2019-06-10 12:48:34 -07002656
2657 // Avoid destructing NarrowArgs: argv might have been mutated to point to string literals.
2658 _exit(main(argc, narrow_args.data()));
Spencer Lowe6ae5732015-09-08 17:13:04 -07002659}
2660
Spencer Lowcf4ff642015-05-11 01:08:48 -07002661// Shadow UTF-8 environment variable name/value pairs that are created from
Spencer Low14022c22018-08-10 16:20:57 -07002662// _wenviron by _init_env(). Note that this is not currently updated if putenv, setenv, unsetenv are
2663// called. Note that no thread synchronization is done, but we're called early enough in
Spencer Lowe347c1d2015-08-02 18:13:54 -07002664// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002665static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002666
Spencer Low14022c22018-08-10 16:20:57 -07002667// Setup shadow UTF-8 environment variables.
2668static void _init_env() {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002669 // If some name/value pairs exist, then we've already done the setup below.
2670 if (g_environ_utf8.size() != 0) {
2671 return;
2672 }
2673
Spencer Lowe6ae5732015-09-08 17:13:04 -07002674 if (_wenviron == nullptr) {
2675 // If _wenviron is null, then -municode probably wasn't used. That
2676 // linker flag will cause the entry point to setup _wenviron. It will
2677 // also require an implementation of wmain() (which we provide above).
Elliott Hughes4679a392018-10-19 13:59:44 -07002678 LOG(FATAL) << "_wenviron is not set, did you link with -municode?";
Spencer Lowe6ae5732015-09-08 17:13:04 -07002679 }
2680
Spencer Lowcf4ff642015-05-11 01:08:48 -07002681 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2682 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2683 // to use the D() macro here because that tracing only works if the
2684 // ADB_TRACE environment variable is setup, but that env var can't be read
2685 // until this code completes.
2686 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2687 wchar_t* const equal = wcschr(*env, L'=');
2688 if (equal == nullptr) {
2689 // Malformed environment variable with no equal sign. Shouldn't
2690 // really happen, but we should be resilient to this.
2691 continue;
2692 }
2693
Spencer Lowd21dc822015-11-12 15:20:15 -08002694 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2695 // var because the program might never even read this particular variable.
2696 std::string name_utf8;
2697 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2698 continue;
2699 }
2700
Spencer Lowe6ae5732015-09-08 17:13:04 -07002701 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002702 name_utf8 = ToLower(name_utf8);
2703
2704 std::string value_utf8;
2705 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2706 continue;
2707 }
2708
2709 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002710
Spencer Lowe6ae5732015-09-08 17:13:04 -07002711 // Don't overwrite a previus env var with the same name. In reality,
2712 // the system probably won't let two env vars with the same name exist
2713 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002714 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002715 }
2716}
2717
2718// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002719// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002720char* adb_getenv(const char* name) {
Spencer Lowe6ae5732015-09-08 17:13:04 -07002721 // Case-insensitive search by searching for lowercase name in a map of
2722 // lowercase names.
2723 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002724 if (it == g_environ_utf8.end()) {
2725 return nullptr;
2726 }
2727
2728 return it->second;
2729}
2730
2731// Version of getcwd() that returns the current working directory in UTF-8.
2732char* adb_getcwd(char* buf, int size) {
2733 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2734 if (wbuf == nullptr) {
2735 return nullptr;
2736 }
2737
Spencer Lowd21dc822015-11-12 15:20:15 -08002738 std::string buf_utf8;
2739 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002740 free(wbuf);
2741 wbuf = nullptr;
2742
Spencer Lowd21dc822015-11-12 15:20:15 -08002743 if (!narrow_result) {
2744 return nullptr;
2745 }
2746
Spencer Lowcf4ff642015-05-11 01:08:48 -07002747 // If size was specified, make sure all the chars will fit.
2748 if (size != 0) {
2749 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2750 errno = ERANGE;
2751 return nullptr;
2752 }
2753 }
2754
2755 // If buf was not specified, allocate storage.
2756 if (buf == nullptr) {
2757 if (size == 0) {
2758 size = buf_utf8.length() + 1;
2759 }
2760 buf = reinterpret_cast<char*>(malloc(size));
2761 if (buf == nullptr) {
2762 return nullptr;
2763 }
2764 }
2765
2766 // Destination buffer was allocated with enough space, or we've already
2767 // checked an existing buffer size for enough space.
2768 strcpy(buf, buf_utf8.c_str());
2769
2770 return buf;
2771}
Spencer Low50beee32018-09-03 16:03:22 -07002772
2773// The SetThreadDescription API was brought in version 1607 of Windows 10.
2774typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);
2775
2776// Based on PlatformThread::SetName() from
2777// https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc
2778int adb_thread_setname(const std::string& name) {
2779 // The SetThreadDescription API works even if no debugger is attached.
2780 auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(
2781 ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
2782 if (set_thread_description_func) {
2783 std::wstring name_wide;
2784 if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) {
2785 return errno;
2786 }
2787 set_thread_description_func(::GetCurrentThread(), name_wide.c_str());
2788 }
2789
2790 // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions.
2791 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017
2792
2793 return 0;
2794}
Spencer Low14022c22018-08-10 16:20:57 -07002795
2796#if !defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2797#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
2798#endif
2799
2800#if !defined(DISABLE_NEWLINE_AUTO_RETURN)
2801#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
2802#endif
2803
2804static void _init_console() {
2805 DWORD old_out_console_mode;
2806
2807 const HANDLE out = _get_console_handle(STDOUT_FILENO, &old_out_console_mode);
2808 if (out == nullptr) {
2809 return;
2810 }
2811
2812 // Try to use ENABLE_VIRTUAL_TERMINAL_PROCESSING on the output console to process virtual
2813 // terminal sequences on newer versions of Windows 10 and later.
2814 // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
2815 // On older OSes that don't support the flag, SetConsoleMode() will return an error.
2816 // ENABLE_VIRTUAL_TERMINAL_PROCESSING also solves a problem where the last column of the
2817 // console cannot be overwritten.
2818 //
2819 // Note that we don't use DISABLE_NEWLINE_AUTO_RETURN because it doesn't seem to be necessary.
2820 // If we use DISABLE_NEWLINE_AUTO_RETURN, _console_write_utf8() would need to be modified to
2821 // translate \n to \r\n.
2822 if (!SetConsoleMode(out, old_out_console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
2823 return;
2824 }
2825
2826 // If SetConsoleMode() succeeded, the console supports virtual terminal processing, so we
2827 // should set the TERM env var to match so that it will be propagated to adbd on devices.
2828 //
2829 // Below's direct manipulation of env vars and not g_environ_utf8 assumes that _init_env() has
2830 // not yet been called. If this fails, _init_env() should be called after _init_console().
2831 if (g_environ_utf8.size() > 0) {
2832 LOG(FATAL) << "environment variables have already been converted to UTF-8";
2833 }
2834
2835#pragma push_macro("getenv")
2836#undef getenv
2837#pragma push_macro("putenv")
2838#undef putenv
2839 if (getenv("TERM") == nullptr) {
2840 // This is the same TERM value used by Gnome Terminal and the version of ssh included with
2841 // Windows.
2842 putenv("TERM=xterm-256color");
2843 }
2844#pragma pop_macro("putenv")
2845#pragma pop_macro("getenv")
2846}
2847
2848static bool _init_sysdeps() {
2849 // _init_console() depends on _init_env() not being called yet.
2850 _init_console();
2851 _init_env();
2852 _init_winsock();
2853 return true;
2854}
2855
2856static bool _sysdeps_init = _init_sysdeps();