blob: 8a6541d60cf216812eb2acecfcccda3a708281a5 [file] [log] [blame]
Dan Albert33134262015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070030#include <mutex>
Spencer Low5200c662015-07-30 23:07:55 -070031#include <string>
Spencer Lowcf4ff642015-05-11 01:08:48 -070032#include <unordered_map>
Josh Gao3777d2e2016-02-16 17:34:53 -080033#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070034
Elliott Hughesd48dbd82015-07-24 11:35:40 -070035#include <cutils/sockets.h>
36
David Pursell5f787ed2016-01-27 08:52:53 -080037#include <android-base/errors.h>
Elliott Hughes4679a392018-10-19 13:59:44 -070038#include <android-base/file.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080039#include <android-base/logging.h>
Josh Gao116aa0a2018-04-05 17:55:25 -070040#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080041#include <android-base/stringprintf.h>
42#include <android-base/strings.h>
43#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070044
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080045#include "adb.h"
Josh Gao3777d2e2016-02-16 17:34:53 -080046#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047
Josh Gao116aa0a2018-04-05 17:55:25 -070048#include "sysdeps/uio.h"
49
Elliott Hughesa2f2e562015-04-16 16:47:02 -070050/* forward declarations */
51
52typedef const struct FHClassRec_* FHClass;
53typedef struct FHRec_* FH;
Elliott Hughesa2f2e562015-04-16 16:47:02 -070054
55typedef struct FHClassRec_ {
56 void (*_fh_init)(FH);
57 int (*_fh_close)(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070058 int64_t (*_fh_lseek)(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070059 int (*_fh_read)(FH, void*, int);
60 int (*_fh_write)(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070061 int (*_fh_writev)(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070062} FHClassRec;
63
64static void _fh_file_init(FH);
65static int _fh_file_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070066static int64_t _fh_file_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070067static int _fh_file_read(FH, void*, int);
68static int _fh_file_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070069static int _fh_file_writev(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070070
71static const FHClassRec _fh_file_class = {
72 _fh_file_init,
73 _fh_file_close,
74 _fh_file_lseek,
75 _fh_file_read,
76 _fh_file_write,
Josh Gao116aa0a2018-04-05 17:55:25 -070077 _fh_file_writev,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070078};
79
80static void _fh_socket_init(FH);
81static int _fh_socket_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070082static int64_t _fh_socket_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070083static int _fh_socket_read(FH, void*, int);
84static int _fh_socket_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070085static int _fh_socket_writev(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070086
87static const FHClassRec _fh_socket_class = {
88 _fh_socket_init,
89 _fh_socket_close,
90 _fh_socket_lseek,
91 _fh_socket_read,
92 _fh_socket_write,
Josh Gao116aa0a2018-04-05 17:55:25 -070093 _fh_socket_writev,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070094};
95
Pirama Arumuga Nainar29e3dd82018-08-08 10:33:24 -070096#if defined(assert)
97#undef assert
98#endif
99
Spencer Low2122c7a2015-08-26 18:46:09 -0700100void handle_deleter::operator()(HANDLE h) {
101 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
102 // implying that NULL is a valid handle, but this is probably impossible.
103 // Other APIs like CreateEvent() are documented to return NULL on error,
104 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
105 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
106 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
107 // only need to check for INVALID_HANDLE_VALUE.
108 if (h != INVALID_HANDLE_VALUE) {
109 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700110 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800111 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700112 }
113 }
114}
115
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800116/**************************************************************************/
117/**************************************************************************/
118/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800119/***** common file descriptor handling *****/
120/***** *****/
121/**************************************************************************/
122/**************************************************************************/
123
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800124typedef struct FHRec_
125{
126 FHClass clazz;
127 int used;
128 int eof;
129 union {
130 HANDLE handle;
131 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800132 } u;
133
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800134 char name[32];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800135} FHRec;
136
137#define fh_handle u.handle
138#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800139
Josh Gaob6232b92016-02-17 16:45:39 -0800140#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700141#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800142
Josh Gao0cd3ae12016-09-21 12:37:10 -0700143static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800144static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700145static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800146
147static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700148_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149{
150 FH f;
151
152 fd -= WIN32_FH_BASE;
153
Spencer Lowc3211552015-07-24 15:38:19 -0700154 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700155 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700156 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800157 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700158 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800159 }
160
161 f = &_win32_fhs[fd];
162
163 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700164 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700165 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800166 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700167 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800168 }
169
170 return f;
171}
172
173
174static int
175_fh_to_int( FH f )
176{
177 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
178 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
179
180 return -1;
181}
182
183static FH
184_fh_alloc( FHClass clazz )
185{
Yi Kongaed415c2018-07-13 18:15:16 -0700186 FH f = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800187
Josh Gao0cd3ae12016-09-21 12:37:10 -0700188 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189
Josh Gaob6232b92016-02-17 16:45:39 -0800190 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
Yi Kongaed415c2018-07-13 18:15:16 -0700191 if (_win32_fhs[i].clazz == nullptr) {
Josh Gaob6232b92016-02-17 16:45:39 -0800192 f = &_win32_fhs[i];
193 _win32_fh_next = i + 1;
Josh Gao0cd3ae12016-09-21 12:37:10 -0700194 f->clazz = clazz;
195 f->used = 1;
196 f->eof = 0;
197 f->name[0] = '\0';
198 clazz->_fh_init(f);
199 return f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800200 }
201 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700202
203 D("_fh_alloc: no more free file descriptors");
204 errno = EMFILE; // Too many open files
205 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800206}
207
208
209static int
210_fh_close( FH f )
211{
Spencer Lowc3211552015-07-24 15:38:19 -0700212 // Use lock so that closing only happens once and so that _fh_alloc can't
213 // allocate a FH that we're in the middle of closing.
Josh Gao0cd3ae12016-09-21 12:37:10 -0700214 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800215
216 int offset = f - _win32_fhs;
217 if (_win32_fh_next > offset) {
218 _win32_fh_next = offset;
219 }
220
Spencer Lowc3211552015-07-24 15:38:19 -0700221 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800222 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700223 f->name[0] = '\0';
224 f->eof = 0;
225 f->used = 0;
Yi Kongaed415c2018-07-13 18:15:16 -0700226 f->clazz = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800227 }
228 return 0;
229}
230
Spencer Low5200c662015-07-30 23:07:55 -0700231// Deleter for unique_fh.
232class fh_deleter {
233 public:
234 void operator()(struct FHRec_* fh) {
235 // We're called from a destructor and destructors should not overwrite
236 // errno because callers may do:
237 // errno = EBLAH;
238 // return -1; // calls destructor, which should not overwrite errno
239 const int saved_errno = errno;
240 _fh_close(fh);
241 errno = saved_errno;
242 }
243};
244
245// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
246typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
247
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800248/**************************************************************************/
249/**************************************************************************/
250/***** *****/
251/***** file-based descriptor handling *****/
252/***** *****/
253/**************************************************************************/
254/**************************************************************************/
255
Josh Gao116aa0a2018-04-05 17:55:25 -0700256static void _fh_file_init(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800257 f->fh_handle = INVALID_HANDLE_VALUE;
258}
259
Josh Gao116aa0a2018-04-05 17:55:25 -0700260static int _fh_file_close(FH f) {
261 CloseHandle(f->fh_handle);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800262 f->fh_handle = INVALID_HANDLE_VALUE;
263 return 0;
264}
265
Josh Gao116aa0a2018-04-05 17:55:25 -0700266static int _fh_file_read(FH f, void* buf, int len) {
267 DWORD read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800268
Yi Kongaed415c2018-07-13 18:15:16 -0700269 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700270 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800271 errno = EIO;
272 return -1;
273 } else if (read_bytes < (DWORD)len) {
274 f->eof = 1;
275 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700276 return read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800277}
278
Josh Gao116aa0a2018-04-05 17:55:25 -0700279static int _fh_file_write(FH f, const void* buf, int len) {
280 DWORD wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281
Yi Kongaed415c2018-07-13 18:15:16 -0700282 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700283 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800284 errno = EIO;
285 return -1;
286 } else if (wrote_bytes < (DWORD)len) {
287 f->eof = 1;
288 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700289 return wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800290}
291
Josh Gao116aa0a2018-04-05 17:55:25 -0700292static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
293 if (iovcnt <= 0) {
294 errno = EINVAL;
295 return -1;
296 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800297
Josh Gao116aa0a2018-04-05 17:55:25 -0700298 DWORD wrote_bytes = 0;
299
300 for (int i = 0; i < iovcnt; ++i) {
301 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
302 if (rc == -1) {
303 return wrote_bytes > 0 ? wrote_bytes : -1;
304 } else if (rc == 0) {
305 return wrote_bytes;
306 }
307
308 wrote_bytes += rc;
309
310 if (static_cast<size_t>(rc) < iov[i].iov_len) {
311 return wrote_bytes;
312 }
313 }
314
315 return wrote_bytes;
316}
317
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700318static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700319 DWORD method;
Josh Gao116aa0a2018-04-05 17:55:25 -0700320 switch (origin) {
321 case SEEK_SET:
322 method = FILE_BEGIN;
323 break;
324 case SEEK_CUR:
325 method = FILE_CURRENT;
326 break;
327 case SEEK_END:
328 method = FILE_END;
329 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800330 default:
331 errno = EINVAL;
332 return -1;
333 }
334
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700335 LARGE_INTEGER li = {.QuadPart = pos};
336 if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800337 errno = EIO;
338 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800339 }
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700340 f->eof = 0;
341 return li.QuadPart;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800342}
343
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800344/**************************************************************************/
345/**************************************************************************/
346/***** *****/
347/***** file-based descriptor handling *****/
348/***** *****/
349/**************************************************************************/
350/**************************************************************************/
351
Josh Gao64a63ac2018-04-05 18:09:02 -0700352int adb_open(const char* path, int options) {
353 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800354
Josh Gao64a63ac2018-04-05 18:09:02 -0700355 DWORD desiredAccess = 0;
356 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800357
358 switch (options) {
359 case O_RDONLY:
360 desiredAccess = GENERIC_READ;
361 break;
362 case O_WRONLY:
363 desiredAccess = GENERIC_WRITE;
364 break;
365 case O_RDWR:
366 desiredAccess = GENERIC_READ | GENERIC_WRITE;
367 break;
368 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700369 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800370 errno = EINVAL;
371 return -1;
372 }
373
Josh Gao64a63ac2018-04-05 18:09:02 -0700374 f = _fh_alloc(&_fh_file_class);
375 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800376 return -1;
377 }
378
Spencer Lowd21dc822015-11-12 15:20:15 -0800379 std::wstring path_wide;
380 if (!android::base::UTF8ToWide(path, &path_wide)) {
381 return -1;
382 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700383 f->fh_handle =
Yi Kongaed415c2018-07-13 18:15:16 -0700384 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800385
Josh Gao64a63ac2018-04-05 18:09:02 -0700386 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700387 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800388 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700389 D("adb_open: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700390 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700392 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800393 errno = ENOENT;
394 return -1;
395
396 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700397 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800398 errno = ENOTDIR;
399 return -1;
400
401 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800402 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800403 errno = ENOENT;
404 return -1;
405 }
406 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800407
Josh Gao64a63ac2018-04-05 18:09:02 -0700408 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
409 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800410 return _fh_to_int(f);
411}
412
413/* ignore mode on Win32 */
Josh Gao64a63ac2018-04-05 18:09:02 -0700414int adb_creat(const char* path, int mode) {
415 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800416
Josh Gao64a63ac2018-04-05 18:09:02 -0700417 f = _fh_alloc(&_fh_file_class);
418 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419 return -1;
420 }
421
Spencer Lowd21dc822015-11-12 15:20:15 -0800422 std::wstring path_wide;
423 if (!android::base::UTF8ToWide(path, &path_wide)) {
424 return -1;
425 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700426 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
Yi Kongaed415c2018-07-13 18:15:16 -0700427 nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800428
Josh Gao64a63ac2018-04-05 18:09:02 -0700429 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700430 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800431 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700432 D("adb_creat: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700433 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700435 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800436 errno = ENOENT;
437 return -1;
438
439 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700440 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800441 errno = ENOTDIR;
442 return -1;
443
444 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800445 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446 errno = ENOENT;
447 return -1;
448 }
449 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700450 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
451 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452 return _fh_to_int(f);
453}
454
Josh Gao116aa0a2018-04-05 17:55:25 -0700455int adb_read(int fd, void* buf, int len) {
456 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800457
Yi Kongaed415c2018-07-13 18:15:16 -0700458 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700459 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460 return -1;
461 }
462
Josh Gao116aa0a2018-04-05 17:55:25 -0700463 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464}
465
Josh Gao116aa0a2018-04-05 17:55:25 -0700466int adb_write(int fd, const void* buf, int len) {
467 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800468
Yi Kongaed415c2018-07-13 18:15:16 -0700469 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700470 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800471 return -1;
472 }
473
474 return f->clazz->_fh_write(f, buf, len);
475}
476
Josh Gao116aa0a2018-04-05 17:55:25 -0700477ssize_t adb_writev(int fd, const adb_iovec* iov, int iovcnt) {
478 FH f = _fh_from_int(fd, __func__);
479
Yi Kongaed415c2018-07-13 18:15:16 -0700480 if (f == nullptr) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700481 errno = EBADF;
482 return -1;
483 }
484
485 return f->clazz->_fh_writev(f, iov, iovcnt);
486}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700488int64_t adb_lseek(int fd, int64_t pos, int where) {
Josh Gao64a63ac2018-04-05 18:09:02 -0700489 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800490 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700491 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492 return -1;
493 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800494 return f->clazz->_fh_lseek(f, pos, where);
495}
496
Josh Gao64a63ac2018-04-05 18:09:02 -0700497int adb_close(int fd) {
498 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800499
500 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700501 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800502 return -1;
503 }
504
Josh Gao64a63ac2018-04-05 18:09:02 -0700505 D("adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800506 _fh_close(f);
507 return 0;
508}
509
510/**************************************************************************/
511/**************************************************************************/
512/***** *****/
513/***** socket-based file descriptors *****/
514/***** *****/
515/**************************************************************************/
516/**************************************************************************/
517
Spencer Lowf055c192015-01-25 14:40:16 -0800518#undef setsockopt
519
Spencer Low5200c662015-07-30 23:07:55 -0700520static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700521 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
522 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gaoa3577e12016-12-05 13:24:48 -0800523 // are mapped to strings by adb_strerror().
Spencer Low5200c662015-07-30 23:07:55 -0700524 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800525 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700526 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
527 // case WSAEINTR: errno = EINTR; break;
528 case WSAEFAULT: errno = EFAULT; break;
529 case WSAEINVAL: errno = EINVAL; break;
530 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700531 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
532 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
533 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800534 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700535 case WSAENOTSOCK: errno = ENOTSOCK; break;
536 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
537 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
538 case WSAENETDOWN: errno = ENETDOWN; break;
539 case WSAENETRESET: errno = ENETRESET; break;
540 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
541 // to use EPIPE for these situations and there are some callers that look
542 // for EPIPE.
543 case WSAECONNABORTED: errno = EPIPE; break;
544 case WSAECONNRESET: errno = ECONNRESET; break;
545 case WSAENOBUFS: errno = ENOBUFS; break;
546 case WSAENOTCONN: errno = ENOTCONN; break;
547 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
548 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
549 // considerations: Reportedly send() can return zero on timeout, and POSIX
550 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
551 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
552 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800553 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700555 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700556 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557 }
558}
559
Josh Gao3777d2e2016-02-16 17:34:53 -0800560extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
561 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
562 int skipped = 0;
563 std::vector<WSAPOLLFD> sockets;
564 std::vector<adb_pollfd*> original;
Josh Gao05fb45b2018-03-29 12:34:28 -0700565
Josh Gao3777d2e2016-02-16 17:34:53 -0800566 for (size_t i = 0; i < nfds; ++i) {
567 FH fh = _fh_from_int(fds[i].fd, __func__);
568 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
569 D("adb_poll received bad FD %d", fds[i].fd);
570 fds[i].revents = POLLNVAL;
571 ++skipped;
572 } else {
573 WSAPOLLFD wsapollfd = {
574 .fd = fh->u.socket,
575 .events = static_cast<short>(fds[i].events)
576 };
577 sockets.push_back(wsapollfd);
578 original.push_back(&fds[i]);
579 }
Spencer Low5200c662015-07-30 23:07:55 -0700580 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800581
582 if (sockets.empty()) {
583 return skipped;
584 }
585
Josh Gao05fb45b2018-03-29 12:34:28 -0700586 // If we have any invalid FDs in our FD set, make sure to return immediately.
587 if (skipped > 0) {
588 timeout = 0;
589 }
590
Josh Gao3777d2e2016-02-16 17:34:53 -0800591 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
592 if (result == SOCKET_ERROR) {
593 _socket_set_errno(WSAGetLastError());
594 return -1;
595 }
596
597 // Map the results back onto the original set.
598 for (size_t i = 0; i < sockets.size(); ++i) {
599 original[i]->revents = sockets[i].revents;
600 }
601
Josh Gao05fb45b2018-03-29 12:34:28 -0700602 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gao3777d2e2016-02-16 17:34:53 -0800603 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
604 // to do. Ignore its result and calculate the proper return value.
605 result = 0;
606 for (size_t i = 0; i < nfds; ++i) {
607 if (fds[i].revents != 0) {
608 ++result;
609 }
610 }
611 return result;
612}
613
614static void _fh_socket_init(FH f) {
615 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800616}
617
Josh Gao116aa0a2018-04-05 17:55:25 -0700618static int _fh_socket_close(FH f) {
Spencer Low5200c662015-07-30 23:07:55 -0700619 if (f->fh_socket != INVALID_SOCKET) {
620 /* gently tell any peer that we're closing the socket */
621 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
622 // If the socket is not connected, this returns an error. We want to
623 // minimize logging spam, so don't log these errors for now.
624#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700625 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800626 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700627#endif
628 }
629 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800630 // Don't set errno here, since adb_close will ignore it.
631 const DWORD err = WSAGetLastError();
632 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700633 }
634 f->fh_socket = INVALID_SOCKET;
635 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800636 return 0;
637}
638
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700639static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800640 errno = EPIPE;
641 return -1;
642}
643
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700644static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700645 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800646 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700647 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700648 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
649 // that to reduce spam and confusion.
650 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700651 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800652 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700653 }
Spencer Low5200c662015-07-30 23:07:55 -0700654 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800655 result = -1;
656 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700657 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658}
659
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700660static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700661 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800662 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700663 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700664 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
665 // that to reduce spam and confusion.
666 if (err != WSAEWOULDBLOCK) {
667 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800668 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700669 }
Spencer Low5200c662015-07-30 23:07:55 -0700670 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800671 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700672 } else {
673 // According to https://code.google.com/p/chromium/issues/detail?id=27870
674 // Winsock Layered Service Providers may cause this.
Josh Gao116aa0a2018-04-05 17:55:25 -0700675 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
676 << result << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677 }
678 return result;
679}
680
Josh Gao116aa0a2018-04-05 17:55:25 -0700681// Make sure that adb_iovec is compatible with WSABUF.
682static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
683static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
684static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
685
686static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
687static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
688
689static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
690 if (iovcnt <= 0) {
691 errno = EINVAL;
692 return -1;
693 }
694
695 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
696 DWORD bytes_written = 0;
697 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
698 if (result == SOCKET_ERROR) {
699 const DWORD err = WSAGetLastError();
700 // 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),
704 android::base::SystemErrorCodeToString(err).c_str());
705 }
706 _socket_set_errno(err);
707 result = -1;
708 }
709 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
710 return static_cast<int>(bytes_written);
711}
712
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800713/**************************************************************************/
714/**************************************************************************/
715/***** *****/
716/***** replacement for libs/cutils/socket_xxxx.c *****/
717/***** *****/
718/**************************************************************************/
719/**************************************************************************/
720
Josh Gao2e93df22018-04-05 18:10:03 -0700721static int _init_winsock(void) {
722 static std::once_flag once;
723 std::call_once(once, []() {
724 WSADATA wsaData;
725 int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800726 if (rc != 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700727 LOG(FATAL) << "could not initialize Winsock: "
728 << android::base::SystemErrorCodeToString(rc);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800729 }
Spencer Low87e97ee2015-08-12 18:19:16 -0700730
731 // Note that we do not call atexit() to register WSACleanup to be called
732 // at normal process termination because:
733 // 1) When exit() is called, there are still threads actively using
734 // Winsock because we don't cleanly shutdown all threads, so it
735 // doesn't make sense to call WSACleanup() and may cause problems
736 // with those threads.
737 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
738 // calls WSACleanup() which tries to unload a DLL, which tries to
739 // grab the LoaderLock. This conflicts with the device_poll_thread
740 // which holds the LoaderLock because AdbWinApi.dll calls
741 // setupapi.dll which tries to load wintrust.dll which tries to load
742 // crypt32.dll which calls atexit() which tries to acquire the C
743 // Runtime lock that the other thread holds.
Josh Gao2e93df22018-04-05 18:10:03 -0700744 });
745 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800746}
747
Josh Gao2e93df22018-04-05 18:10:03 -0700748static int _winsock_init = _init_winsock();
749
Spencer Low677fb432015-09-29 15:05:29 -0700750// Map a socket type to an explicit socket protocol instead of using the socket
751// protocol of 0. Explicit socket protocols are used by most apps and we should
752// do the same to reduce the chance of exercising uncommon code-paths that might
753// have problems or that might load different Winsock service providers that
754// have problems.
755static int GetSocketProtocolFromSocketType(int type) {
756 switch (type) {
757 case SOCK_STREAM:
758 return IPPROTO_TCP;
759 case SOCK_DGRAM:
760 return IPPROTO_UDP;
761 default:
762 LOG(FATAL) << "Unknown socket type: " << type;
763 return 0;
764 }
765}
766
Spencer Low5200c662015-07-30 23:07:55 -0700767int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800768 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800769 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800770
Josh Gao6487e742016-02-18 13:43:55 -0800771 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700772 if (!f) {
773 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800774 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700775 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800776
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800777 memset(&addr, 0, sizeof(addr));
778 addr.sin_family = AF_INET;
779 addr.sin_port = htons(port);
780 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
781
Spencer Low677fb432015-09-29 15:05:29 -0700782 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800783 if (s == INVALID_SOCKET) {
784 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700785 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800786 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700787 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800788 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700789 return -1;
790 }
791 f->fh_socket = s;
792
Josh Gao6487e742016-02-18 13:43:55 -0800793 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700794 // Save err just in case inet_ntoa() or ntohs() changes the last error.
795 const DWORD err = WSAGetLastError();
796 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800797 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
798 android::base::SystemErrorCodeToString(err).c_str());
799 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
800 error->c_str());
801 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800802 return -1;
803 }
804
Spencer Low5200c662015-07-30 23:07:55 -0700805 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800806 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
807 port);
808 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700809 f.release();
810 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800811}
812
Spencer Low5200c662015-07-30 23:07:55 -0700813// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800814static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800815 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800816 SOCKET s;
817 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800818
Josh Gao6487e742016-02-18 13:43:55 -0800819 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700821 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 return -1;
823 }
824
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800825 memset(&addr, 0, sizeof(addr));
826 addr.sin_family = AF_INET;
827 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700828 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800829
Spencer Low5200c662015-07-30 23:07:55 -0700830 // TODO: Consider using dual-stack socket that can simultaneously listen on
831 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700832 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700833 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800834 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700835 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800836 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700837 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800838 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700839 return -1;
840 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800841
842 f->fh_socket = s;
843
Spencer Lowbf7c6052015-08-11 16:45:32 -0700844 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
845 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800846 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800847 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
848 const DWORD err = WSAGetLastError();
849 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
850 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700851 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800852 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700853 return -1;
854 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800855
Josh Gao6487e742016-02-18 13:43:55 -0800856 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700857 // Save err just in case inet_ntoa() or ntohs() changes the last error.
858 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800859 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
860 ntohs(addr.sin_port),
861 android::base::SystemErrorCodeToString(err).c_str());
862 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
863 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800864 return -1;
865 }
866 if (type == SOCK_STREAM) {
Josh Gaobf243a62018-03-20 14:25:03 -0700867 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800868 const DWORD err = WSAGetLastError();
869 *error = android::base::StringPrintf(
870 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
871 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
872 error->c_str());
873 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800874 return -1;
875 }
876 }
Spencer Low5200c662015-07-30 23:07:55 -0700877 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800878 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
879 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
880 port);
881 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700882 f.release();
883 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800884}
885
Spencer Low5200c662015-07-30 23:07:55 -0700886int network_loopback_server(int port, int type, std::string* error) {
887 return _network_server(port, type, INADDR_LOOPBACK, error);
888}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800889
Spencer Low5200c662015-07-30 23:07:55 -0700890int network_inaddr_any_server(int port, int type, std::string* error) {
891 return _network_server(port, type, INADDR_ANY, error);
892}
893
894int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
895 unique_fh f(_fh_alloc(&_fh_socket_class));
896 if (!f) {
897 *error = strerror(errno);
898 return -1;
899 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800900
Spencer Low5200c662015-07-30 23:07:55 -0700901 struct addrinfo hints;
902 memset(&hints, 0, sizeof(hints));
903 hints.ai_family = AF_UNSPEC;
904 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700905 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700906
907 char port_str[16];
908 snprintf(port_str, sizeof(port_str), "%d", port);
909
910 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700911
912#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800913// TODO: When the Android SDK tools increases the Windows system
914// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700915#else
Josh Gao6487e742016-02-18 13:43:55 -0800916// Otherwise, keep using getaddrinfo(), or do runtime API detection
917// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700918#endif
Spencer Low5200c662015-07-30 23:07:55 -0700919 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800920 const DWORD err = WSAGetLastError();
921 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
922 host.c_str(), port_str,
923 android::base::SystemErrorCodeToString(err).c_str());
924
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700925 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800926 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800927 return -1;
928 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700929 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700930 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800931
Spencer Low5200c662015-07-30 23:07:55 -0700932 // TODO: Try all the addresses if there's more than one? This just uses
933 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
934 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800935 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
936 if (s == INVALID_SOCKET) {
937 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700938 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800939 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700940 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800941 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800942 return -1;
943 }
944 f->fh_socket = s;
945
Spencer Low5200c662015-07-30 23:07:55 -0700946 // TODO: Implement timeouts for Windows. Seems like the default in theory
947 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800948 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700949 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800950 const DWORD err = WSAGetLastError();
951 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
952 android::base::SystemErrorCodeToString(err).c_str());
953 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
954 port_str, error->c_str());
955 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800956 return -1;
957 }
958
Spencer Low5200c662015-07-30 23:07:55 -0700959 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800960 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
961 port);
962 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
963 fd);
Spencer Low5200c662015-07-30 23:07:55 -0700964 f.release();
965 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800966}
967
Josh Gao64a63ac2018-04-05 18:09:02 -0700968int adb_register_socket(SOCKET s) {
969 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin2fe9b602016-09-21 14:03:39 -0700970 f->fh_socket = s;
971 return _fh_to_int(f);
972}
973
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800974#undef accept
Josh Gao64a63ac2018-04-05 18:09:02 -0700975int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t* addrlen) {
976 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200977
Josh Gao64a63ac2018-04-05 18:09:02 -0700978 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700979 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -0700980 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800981 return -1;
982 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200983
Josh Gao64a63ac2018-04-05 18:09:02 -0700984 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800985 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -0700986 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
987 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800988 return -1;
989 }
990
Josh Gao64a63ac2018-04-05 18:09:02 -0700991 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800992 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700993 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -0700994 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd
995 << " failed: " + android::base::SystemErrorCodeToString(err);
996 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800997 return -1;
998 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200999
Spencer Low5200c662015-07-30 23:07:55 -07001000 const int fd = _fh_to_int(fh.get());
Josh Gao64a63ac2018-04-05 18:09:02 -07001001 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
1002 D("adb_socket_accept on fd %d returns fd %d", serverfd, fd);
Spencer Low5200c662015-07-30 23:07:55 -07001003 fh.release();
Josh Gao64a63ac2018-04-05 18:09:02 -07001004 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001005}
1006
Josh Gao64a63ac2018-04-05 18:09:02 -07001007int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) {
1008 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001009
Josh Gao64a63ac2018-04-05 18:09:02 -07001010 if (!fh || fh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001011 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001012 errno = EBADF;
1013 return -1;
1014 }
Spencer Low677fb432015-09-29 15:05:29 -07001015
1016 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1017 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1018 // auto-tuning.
1019
Josh Gao64a63ac2018-04-05 18:09:02 -07001020 int result =
1021 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1022 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001023 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -07001024 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd, level,
1025 optname, android::base::SystemErrorCodeToString(err).c_str());
1026 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -07001027 result = -1;
1028 }
1029 return result;
1030}
1031
Josh Gao3777d2e2016-02-16 17:34:53 -08001032int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1033 FH fh = _fh_from_int(fd, __func__);
1034
1035 if (!fh || fh->clazz != &_fh_socket_class) {
1036 D("adb_getsockname: invalid fd %d", fd);
1037 errno = EBADF;
1038 return -1;
1039 }
1040
Josh Gao3726a012017-03-30 13:04:35 -07001041 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001042 if (result == SOCKET_ERROR) {
1043 const DWORD err = WSAGetLastError();
1044 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1045 android::base::SystemErrorCodeToString(err).c_str());
1046 _socket_set_errno(err);
1047 result = -1;
1048 }
1049 return result;
1050}
Spencer Low5200c662015-07-30 23:07:55 -07001051
David Purselleaae97e2016-04-07 11:25:48 -07001052int adb_socket_get_local_port(int fd) {
1053 sockaddr_storage addr_storage;
1054 socklen_t addr_len = sizeof(addr_storage);
1055
1056 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1057 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1058 return -1;
1059 }
1060
1061 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1062 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1063 errno = ECONNABORTED;
1064 return -1;
1065 }
1066
1067 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1068}
1069
Josh Gao2e1e7892018-03-23 13:03:28 -07001070int adb_shutdown(int fd, int direction) {
1071 FH f = _fh_from_int(fd, __func__);
Spencer Low5200c662015-07-30 23:07:55 -07001072
1073 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001074 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001075 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001076 return -1;
1077 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001078
Josh Gao2e1e7892018-03-23 13:03:28 -07001079 D("adb_shutdown: %s", f->name);
1080 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001081 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001082 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001083 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001084 _socket_set_errno(err);
1085 return -1;
1086 }
1087 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001088}
1089
Josh Gao3777d2e2016-02-16 17:34:53 -08001090// Emulate socketpair(2) by binding and connecting to a socket.
1091int adb_socketpair(int sv[2]) {
1092 int server = -1;
1093 int client = -1;
1094 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001095 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001096 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001097
Josh Gao3777d2e2016-02-16 17:34:53 -08001098 server = network_loopback_server(0, SOCK_STREAM, &error);
1099 if (server < 0) {
1100 D("adb_socketpair: failed to create server: %s", error.c_str());
1101 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001102 }
1103
David Purselleaae97e2016-04-07 11:25:48 -07001104 local_port = adb_socket_get_local_port(server);
1105 if (local_port < 0) {
1106 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001107 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001108 }
David Purselleaae97e2016-04-07 11:25:48 -07001109 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001110
David Purselleaae97e2016-04-07 11:25:48 -07001111 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001112 if (client < 0) {
1113 D("adb_socketpair: failed to connect client: %s", error.c_str());
1114 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001115 }
1116
Josh Gao3726a012017-03-30 13:04:35 -07001117 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gao3777d2e2016-02-16 17:34:53 -08001118 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001119 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001120 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001121 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001122 adb_close(server);
1123 sv[0] = client;
1124 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001125 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001126
Josh Gao3777d2e2016-02-16 17:34:53 -08001127fail:
1128 if (server >= 0) {
1129 adb_close(server);
1130 }
1131 if (client >= 0) {
1132 adb_close(client);
1133 }
1134 if (accepted >= 0) {
1135 adb_close(accepted);
1136 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001137 return -1;
1138}
1139
Josh Gao3777d2e2016-02-16 17:34:53 -08001140bool set_file_block_mode(int fd, bool block) {
1141 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001142
Josh Gao3777d2e2016-02-16 17:34:53 -08001143 if (!fh || !fh->used) {
1144 errno = EBADF;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001145 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001146 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001147 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001148
Josh Gao3777d2e2016-02-16 17:34:53 -08001149 if (fh->clazz == &_fh_socket_class) {
1150 u_long x = !block;
1151 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001152 int error = WSAGetLastError();
1153 _socket_set_errno(error);
1154 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001155 return false;
1156 }
1157 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001158 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001159 errno = ENOTSOCK;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001160 D("Setting nonblocking on non-socket %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001161 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001162 }
1163}
1164
David Pursellbfd95032016-02-22 14:27:23 -08001165bool set_tcp_keepalive(int fd, int interval_sec) {
1166 FH fh = _fh_from_int(fd, __func__);
1167
1168 if (!fh || fh->clazz != &_fh_socket_class) {
1169 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1170 errno = EBADF;
1171 return false;
1172 }
1173
1174 tcp_keepalive keepalive;
1175 keepalive.onoff = (interval_sec > 0);
1176 keepalive.keepalivetime = interval_sec * 1000;
1177 keepalive.keepaliveinterval = interval_sec * 1000;
1178
1179 DWORD bytes_returned = 0;
1180 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1181 &bytes_returned, nullptr, nullptr) != 0) {
1182 const DWORD err = WSAGetLastError();
1183 D("set_tcp_keepalive(%d) failed: %s", fd,
1184 android::base::SystemErrorCodeToString(err).c_str());
1185 _socket_set_errno(err);
1186 return false;
1187 }
1188
1189 return true;
1190}
1191
Spencer Low50184062015-03-01 15:06:21 -08001192/**************************************************************************/
1193/**************************************************************************/
1194/***** *****/
1195/***** Console Window Terminal Emulation *****/
1196/***** *****/
1197/**************************************************************************/
1198/**************************************************************************/
1199
1200// This reads input from a Win32 console window and translates it into Unix
1201// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1202// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1203// is emulated instead of xterm because it is probably more popular than xterm:
1204// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1205// supports modern fonts, etc. It seems best to emulate the terminal that most
1206// Android developers use because they'll fix apps (the shell, etc.) to keep
1207// working with that terminal's emulation.
1208//
1209// The point of this emulation is not to be perfect or to solve all issues with
1210// console windows on Windows, but to be better than the original code which
1211// just called read() (which called ReadFile(), which called ReadConsoleA())
1212// which did not support Ctrl-C, tab completion, shell input line editing
1213// keys, server echo, and more.
1214//
1215// This implementation reconfigures the console with SetConsoleMode(), then
1216// calls ReadConsoleInput() to get raw input which it remaps to Unix
1217// terminal-style sequences which is returned via unix_read() which is used
1218// by the 'adb shell' command.
1219//
1220// Code organization:
1221//
David Pursellc5b8ad82015-10-28 14:29:51 -07001222// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001223// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1224// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1225// * _console_read() is the main code of the emulation.
1226
David Pursellc5b8ad82015-10-28 14:29:51 -07001227// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1228// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1229// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1230static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1231 // First check isatty(); this is very fast and eliminates most non-console
1232 // FDs, but returns 1 for both consoles and character devices like NUL.
1233#pragma push_macro("isatty")
1234#undef isatty
1235 if (!isatty(fd)) {
1236 return nullptr;
1237 }
1238#pragma pop_macro("isatty")
1239
1240 // To differentiate between character devices and consoles we need to get
1241 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1242 // GENERIC_READ permissions.
1243 const intptr_t intptr_handle = _get_osfhandle(fd);
1244 if (intptr_handle == -1) {
1245 return nullptr;
1246 }
1247 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1248 DWORD temp_mode = 0;
1249 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1250 return nullptr;
1251 }
1252
1253 return handle;
1254}
1255
1256// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1257static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001258 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1259 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001260 const int fd = fileno(stream);
1261 if (fd < 0) {
1262 return nullptr;
1263 }
1264 return _get_console_handle(fd);
1265}
1266
1267int unix_isatty(int fd) {
1268 return _get_console_handle(fd) ? 1 : 0;
1269}
Spencer Low50184062015-03-01 15:06:21 -08001270
Spencer Low32762f42015-11-10 19:17:16 -08001271// Get the next KEY_EVENT_RECORD that should be processed.
1272static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001273 for (;;) {
1274 DWORD read_count = 0;
1275 memset(input_record, 0, sizeof(*input_record));
1276 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001277 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001278 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001279 errno = EIO;
1280 return false;
1281 }
1282
1283 if (read_count == 0) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001284 LOG(FATAL) << "ReadConsoleInputA returned 0";
Spencer Low50184062015-03-01 15:06:21 -08001285 }
1286
1287 if (read_count != 1) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001288 LOG(FATAL) << "ReadConsoleInputA did not return one input record";
Spencer Low50184062015-03-01 15:06:21 -08001289 }
1290
Spencer Low2e02dc62015-11-07 17:34:39 -08001291 // If the console window is resized, emulate SIGWINCH by breaking out
1292 // of read() with errno == EINTR. Note that there is no event on
1293 // vertical resize because we don't give the console our own custom
1294 // screen buffer (with CreateConsoleScreenBuffer() +
1295 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1296 // supports scrollback, but doesn't seem to raise an event for vertical
1297 // window resize.
1298 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1299 errno = EINTR;
1300 return false;
1301 }
1302
Spencer Low50184062015-03-01 15:06:21 -08001303 if ((input_record->EventType == KEY_EVENT) &&
1304 (input_record->Event.KeyEvent.bKeyDown)) {
1305 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -07001306 LOG(FATAL) << "ReadConsoleInputA returned a key event with zero repeat count";
Spencer Low50184062015-03-01 15:06:21 -08001307 }
1308
1309 // Got an interesting INPUT_RECORD, so return
1310 return true;
1311 }
1312 }
1313}
1314
Spencer Low50184062015-03-01 15:06:21 -08001315static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1316 return (control_key_state & SHIFT_PRESSED) != 0;
1317}
1318
1319static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1320 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1321}
1322
1323static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1324 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1325}
1326
1327static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1328 return (control_key_state & NUMLOCK_ON) != 0;
1329}
1330
1331static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1332 return (control_key_state & CAPSLOCK_ON) != 0;
1333}
1334
1335static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1336 return (control_key_state & ENHANCED_KEY) != 0;
1337}
1338
1339// Constants from MSDN for ToAscii().
1340static const BYTE TOASCII_KEY_OFF = 0x00;
1341static const BYTE TOASCII_KEY_DOWN = 0x80;
1342static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1343
1344// Given a key event, ignore a modifier key and return the character that was
1345// entered without the modifier. Writes to *ch and returns the number of bytes
1346// written.
1347static size_t _get_char_ignoring_modifier(char* const ch,
1348 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1349 const WORD modifier) {
1350 // If there is no character from Windows, try ignoring the specified
1351 // modifier and look for a character. Note that if AltGr is being used,
1352 // there will be a character from Windows.
1353 if (key_event->uChar.AsciiChar == '\0') {
1354 // Note that we read the control key state from the passed in argument
1355 // instead of from key_event since the argument has been normalized.
1356 if (((modifier == VK_SHIFT) &&
1357 _is_shift_pressed(control_key_state)) ||
1358 ((modifier == VK_CONTROL) &&
1359 _is_ctrl_pressed(control_key_state)) ||
1360 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1361
1362 BYTE key_state[256] = {0};
1363 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1364 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1365 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1366 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1367 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1368 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1369 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1370 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1371
1372 // cause this modifier to be ignored
1373 key_state[modifier] = TOASCII_KEY_OFF;
1374
1375 WORD translated = 0;
1376 if (ToAscii(key_event->wVirtualKeyCode,
1377 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1378 // Ignoring the modifier, we found a character.
1379 *ch = (CHAR)translated;
1380 return 1;
1381 }
1382 }
1383 }
1384
1385 // Just use whatever Windows told us originally.
1386 *ch = key_event->uChar.AsciiChar;
1387
1388 // If the character from Windows is NULL, return a size of zero.
1389 return (*ch == '\0') ? 0 : 1;
1390}
1391
1392// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1393// but taking into account the shift key. This is because for a sequence like
1394// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1395// we want to find the character ')'.
1396//
1397// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1398// because it is the default key-sequence to switch the input language.
1399// This is configurable in the Region and Language control panel.
1400static __inline__ size_t _get_non_control_char(char* const ch,
1401 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1402 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1403 VK_CONTROL);
1404}
1405
1406// Get without Alt.
1407static __inline__ size_t _get_non_alt_char(char* const ch,
1408 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1409 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1410 VK_MENU);
1411}
1412
1413// Ignore the control key, find the character from Windows, and apply any
1414// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1415// *pch and returns number of bytes written.
1416static size_t _get_control_character(char* const pch,
1417 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1418 const size_t len = _get_non_control_char(pch, key_event,
1419 control_key_state);
1420
1421 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1422 char ch = *pch;
1423 switch (ch) {
1424 case '2':
1425 case '@':
1426 case '`':
1427 ch = '\0';
1428 break;
1429 case '3':
1430 case '[':
1431 case '{':
1432 ch = '\x1b';
1433 break;
1434 case '4':
1435 case '\\':
1436 case '|':
1437 ch = '\x1c';
1438 break;
1439 case '5':
1440 case ']':
1441 case '}':
1442 ch = '\x1d';
1443 break;
1444 case '6':
1445 case '^':
1446 case '~':
1447 ch = '\x1e';
1448 break;
1449 case '7':
1450 case '-':
1451 case '_':
1452 ch = '\x1f';
1453 break;
1454 case '8':
1455 ch = '\x7f';
1456 break;
1457 case '/':
1458 if (!_is_alt_pressed(control_key_state)) {
1459 ch = '\x1f';
1460 }
1461 break;
1462 case '?':
1463 if (!_is_alt_pressed(control_key_state)) {
1464 ch = '\x7f';
1465 }
1466 break;
1467 }
1468 *pch = ch;
1469 }
1470
1471 return len;
1472}
1473
1474static DWORD _normalize_altgr_control_key_state(
1475 const KEY_EVENT_RECORD* const key_event) {
1476 DWORD control_key_state = key_event->dwControlKeyState;
1477
1478 // If we're in an AltGr situation where the AltGr key is down (depending on
1479 // the keyboard layout, that might be the physical right alt key which
1480 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1481 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1482 // a character (which indicates that there was an AltGr mapping), then act
1483 // as if alt and control are not really down for the purposes of modifiers.
1484 // This makes it so that if the user with, say, a German keyboard layout
1485 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1486 // output the key and we don't see the Alt and Ctrl keys.
1487 if (_is_ctrl_pressed(control_key_state) &&
1488 _is_alt_pressed(control_key_state)
1489 && (key_event->uChar.AsciiChar != '\0')) {
1490 // Try to remove as few bits as possible to improve our chances of
1491 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1492 // Left-Alt + Right-Ctrl + AltGr.
1493 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1494 // Remove Right-Alt.
1495 control_key_state &= ~RIGHT_ALT_PRESSED;
1496 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1497 // pressed, Left-Ctrl is almost always set, except if the user
1498 // presses Right-Ctrl, then AltGr (in that specific order) for
1499 // whatever reason. At any rate, make sure the bit is not set.
1500 control_key_state &= ~LEFT_CTRL_PRESSED;
1501 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1502 // Remove Left-Alt.
1503 control_key_state &= ~LEFT_ALT_PRESSED;
1504 // Whichever Ctrl key is down, remove it from the state. We only
1505 // remove one key, to improve our chances of detecting the
1506 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1507 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1508 // Remove Left-Ctrl.
1509 control_key_state &= ~LEFT_CTRL_PRESSED;
1510 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1511 // Remove Right-Ctrl.
1512 control_key_state &= ~RIGHT_CTRL_PRESSED;
1513 }
1514 }
1515
1516 // Note that this logic isn't 100% perfect because Windows doesn't
1517 // allow us to detect all combinations because a physical AltGr key
1518 // press shows up as two bits, plus some combinations are ambiguous
1519 // about what is actually physically pressed.
1520 }
1521
1522 return control_key_state;
1523}
1524
1525// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1526// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1527// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1528// appropriately.
1529static DWORD _normalize_keypad_control_key_state(const WORD vk,
1530 const DWORD control_key_state) {
1531 if (!_is_numlock_on(control_key_state)) {
1532 return control_key_state;
1533 }
1534 if (!_is_enhanced_key(control_key_state)) {
1535 switch (vk) {
1536 case VK_INSERT: // 0
1537 case VK_DELETE: // .
1538 case VK_END: // 1
1539 case VK_DOWN: // 2
1540 case VK_NEXT: // 3
1541 case VK_LEFT: // 4
1542 case VK_CLEAR: // 5
1543 case VK_RIGHT: // 6
1544 case VK_HOME: // 7
1545 case VK_UP: // 8
1546 case VK_PRIOR: // 9
1547 return control_key_state | SHIFT_PRESSED;
1548 }
1549 }
1550
1551 return control_key_state;
1552}
1553
1554static const char* _get_keypad_sequence(const DWORD control_key_state,
1555 const char* const normal, const char* const shifted) {
1556 if (_is_shift_pressed(control_key_state)) {
1557 // Shift is pressed and NumLock is off
1558 return shifted;
1559 } else {
1560 // Shift is not pressed and NumLock is off, or,
1561 // Shift is pressed and NumLock is on, in which case we want the
1562 // NumLock and Shift to neutralize each other, thus, we want the normal
1563 // sequence.
1564 return normal;
1565 }
1566 // If Shift is not pressed and NumLock is on, a different virtual key code
1567 // is returned by Windows, which can be taken care of by a different case
1568 // statement in _console_read().
1569}
1570
1571// Write sequence to buf and return the number of bytes written.
1572static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1573 DWORD control_key_state, const char* const normal) {
1574 // Copy the base sequence into buf.
1575 const size_t len = strlen(normal);
1576 memcpy(buf, normal, len);
1577
1578 int code = 0;
1579
1580 control_key_state = _normalize_keypad_control_key_state(vk,
1581 control_key_state);
1582
1583 if (_is_shift_pressed(control_key_state)) {
1584 code |= 0x1;
1585 }
1586 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1587 code |= 0x2;
1588 }
1589 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1590 code |= 0x4;
1591 }
1592 // If some modifier was held down, then we need to insert the modifier code
1593 if (code != 0) {
1594 if (len == 0) {
1595 // Should be impossible because caller should pass a string of
1596 // non-zero length.
1597 return 0;
1598 }
1599 size_t index = len - 1;
1600 const char lastChar = buf[index];
1601 if (lastChar != '~') {
1602 buf[index++] = '1';
1603 }
1604 buf[index++] = ';'; // modifier separator
1605 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1606 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1607 buf[index++] = '1' + code;
1608 buf[index++] = lastChar; // move ~ (or other last char) to the end
1609 return index;
1610 }
1611 return len;
1612}
1613
1614// Write sequence to buf and return the number of bytes written.
1615static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1616 const DWORD control_key_state, const char* const normal,
1617 const char shifted) {
1618 if (_is_shift_pressed(control_key_state)) {
1619 // Shift is pressed and NumLock is off
1620 if (shifted != '\0') {
1621 buf[0] = shifted;
1622 return sizeof(buf[0]);
1623 } else {
1624 return 0;
1625 }
1626 } else {
1627 // Shift is not pressed and NumLock is off, or,
1628 // Shift is pressed and NumLock is on, in which case we want the
1629 // NumLock and Shift to neutralize each other, thus, we want the normal
1630 // sequence.
1631 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1632 }
1633 // If Shift is not pressed and NumLock is on, a different virtual key code
1634 // is returned by Windows, which can be taken care of by a different case
1635 // statement in _console_read().
1636}
1637
1638// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1639// Standard German. Figure this out at runtime so we know what to output for
1640// Shift-VK_DELETE.
1641static char _get_decimal_char() {
1642 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1643}
1644
1645// Prefix the len bytes in buf with the escape character, and then return the
1646// new buffer length.
1647size_t _escape_prefix(char* const buf, const size_t len) {
1648 // If nothing to prefix, don't do anything. We might be called with
1649 // len == 0, if alt was held down with a dead key which produced nothing.
1650 if (len == 0) {
1651 return 0;
1652 }
1653
1654 memmove(&buf[1], buf, len);
1655 buf[0] = '\x1b';
1656 return len + 1;
1657}
1658
Spencer Low32762f42015-11-10 19:17:16 -08001659// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001660static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001661
1662// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1663// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001664static int _console_read(const HANDLE console, void* buf, size_t len) {
1665 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001666 // Read of zero bytes should not block waiting for something from the console.
1667 if (len == 0) {
1668 return 0;
1669 }
1670
1671 // Flush as much as possible from input buffer.
1672 if (!g_console_input_buffer.empty()) {
1673 const int bytes_read = std::min(len, g_console_input_buffer.size());
1674 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1675 const auto begin = g_console_input_buffer.begin();
1676 g_console_input_buffer.erase(begin, begin + bytes_read);
1677 return bytes_read;
1678 }
1679
1680 // Read from the actual console. This may block until input.
1681 INPUT_RECORD input_record;
1682 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001683 return -1;
1684 }
1685
Spencer Low32762f42015-11-10 19:17:16 -08001686 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001687 const WORD vk = key_event->wVirtualKeyCode;
1688 const CHAR ch = key_event->uChar.AsciiChar;
1689 const DWORD control_key_state = _normalize_altgr_control_key_state(
1690 key_event);
1691
1692 // The following emulation code should write the output sequence to
1693 // either seqstr or to seqbuf and seqbuflen.
Yi Kongaed415c2018-07-13 18:15:16 -07001694 const char* seqstr = nullptr; // NULL terminated C-string
Spencer Low50184062015-03-01 15:06:21 -08001695 // Enough space for max sequence string below, plus modifiers and/or
1696 // escape prefix.
1697 char seqbuf[16];
1698 size_t seqbuflen = 0; // Space used in seqbuf.
1699
1700#define MATCH(vk, normal) \
1701 case (vk): \
1702 { \
1703 seqstr = (normal); \
1704 } \
1705 break;
1706
1707 // Modifier keys should affect the output sequence.
1708#define MATCH_MODIFIER(vk, normal) \
1709 case (vk): \
1710 { \
1711 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1712 control_key_state, (normal)); \
1713 } \
1714 break;
1715
1716 // The shift key should affect the output sequence.
1717#define MATCH_KEYPAD(vk, normal, shifted) \
1718 case (vk): \
1719 { \
1720 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1721 (shifted)); \
1722 } \
1723 break;
1724
1725 // The shift key and other modifier keys should affect the output
1726 // sequence.
1727#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1728 case (vk): \
1729 { \
1730 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1731 control_key_state, (normal), (shifted)); \
1732 } \
1733 break;
1734
1735#define ESC "\x1b"
1736#define CSI ESC "["
1737#define SS3 ESC "O"
1738
1739 // Only support normal mode, not application mode.
1740
1741 // Enhanced keys:
1742 // * 6-pack: insert, delete, home, end, page up, page down
1743 // * cursor keys: up, down, right, left
1744 // * keypad: divide, enter
1745 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1746 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1747 if (_is_enhanced_key(control_key_state)) {
1748 switch (vk) {
1749 case VK_RETURN: // Enter key on keypad
1750 if (_is_ctrl_pressed(control_key_state)) {
1751 seqstr = "\n";
1752 } else {
1753 seqstr = "\r";
1754 }
1755 break;
1756
1757 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1758 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1759
1760 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1761 // will be fixed soon to match xterm which sends CSI "F" and
1762 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1763 MATCH(VK_END, CSI "F");
1764 MATCH(VK_HOME, CSI "H");
1765
1766 MATCH_MODIFIER(VK_LEFT, CSI "D");
1767 MATCH_MODIFIER(VK_UP, CSI "A");
1768 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1769 MATCH_MODIFIER(VK_DOWN, CSI "B");
1770
1771 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1772 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1773
1774 MATCH(VK_DIVIDE, "/");
1775 }
1776 } else { // Non-enhanced keys:
1777 switch (vk) {
1778 case VK_BACK: // backspace
1779 if (_is_alt_pressed(control_key_state)) {
1780 seqstr = ESC "\x7f";
1781 } else {
1782 seqstr = "\x7f";
1783 }
1784 break;
1785
1786 case VK_TAB:
1787 if (_is_shift_pressed(control_key_state)) {
1788 seqstr = CSI "Z";
1789 } else {
1790 seqstr = "\t";
1791 }
1792 break;
1793
1794 // Number 5 key in keypad when NumLock is off, or if NumLock is
1795 // on and Shift is down.
1796 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1797
1798 case VK_RETURN: // Enter key on main keyboard
1799 if (_is_alt_pressed(control_key_state)) {
1800 seqstr = ESC "\n";
1801 } else if (_is_ctrl_pressed(control_key_state)) {
1802 seqstr = "\n";
1803 } else {
1804 seqstr = "\r";
1805 }
1806 break;
1807
1808 // VK_ESCAPE: Don't do any special handling. The OS uses many
1809 // of the sequences with Escape and many of the remaining
1810 // sequences don't produce bKeyDown messages, only !bKeyDown
1811 // for whatever reason.
1812
1813 case VK_SPACE:
1814 if (_is_alt_pressed(control_key_state)) {
1815 seqstr = ESC " ";
1816 } else if (_is_ctrl_pressed(control_key_state)) {
1817 seqbuf[0] = '\0'; // NULL char
1818 seqbuflen = 1;
1819 } else {
1820 seqstr = " ";
1821 }
1822 break;
1823
1824 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1825 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1826
1827 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1828 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1829
1830 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1831 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1832 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1833 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1834
1835 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1836 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1837 _get_decimal_char());
1838
1839 case 0x30: // 0
1840 case 0x31: // 1
1841 case 0x39: // 9
1842 case VK_OEM_1: // ;:
1843 case VK_OEM_PLUS: // =+
1844 case VK_OEM_COMMA: // ,<
1845 case VK_OEM_PERIOD: // .>
1846 case VK_OEM_7: // '"
1847 case VK_OEM_102: // depends on keyboard, could be <> or \|
1848 case VK_OEM_2: // /?
1849 case VK_OEM_3: // `~
1850 case VK_OEM_4: // [{
1851 case VK_OEM_5: // \|
1852 case VK_OEM_6: // ]}
1853 {
1854 seqbuflen = _get_control_character(seqbuf, key_event,
1855 control_key_state);
1856
1857 if (_is_alt_pressed(control_key_state)) {
1858 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1859 }
1860 }
1861 break;
1862
1863 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001864 case 0x33: // 3
1865 case 0x34: // 4
1866 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001867 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001868 case 0x37: // 7
1869 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001870 case VK_OEM_MINUS: // -_
1871 {
1872 seqbuflen = _get_control_character(seqbuf, key_event,
1873 control_key_state);
1874
1875 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1876 // prefix with escape.
1877 if (_is_alt_pressed(control_key_state) &&
1878 !(_is_ctrl_pressed(control_key_state) &&
1879 !_is_shift_pressed(control_key_state))) {
1880 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1881 }
1882 }
1883 break;
1884
Spencer Low50184062015-03-01 15:06:21 -08001885 case 0x41: // a
1886 case 0x42: // b
1887 case 0x43: // c
1888 case 0x44: // d
1889 case 0x45: // e
1890 case 0x46: // f
1891 case 0x47: // g
1892 case 0x48: // h
1893 case 0x49: // i
1894 case 0x4a: // j
1895 case 0x4b: // k
1896 case 0x4c: // l
1897 case 0x4d: // m
1898 case 0x4e: // n
1899 case 0x4f: // o
1900 case 0x50: // p
1901 case 0x51: // q
1902 case 0x52: // r
1903 case 0x53: // s
1904 case 0x54: // t
1905 case 0x55: // u
1906 case 0x56: // v
1907 case 0x57: // w
1908 case 0x58: // x
1909 case 0x59: // y
1910 case 0x5a: // z
1911 {
1912 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1913 control_key_state);
1914
1915 // If Alt is pressed, then prefix with escape.
1916 if (_is_alt_pressed(control_key_state)) {
1917 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1918 }
1919 }
1920 break;
1921
1922 // These virtual key codes are generated by the keys on the
1923 // keypad *when NumLock is on* and *Shift is up*.
1924 MATCH(VK_NUMPAD0, "0");
1925 MATCH(VK_NUMPAD1, "1");
1926 MATCH(VK_NUMPAD2, "2");
1927 MATCH(VK_NUMPAD3, "3");
1928 MATCH(VK_NUMPAD4, "4");
1929 MATCH(VK_NUMPAD5, "5");
1930 MATCH(VK_NUMPAD6, "6");
1931 MATCH(VK_NUMPAD7, "7");
1932 MATCH(VK_NUMPAD8, "8");
1933 MATCH(VK_NUMPAD9, "9");
1934
1935 MATCH(VK_MULTIPLY, "*");
1936 MATCH(VK_ADD, "+");
1937 MATCH(VK_SUBTRACT, "-");
1938 // VK_DECIMAL is generated by the . key on the keypad *when
1939 // NumLock is on* and *Shift is up* and the sequence is not
1940 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1941 // Windows Security screen to come up).
1942 case VK_DECIMAL:
1943 // U.S. English uses '.', Germany German uses ','.
1944 seqbuflen = _get_non_control_char(seqbuf, key_event,
1945 control_key_state);
1946 break;
1947
1948 MATCH_MODIFIER(VK_F1, SS3 "P");
1949 MATCH_MODIFIER(VK_F2, SS3 "Q");
1950 MATCH_MODIFIER(VK_F3, SS3 "R");
1951 MATCH_MODIFIER(VK_F4, SS3 "S");
1952 MATCH_MODIFIER(VK_F5, CSI "15~");
1953 MATCH_MODIFIER(VK_F6, CSI "17~");
1954 MATCH_MODIFIER(VK_F7, CSI "18~");
1955 MATCH_MODIFIER(VK_F8, CSI "19~");
1956 MATCH_MODIFIER(VK_F9, CSI "20~");
1957 MATCH_MODIFIER(VK_F10, CSI "21~");
1958 MATCH_MODIFIER(VK_F11, CSI "23~");
1959 MATCH_MODIFIER(VK_F12, CSI "24~");
1960
1961 MATCH_MODIFIER(VK_F13, CSI "25~");
1962 MATCH_MODIFIER(VK_F14, CSI "26~");
1963 MATCH_MODIFIER(VK_F15, CSI "28~");
1964 MATCH_MODIFIER(VK_F16, CSI "29~");
1965 MATCH_MODIFIER(VK_F17, CSI "31~");
1966 MATCH_MODIFIER(VK_F18, CSI "32~");
1967 MATCH_MODIFIER(VK_F19, CSI "33~");
1968 MATCH_MODIFIER(VK_F20, CSI "34~");
1969
1970 // MATCH_MODIFIER(VK_F21, ???);
1971 // MATCH_MODIFIER(VK_F22, ???);
1972 // MATCH_MODIFIER(VK_F23, ???);
1973 // MATCH_MODIFIER(VK_F24, ???);
1974 }
1975 }
1976
1977#undef MATCH
1978#undef MATCH_MODIFIER
1979#undef MATCH_KEYPAD
1980#undef MATCH_MODIFIER_KEYPAD
1981#undef ESC
1982#undef CSI
1983#undef SS3
1984
1985 const char* out;
1986 size_t outlen;
1987
1988 // Check for output in any of:
1989 // * seqstr is set (and strlen can be used to determine the length).
1990 // * seqbuf and seqbuflen are set
1991 // Fallback to ch from Windows.
Yi Kongaed415c2018-07-13 18:15:16 -07001992 if (seqstr != nullptr) {
Spencer Low50184062015-03-01 15:06:21 -08001993 out = seqstr;
1994 outlen = strlen(seqstr);
1995 } else if (seqbuflen > 0) {
1996 out = seqbuf;
1997 outlen = seqbuflen;
1998 } else if (ch != '\0') {
1999 // Use whatever Windows told us it is.
2000 seqbuf[0] = ch;
2001 seqbuflen = 1;
2002 out = seqbuf;
2003 outlen = seqbuflen;
2004 } else {
2005 // No special handling for the virtual key code and Windows isn't
2006 // telling us a character code, then we don't know how to translate
2007 // the key press.
2008 //
2009 // Consume the input and 'continue' to cause us to get a new key
2010 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002011 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002012 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002013 continue;
2014 }
2015
Spencer Low32762f42015-11-10 19:17:16 -08002016 // put output wRepeatCount times into g_console_input_buffer
2017 while (key_event->wRepeatCount-- > 0) {
2018 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002019 }
2020
Spencer Low32762f42015-11-10 19:17:16 -08002021 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002022 }
2023}
2024
2025static DWORD _old_console_mode; // previous GetConsoleMode() result
2026static HANDLE _console_handle; // when set, console mode should be restored
2027
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002028void stdin_raw_init() {
2029 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002030 if (in == nullptr) {
2031 return;
2032 }
Spencer Low50184062015-03-01 15:06:21 -08002033
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002034 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2035 // calling the process Ctrl-C routine (configured by
2036 // SetConsoleCtrlHandler()).
2037 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2038 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2039 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002040 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2041 ENABLE_LINE_INPUT |
2042 ENABLE_ECHO_INPUT);
2043 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2044 new_console_mode |= ENABLE_WINDOW_INPUT;
2045
2046 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002047 // This really should not fail.
2048 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002049 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002050 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002051
2052 // Once this is set, it means that stdin has been configured for
2053 // reading from and that the old console mode should be restored later.
2054 _console_handle = in;
2055
2056 // Note that we don't need to configure C Runtime line-ending
2057 // translation because _console_read() does not call the C Runtime to
2058 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002059}
2060
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002061void stdin_raw_restore() {
Yi Kongaed415c2018-07-13 18:15:16 -07002062 if (_console_handle != nullptr) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002063 const HANDLE in = _console_handle;
Yi Kongaed415c2018-07-13 18:15:16 -07002064 _console_handle = nullptr; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002065
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002066 if (!SetConsoleMode(in, _old_console_mode)) {
2067 // This really should not fail.
2068 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002069 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002070 }
2071 }
2072}
2073
Spencer Low2e02dc62015-11-07 17:34:39 -08002074// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2075int unix_read_interruptible(int fd, void* buf, size_t len) {
Yi Kongaed415c2018-07-13 18:15:16 -07002076 if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) {
Spencer Low50184062015-03-01 15:06:21 -08002077 // If it is a request to read from stdin, and stdin_raw_init() has been
2078 // called, and it successfully configured the console, then read from
2079 // the console using Win32 console APIs and partially emulate a unix
2080 // terminal.
2081 return _console_read(_console_handle, buf, len);
2082 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002083 // On older versions of Windows (definitely 7, definitely not 10),
2084 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002085 // we need to limit the read size.
2086 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002087 len = 4096;
2088 }
Spencer Low50184062015-03-01 15:06:21 -08002089 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002090 // can do LF/CR translation (which is overridable with _setmode()).
2091 // Undefine the macro that is set in sysdeps.h which bans calls to
2092 // plain read() in favor of unix_read() or adb_read().
2093#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002094#undef read
2095 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002096#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002097 }
2098}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002099
2100/**************************************************************************/
2101/**************************************************************************/
2102/***** *****/
2103/***** Unicode support *****/
2104/***** *****/
2105/**************************************************************************/
2106/**************************************************************************/
2107
2108// This implements support for using files with Unicode filenames and for
2109// outputting Unicode text to a Win32 console window. This is inspired from
2110// http://utf8everywhere.org/.
2111//
2112// Background
2113// ----------
2114//
2115// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2116// filenames to APIs such as open(). This works because filenames are largely
2117// opaque 'cookies' (perhaps excluding path separators).
2118//
2119// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2120// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2121// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2122// CreateFile() API is really just a macro that adds the W/A based on whether
2123// the UNICODE preprocessor symbol is defined).
2124//
2125// Options
2126// -------
2127//
2128// Thus, to write a portable program, there are a few options:
2129//
2130// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2131// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2132// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2133// open() API.
2134//
2135// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2136// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2137// potentially touching a lot of code.
2138//
2139// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2140// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2141// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2142// or C Runtime API.
2143//
2144// The Choice
2145// ----------
2146//
Spencer Lowd21dc822015-11-12 15:20:15 -08002147// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2148// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002149// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002150// args that are passed to main() at the beginning of program startup. We also use
2151// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002152// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2153//
2154// Unicode console output
2155// ----------------------
2156//
2157// The way to output Unicode to a Win32 console window is to call
2158// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002159// such as Lucida Console or Consolas, and in the case of East Asian languages
2160// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2161// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2162// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002163//
2164// The problem is getting the C Runtime to make fprintf and related APIs call
2165// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2166// promising, but the various modes have issues:
2167//
2168// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2169// UTF-16 do not display properly.
2170// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2171// totally wrong.
2172// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2173// handler to be called (upon a later I/O call), aborting the process.
2174// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2175// to output nothing.
2176//
2177// So the only solution is to write our own adb_fprintf() that converts UTF-8
2178// to UTF-16 and then calls WriteConsoleW().
2179
2180
Spencer Lowcf4ff642015-05-11 01:08:48 -07002181// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2182// be passed to main().
2183NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2184 narrow_args = new char*[argc + 1];
2185
2186 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002187 std::string arg_narrow;
2188 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
Elliott Hughes4679a392018-10-19 13:59:44 -07002189 PLOG(FATAL) << "cannot convert argument from UTF-16 to UTF-8";
Spencer Lowd21dc822015-11-12 15:20:15 -08002190 }
2191 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002192 }
2193 narrow_args[argc] = nullptr; // terminate
2194}
2195
2196NarrowArgs::~NarrowArgs() {
2197 if (narrow_args != nullptr) {
2198 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2199 free(*argp);
2200 }
2201 delete[] narrow_args;
2202 narrow_args = nullptr;
2203 }
2204}
2205
2206int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002207 std::wstring path_wide;
2208 if (!android::base::UTF8ToWide(path, &path_wide)) {
2209 return -1;
2210 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002211 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002212 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002213 } else {
2214 int mode;
2215 va_list args;
2216 va_start(args, options);
2217 mode = va_arg(args, int);
2218 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002219 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002220 }
2221}
2222
Spencer Lowcf4ff642015-05-11 01:08:48 -07002223// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002224DIR* adb_opendir(const char* path) {
2225 std::wstring path_wide;
2226 if (!android::base::UTF8ToWide(path, &path_wide)) {
2227 return nullptr;
2228 }
2229
Spencer Lowcf4ff642015-05-11 01:08:48 -07002230 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2231 // the fields, but right now all the callers treat the structure as
2232 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002233 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002234}
2235
2236// Version of readdir() that returns UTF-8 paths.
2237struct dirent* adb_readdir(DIR* dir) {
2238 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2239 struct _wdirent* const went = _wreaddir(wdir);
2240 if (went == nullptr) {
2241 return nullptr;
2242 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002243
Spencer Lowcf4ff642015-05-11 01:08:48 -07002244 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002245 std::string name_utf8;
2246 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2247 return nullptr;
2248 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002249
2250 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2251 // space for UTF-16 wchar_t's) with UTF-8 char's.
2252 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2253
2254 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2255 // Name too big to fit in existing buffer.
2256 errno = ENOMEM;
2257 return nullptr;
2258 }
2259
2260 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2261 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2262 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2263 // bigger than the caller expects because they expect a dirent structure
2264 // which has a smaller d_name field. Ignore this since the caller should be
2265 // resilient.
2266
2267 // Rewrite the UTF-16 d_name field to UTF-8.
2268 strcpy(ent->d_name, name_utf8.c_str());
2269
2270 return ent;
2271}
2272
2273// Version of closedir() to go with our version of adb_opendir().
2274int adb_closedir(DIR* dir) {
2275 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2276}
2277
2278// Version of unlink() that takes a UTF-8 path.
2279int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002280 std::wstring wpath;
2281 if (!android::base::UTF8ToWide(path, &wpath)) {
2282 return -1;
2283 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002284
2285 int rc = _wunlink(wpath.c_str());
2286
2287 if (rc == -1 && errno == EACCES) {
2288 /* unlink returns EACCES when the file is read-only, so we first */
2289 /* try to make it writable, then unlink again... */
2290 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2291 if (rc == 0)
2292 rc = _wunlink(wpath.c_str());
2293 }
2294 return rc;
2295}
2296
2297// Version of mkdir() that takes a UTF-8 path.
2298int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002299 std::wstring path_wide;
2300 if (!android::base::UTF8ToWide(path, &path_wide)) {
2301 return -1;
2302 }
2303
2304 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002305}
2306
2307// Version of utime() that takes a UTF-8 path.
2308int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002309 std::wstring path_wide;
2310 if (!android::base::UTF8ToWide(path, &path_wide)) {
2311 return -1;
2312 }
2313
Spencer Lowcf4ff642015-05-11 01:08:48 -07002314 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2315 "utimbuf and _utimbuf should be the same size because they both "
2316 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002317 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002318}
2319
2320// Version of chmod() that takes a UTF-8 path.
2321int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002322 std::wstring path_wide;
2323 if (!android::base::UTF8ToWide(path, &path_wide)) {
2324 return -1;
2325 }
2326
2327 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002328}
2329
Spencer Lowa30b79a2015-11-15 16:29:36 -08002330// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2331static inline size_t utf8_codepoint_len(uint8_t ch) {
2332 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2333}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002334
Spencer Lowa30b79a2015-11-15 16:29:36 -08002335namespace internal {
2336
2337// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2338// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2339// remaining_bytes.
2340size_t ParseCompleteUTF8(const char* const first, const char* const last,
2341 std::vector<char>* const remaining_bytes) {
2342 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2343 // Current_after points one byte past the current byte to be examined.
2344 for (const char* current_after = last; current_after != first; --current_after) {
2345 const char* const current = current_after - 1;
2346 const char ch = *current;
2347 const char kHighBit = 0x80u;
2348 const char kTwoHighestBits = 0xC0u;
2349 if ((ch & kHighBit) == 0) { // high bit not set
2350 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2351 // bytes with no leading byte, so return the entire buffer.
2352 break;
2353 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2354 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2355 const size_t bytes_available = last - current;
2356 if (bytes_available < utf8_codepoint_len(ch)) {
2357 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2358 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2359 // to remaining_bytes.
2360 remaining_bytes->insert(remaining_bytes->end(), current, last);
2361 return current - first;
2362 } else {
2363 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2364 // trailing bytes with no lead byte, so return the entire buffer.
2365 break;
2366 }
2367 } else {
2368 // Trailing byte, so keep going backwards looking for the lead byte.
2369 }
2370 }
2371
2372 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2373 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2374 // so that they can be processed.
2375 return last - first;
2376}
2377
2378}
2379
2380// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2381// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2382// This matches the behavior of Linux.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002383
2384// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2385static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2386 HANDLE console) {
Josh Gao0cd3ae12016-09-21 12:37:10 -07002387 static std::mutex& console_output_buffer_lock = *new std::mutex();
2388 static auto& console_output_buffer = *new std::vector<char>();
2389
Spencer Lowa30b79a2015-11-15 16:29:36 -08002390 const int saved_errno = errno;
2391 std::vector<char> combined_buffer;
2392
2393 // Complete UTF-8 sequences that should be immediately written to the console.
2394 const char* utf8;
2395 size_t utf8_size;
2396
Josh Gao0cd3ae12016-09-21 12:37:10 -07002397 {
2398 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2399 if (console_output_buffer.empty()) {
2400 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2401 // common case with plain ASCII), parse buf directly.
2402 utf8 = buf;
2403 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2404 } else {
2405 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2406 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2407 // combined_buffer, then parse it all together.
2408 combined_buffer.swap(console_output_buffer);
2409 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002410
Josh Gao0cd3ae12016-09-21 12:37:10 -07002411 utf8 = combined_buffer.data();
2412 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2413 &console_output_buffer);
2414 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002415 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002416
2417 std::wstring utf16;
2418
2419 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2420 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2421 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002422 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002423 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002424
2425 // Note that this does not do \n => \r\n translation because that
2426 // doesn't seem necessary for the Windows console. For the Windows
2427 // console \r moves to the beginning of the line and \n moves to a new
2428 // line.
2429
2430 // Flush any stream buffering so that our output is afterwards which
2431 // makes sense because our call is afterwards.
2432 (void)fflush(stream);
2433
2434 // Write UTF-16 to the console.
2435 DWORD written = 0;
Yi Kongaed415c2018-07-13 18:15:16 -07002436 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002437 errno = EIO;
2438 return -1;
2439 }
2440
Spencer Lowa30b79a2015-11-15 16:29:36 -08002441 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2442 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2443 // matches the Linux behavior.
2444 errno = saved_errno;
2445 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002446}
2447
2448// Function prototype because attributes cannot be placed on func definitions.
Elliott Hughesd8a4c602018-06-26 13:06:15 -07002449static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap)
2450 __attribute__((__format__(__printf__, 3, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002451
2452// Internal function to format a UTF-8 string and write it to a Win32 console.
2453// Returns -1 on error.
2454static int _console_vfprintf(const HANDLE console, FILE* stream,
2455 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002456 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002457 std::string output_utf8;
2458
2459 // Format the string.
2460 // This could throw std::bad_alloc.
2461 android::base::StringAppendV(&output_utf8, format, ap);
2462
Spencer Lowa30b79a2015-11-15 16:29:36 -08002463 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2464 console);
2465 if (result != -1) {
2466 errno = saved_errno;
2467 } else {
2468 // If -1 was returned, errno has been set.
2469 }
2470 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002471}
2472
2473// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2474// Windows console.
2475int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2476 const HANDLE console = _get_console_handle(stream);
2477
2478 // If there is an associated Win32 console, write to it specially,
2479 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002480 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002481 return _console_vfprintf(console, stream, format, ap);
2482 } else {
2483 // If vfprintf is a macro, undefine it, so we can call the real
2484 // C Runtime API.
2485#pragma push_macro("vfprintf")
2486#undef vfprintf
2487 return vfprintf(stream, format, ap);
2488#pragma pop_macro("vfprintf")
2489 }
2490}
2491
Spencer Lowa30b79a2015-11-15 16:29:36 -08002492// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2493int adb_vprintf(const char *format, va_list ap) {
2494 return adb_vfprintf(stdout, format, ap);
2495}
2496
Spencer Lowcf4ff642015-05-11 01:08:48 -07002497// Version of fprintf() that takes UTF-8 and can write Unicode to a
2498// Windows console.
2499int adb_fprintf(FILE *stream, const char *format, ...) {
2500 va_list ap;
2501 va_start(ap, format);
2502 const int result = adb_vfprintf(stream, format, ap);
2503 va_end(ap);
2504
2505 return result;
2506}
2507
2508// Version of printf() that takes UTF-8 and can write Unicode to a
2509// Windows console.
2510int adb_printf(const char *format, ...) {
2511 va_list ap;
2512 va_start(ap, format);
2513 const int result = adb_vfprintf(stdout, format, ap);
2514 va_end(ap);
2515
2516 return result;
2517}
2518
2519// Version of fputs() that takes UTF-8 and can write Unicode to a
2520// Windows console.
2521int adb_fputs(const char* buf, FILE* stream) {
2522 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2523 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002524 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002525 return adb_fprintf(stream, "%s", buf);
2526}
2527
2528// Version of fputc() that takes UTF-8 and can write Unicode to a
2529// Windows console.
2530int adb_fputc(int ch, FILE* stream) {
2531 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002532 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002533 return EOF;
2534 }
2535 // For success, fputc returns the char, cast to unsigned char, then to int.
2536 return static_cast<unsigned char>(ch);
2537}
2538
Spencer Lowa30b79a2015-11-15 16:29:36 -08002539// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2540int adb_putchar(int ch) {
2541 return adb_fputc(ch, stdout);
2542}
2543
2544// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2545int adb_puts(const char* buf) {
2546 // adb_printf returns -1 on error, which is conveniently the same as EOF
2547 // which puts (and hence adb_puts) should return on error.
2548 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2549 return adb_printf("%s\n", buf);
2550}
2551
Spencer Lowcf4ff642015-05-11 01:08:48 -07002552// Internal function to write UTF-8 to a Win32 console. Returns the number of
2553// items (of length size) written. On error, returns a short item count or 0.
2554static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2555 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002556 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2557 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002558 if (result == -1) {
2559 return 0;
2560 }
2561 return result / size;
2562}
2563
2564// Version of fwrite() that takes UTF-8 and can write Unicode to a
2565// Windows console.
2566size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2567 const HANDLE console = _get_console_handle(stream);
2568
2569 // If there is an associated Win32 console, write to it specially,
2570 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002571 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002572 return _console_fwrite(ptr, size, nmemb, stream, console);
2573 } else {
2574 // If fwrite is a macro, undefine it, so we can call the real
2575 // C Runtime API.
2576#pragma push_macro("fwrite")
2577#undef fwrite
2578 return fwrite(ptr, size, nmemb, stream);
2579#pragma pop_macro("fwrite")
2580 }
2581}
2582
2583// Version of fopen() that takes a UTF-8 filename and can access a file with
2584// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002585FILE* adb_fopen(const char* path, const char* mode) {
2586 std::wstring path_wide;
2587 if (!android::base::UTF8ToWide(path, &path_wide)) {
2588 return nullptr;
2589 }
2590
2591 std::wstring mode_wide;
2592 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2593 return nullptr;
2594 }
2595
2596 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002597}
2598
Spencer Lowe6ae5732015-09-08 17:13:04 -07002599// Return a lowercase version of the argument. Uses C Runtime tolower() on
2600// each byte which is not UTF-8 aware, and theoretically uses the current C
2601// Runtime locale (which in practice is not changed, so this becomes a ASCII
2602// conversion).
2603static std::string ToLower(const std::string& anycase) {
2604 // copy string
2605 std::string str(anycase);
2606 // transform the copy
2607 std::transform(str.begin(), str.end(), str.begin(), tolower);
2608 return str;
2609}
2610
2611extern "C" int main(int argc, char** argv);
2612
2613// Link with -municode to cause this wmain() to be used as the program
2614// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2615// regular main() with UTF-8 args.
2616extern "C" int wmain(int argc, wchar_t **argv) {
2617 // Convert args from UTF-16 to UTF-8 and pass that to main().
2618 NarrowArgs narrow_args(argc, argv);
2619 return main(argc, narrow_args.data());
2620}
2621
Spencer Lowcf4ff642015-05-11 01:08:48 -07002622// Shadow UTF-8 environment variable name/value pairs that are created from
2623// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002624// currently updated if putenv, setenv, unsetenv are called. Note that no
2625// thread synchronization is done, but we're called early enough in
2626// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002627static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002628
2629// Make sure that shadow UTF-8 environment variables are setup.
2630static void _ensure_env_setup() {
2631 // If some name/value pairs exist, then we've already done the setup below.
2632 if (g_environ_utf8.size() != 0) {
2633 return;
2634 }
2635
Spencer Lowe6ae5732015-09-08 17:13:04 -07002636 if (_wenviron == nullptr) {
2637 // If _wenviron is null, then -municode probably wasn't used. That
2638 // linker flag will cause the entry point to setup _wenviron. It will
2639 // also require an implementation of wmain() (which we provide above).
Elliott Hughes4679a392018-10-19 13:59:44 -07002640 LOG(FATAL) << "_wenviron is not set, did you link with -municode?";
Spencer Lowe6ae5732015-09-08 17:13:04 -07002641 }
2642
Spencer Lowcf4ff642015-05-11 01:08:48 -07002643 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2644 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2645 // to use the D() macro here because that tracing only works if the
2646 // ADB_TRACE environment variable is setup, but that env var can't be read
2647 // until this code completes.
2648 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2649 wchar_t* const equal = wcschr(*env, L'=');
2650 if (equal == nullptr) {
2651 // Malformed environment variable with no equal sign. Shouldn't
2652 // really happen, but we should be resilient to this.
2653 continue;
2654 }
2655
Spencer Lowd21dc822015-11-12 15:20:15 -08002656 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2657 // var because the program might never even read this particular variable.
2658 std::string name_utf8;
2659 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2660 continue;
2661 }
2662
Spencer Lowe6ae5732015-09-08 17:13:04 -07002663 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002664 name_utf8 = ToLower(name_utf8);
2665
2666 std::string value_utf8;
2667 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2668 continue;
2669 }
2670
2671 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002672
Spencer Lowe6ae5732015-09-08 17:13:04 -07002673 // Don't overwrite a previus env var with the same name. In reality,
2674 // the system probably won't let two env vars with the same name exist
2675 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002676 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002677 }
2678}
2679
2680// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002681// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002682char* adb_getenv(const char* name) {
2683 _ensure_env_setup();
2684
Spencer Lowe6ae5732015-09-08 17:13:04 -07002685 // Case-insensitive search by searching for lowercase name in a map of
2686 // lowercase names.
2687 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002688 if (it == g_environ_utf8.end()) {
2689 return nullptr;
2690 }
2691
2692 return it->second;
2693}
2694
2695// Version of getcwd() that returns the current working directory in UTF-8.
2696char* adb_getcwd(char* buf, int size) {
2697 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2698 if (wbuf == nullptr) {
2699 return nullptr;
2700 }
2701
Spencer Lowd21dc822015-11-12 15:20:15 -08002702 std::string buf_utf8;
2703 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002704 free(wbuf);
2705 wbuf = nullptr;
2706
Spencer Lowd21dc822015-11-12 15:20:15 -08002707 if (!narrow_result) {
2708 return nullptr;
2709 }
2710
Spencer Lowcf4ff642015-05-11 01:08:48 -07002711 // If size was specified, make sure all the chars will fit.
2712 if (size != 0) {
2713 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2714 errno = ERANGE;
2715 return nullptr;
2716 }
2717 }
2718
2719 // If buf was not specified, allocate storage.
2720 if (buf == nullptr) {
2721 if (size == 0) {
2722 size = buf_utf8.length() + 1;
2723 }
2724 buf = reinterpret_cast<char*>(malloc(size));
2725 if (buf == nullptr) {
2726 return nullptr;
2727 }
2728 }
2729
2730 // Destination buffer was allocated with enough space, or we've already
2731 // checked an existing buffer size for enough space.
2732 strcpy(buf, buf_utf8.c_str());
2733
2734 return buf;
2735}
Spencer Low50beee32018-09-03 16:03:22 -07002736
2737// The SetThreadDescription API was brought in version 1607 of Windows 10.
2738typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);
2739
2740// Based on PlatformThread::SetName() from
2741// https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc
2742int adb_thread_setname(const std::string& name) {
2743 // The SetThreadDescription API works even if no debugger is attached.
2744 auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(
2745 ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
2746 if (set_thread_description_func) {
2747 std::wstring name_wide;
2748 if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) {
2749 return errno;
2750 }
2751 set_thread_description_func(::GetCurrentThread(), name_wide.c_str());
2752 }
2753
2754 // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions.
2755 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017
2756
2757 return 0;
2758}