blob: d587589800170c65cb0bee7e04e79256cc6250eb [file] [log] [blame]
Dan Albert33134262015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070030#include <mutex>
Spencer Low5200c662015-07-30 23:07:55 -070031#include <string>
Josh Gao0f29cbc2018-12-12 16:12:28 -080032#include <string_view>
Spencer Lowcf4ff642015-05-11 01:08:48 -070033#include <unordered_map>
Josh Gao3777d2e2016-02-16 17:34:53 -080034#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070035
Elliott Hughesd48dbd82015-07-24 11:35:40 -070036#include <cutils/sockets.h>
37
David Pursell5f787ed2016-01-27 08:52:53 -080038#include <android-base/errors.h>
Elliott Hughes4679a392018-10-19 13:59:44 -070039#include <android-base/file.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080040#include <android-base/logging.h>
Josh Gao116aa0a2018-04-05 17:55:25 -070041#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080042#include <android-base/stringprintf.h>
43#include <android-base/strings.h>
44#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070045
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046#include "adb.h"
Josh Gao3777d2e2016-02-16 17:34:53 -080047#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080048
Josh Gao116aa0a2018-04-05 17:55:25 -070049#include "sysdeps/uio.h"
50
Elliott Hughesa2f2e562015-04-16 16:47:02 -070051/* forward declarations */
52
53typedef const struct FHClassRec_* FHClass;
54typedef struct FHRec_* FH;
Elliott Hughesa2f2e562015-04-16 16:47:02 -070055
56typedef struct FHClassRec_ {
57 void (*_fh_init)(FH);
58 int (*_fh_close)(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070059 int64_t (*_fh_lseek)(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070060 int (*_fh_read)(FH, void*, int);
61 int (*_fh_write)(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070062 int (*_fh_writev)(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070063} FHClassRec;
64
65static void _fh_file_init(FH);
66static int _fh_file_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070067static int64_t _fh_file_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070068static int _fh_file_read(FH, void*, int);
69static int _fh_file_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070070static int _fh_file_writev(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070071
72static const FHClassRec _fh_file_class = {
73 _fh_file_init,
74 _fh_file_close,
75 _fh_file_lseek,
76 _fh_file_read,
77 _fh_file_write,
Josh Gao116aa0a2018-04-05 17:55:25 -070078 _fh_file_writev,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070079};
80
81static void _fh_socket_init(FH);
82static int _fh_socket_close(FH);
Elliott Hughescabfc3d2018-09-20 13:59:49 -070083static int64_t _fh_socket_lseek(FH, int64_t, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070084static int _fh_socket_read(FH, void*, int);
85static int _fh_socket_write(FH, const void*, int);
Josh Gao116aa0a2018-04-05 17:55:25 -070086static int _fh_socket_writev(FH, const adb_iovec*, int);
Elliott Hughesa2f2e562015-04-16 16:47:02 -070087
88static const FHClassRec _fh_socket_class = {
89 _fh_socket_init,
90 _fh_socket_close,
91 _fh_socket_lseek,
92 _fh_socket_read,
93 _fh_socket_write,
Josh Gao116aa0a2018-04-05 17:55:25 -070094 _fh_socket_writev,
Elliott Hughesa2f2e562015-04-16 16:47:02 -070095};
96
Pirama Arumuga Nainar29e3dd82018-08-08 10:33:24 -070097#if defined(assert)
98#undef assert
99#endif
100
Spencer Low2122c7a2015-08-26 18:46:09 -0700101void handle_deleter::operator()(HANDLE h) {
102 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
103 // implying that NULL is a valid handle, but this is probably impossible.
104 // Other APIs like CreateEvent() are documented to return NULL on error,
105 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
106 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
107 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
108 // only need to check for INVALID_HANDLE_VALUE.
109 if (h != INVALID_HANDLE_VALUE) {
110 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700111 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800112 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700113 }
114 }
115}
116
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800117/**************************************************************************/
118/**************************************************************************/
119/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800120/***** common file descriptor handling *****/
121/***** *****/
122/**************************************************************************/
123/**************************************************************************/
124
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800125typedef struct FHRec_
126{
127 FHClass clazz;
128 int used;
129 int eof;
130 union {
131 HANDLE handle;
132 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800133 } u;
134
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800135 char name[32];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800136} FHRec;
137
138#define fh_handle u.handle
139#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800140
Josh Gaob6232b92016-02-17 16:45:39 -0800141#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700142#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800143
Josh Gao0cd3ae12016-09-21 12:37:10 -0700144static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800145static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700146static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800147
148static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700149_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800150{
151 FH f;
152
153 fd -= WIN32_FH_BASE;
154
Spencer Lowc3211552015-07-24 15:38:19 -0700155 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700156 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700157 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800158 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700159 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800160 }
161
162 f = &_win32_fhs[fd];
163
164 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700165 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700166 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800167 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700168 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800169 }
170
171 return f;
172}
173
174
175static int
176_fh_to_int( FH f )
177{
178 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
179 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
180
181 return -1;
182}
183
184static FH
185_fh_alloc( FHClass clazz )
186{
Yi Kongaed415c2018-07-13 18:15:16 -0700187 FH f = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188
Josh Gao0cd3ae12016-09-21 12:37:10 -0700189 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800190
Josh Gaob6232b92016-02-17 16:45:39 -0800191 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
Yi Kongaed415c2018-07-13 18:15:16 -0700192 if (_win32_fhs[i].clazz == nullptr) {
Josh Gaob6232b92016-02-17 16:45:39 -0800193 f = &_win32_fhs[i];
194 _win32_fh_next = i + 1;
Josh Gao0cd3ae12016-09-21 12:37:10 -0700195 f->clazz = clazz;
196 f->used = 1;
197 f->eof = 0;
198 f->name[0] = '\0';
199 clazz->_fh_init(f);
200 return f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201 }
202 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700203
204 D("_fh_alloc: no more free file descriptors");
205 errno = EMFILE; // Too many open files
206 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800207}
208
209
210static int
211_fh_close( FH f )
212{
Spencer Lowc3211552015-07-24 15:38:19 -0700213 // Use lock so that closing only happens once and so that _fh_alloc can't
214 // allocate a FH that we're in the middle of closing.
Josh Gao0cd3ae12016-09-21 12:37:10 -0700215 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800216
217 int offset = f - _win32_fhs;
218 if (_win32_fh_next > offset) {
219 _win32_fh_next = offset;
220 }
221
Spencer Lowc3211552015-07-24 15:38:19 -0700222 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800223 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700224 f->name[0] = '\0';
225 f->eof = 0;
226 f->used = 0;
Yi Kongaed415c2018-07-13 18:15:16 -0700227 f->clazz = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800228 }
229 return 0;
230}
231
Spencer Low5200c662015-07-30 23:07:55 -0700232// Deleter for unique_fh.
233class fh_deleter {
234 public:
235 void operator()(struct FHRec_* fh) {
236 // We're called from a destructor and destructors should not overwrite
237 // errno because callers may do:
238 // errno = EBLAH;
239 // return -1; // calls destructor, which should not overwrite errno
240 const int saved_errno = errno;
241 _fh_close(fh);
242 errno = saved_errno;
243 }
244};
245
246// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
247typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
248
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800249/**************************************************************************/
250/**************************************************************************/
251/***** *****/
252/***** file-based descriptor handling *****/
253/***** *****/
254/**************************************************************************/
255/**************************************************************************/
256
Josh Gao116aa0a2018-04-05 17:55:25 -0700257static void _fh_file_init(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 f->fh_handle = INVALID_HANDLE_VALUE;
259}
260
Josh Gao116aa0a2018-04-05 17:55:25 -0700261static int _fh_file_close(FH f) {
262 CloseHandle(f->fh_handle);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800263 f->fh_handle = INVALID_HANDLE_VALUE;
264 return 0;
265}
266
Josh Gao116aa0a2018-04-05 17:55:25 -0700267static int _fh_file_read(FH f, void* buf, int len) {
268 DWORD read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800269
Yi Kongaed415c2018-07-13 18:15:16 -0700270 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700271 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272 errno = EIO;
273 return -1;
274 } else if (read_bytes < (DWORD)len) {
275 f->eof = 1;
276 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700277 return read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800278}
279
Josh Gao116aa0a2018-04-05 17:55:25 -0700280static int _fh_file_write(FH f, const void* buf, int len) {
281 DWORD wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800282
Yi Kongaed415c2018-07-13 18:15:16 -0700283 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700284 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800285 errno = EIO;
286 return -1;
287 } else if (wrote_bytes < (DWORD)len) {
288 f->eof = 1;
289 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700290 return wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800291}
292
Josh Gao116aa0a2018-04-05 17:55:25 -0700293static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
294 if (iovcnt <= 0) {
295 errno = EINVAL;
296 return -1;
297 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800298
Josh Gao116aa0a2018-04-05 17:55:25 -0700299 DWORD wrote_bytes = 0;
300
301 for (int i = 0; i < iovcnt; ++i) {
302 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
303 if (rc == -1) {
304 return wrote_bytes > 0 ? wrote_bytes : -1;
305 } else if (rc == 0) {
306 return wrote_bytes;
307 }
308
309 wrote_bytes += rc;
310
311 if (static_cast<size_t>(rc) < iov[i].iov_len) {
312 return wrote_bytes;
313 }
314 }
315
316 return wrote_bytes;
317}
318
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700319static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700320 DWORD method;
Josh Gao116aa0a2018-04-05 17:55:25 -0700321 switch (origin) {
322 case SEEK_SET:
323 method = FILE_BEGIN;
324 break;
325 case SEEK_CUR:
326 method = FILE_CURRENT;
327 break;
328 case SEEK_END:
329 method = FILE_END;
330 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800331 default:
332 errno = EINVAL;
333 return -1;
334 }
335
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700336 LARGE_INTEGER li = {.QuadPart = pos};
337 if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800338 errno = EIO;
339 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800340 }
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700341 f->eof = 0;
342 return li.QuadPart;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800343}
344
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800345/**************************************************************************/
346/**************************************************************************/
347/***** *****/
348/***** file-based descriptor handling *****/
349/***** *****/
350/**************************************************************************/
351/**************************************************************************/
352
Josh Gao64a63ac2018-04-05 18:09:02 -0700353int adb_open(const char* path, int options) {
354 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800355
Josh Gao64a63ac2018-04-05 18:09:02 -0700356 DWORD desiredAccess = 0;
357 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800358
359 switch (options) {
360 case O_RDONLY:
361 desiredAccess = GENERIC_READ;
362 break;
363 case O_WRONLY:
364 desiredAccess = GENERIC_WRITE;
365 break;
366 case O_RDWR:
367 desiredAccess = GENERIC_READ | GENERIC_WRITE;
368 break;
369 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700370 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800371 errno = EINVAL;
372 return -1;
373 }
374
Josh Gao64a63ac2018-04-05 18:09:02 -0700375 f = _fh_alloc(&_fh_file_class);
376 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800377 return -1;
378 }
379
Spencer Lowd21dc822015-11-12 15:20:15 -0800380 std::wstring path_wide;
381 if (!android::base::UTF8ToWide(path, &path_wide)) {
382 return -1;
383 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700384 f->fh_handle =
Yi Kongaed415c2018-07-13 18:15:16 -0700385 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800386
Josh Gao64a63ac2018-04-05 18:09:02 -0700387 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700388 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800389 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700390 D("adb_open: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700391 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800392 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700393 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800394 errno = ENOENT;
395 return -1;
396
397 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700398 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800399 errno = ENOTDIR;
400 return -1;
401
402 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800403 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800404 errno = ENOENT;
405 return -1;
406 }
407 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800408
Josh Gao64a63ac2018-04-05 18:09:02 -0700409 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
410 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800411 return _fh_to_int(f);
412}
413
414/* ignore mode on Win32 */
Josh Gao64a63ac2018-04-05 18:09:02 -0700415int adb_creat(const char* path, int mode) {
416 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800417
Josh Gao64a63ac2018-04-05 18:09:02 -0700418 f = _fh_alloc(&_fh_file_class);
419 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800420 return -1;
421 }
422
Spencer Lowd21dc822015-11-12 15:20:15 -0800423 std::wstring path_wide;
424 if (!android::base::UTF8ToWide(path, &path_wide)) {
425 return -1;
426 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700427 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
Yi Kongaed415c2018-07-13 18:15:16 -0700428 nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429
Josh Gao64a63ac2018-04-05 18:09:02 -0700430 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700431 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800432 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700433 D("adb_creat: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700434 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800435 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700436 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800437 errno = ENOENT;
438 return -1;
439
440 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700441 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800442 errno = ENOTDIR;
443 return -1;
444
445 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800446 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800447 errno = ENOENT;
448 return -1;
449 }
450 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700451 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
452 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800453 return _fh_to_int(f);
454}
455
Josh Gao116aa0a2018-04-05 17:55:25 -0700456int adb_read(int fd, void* buf, int len) {
457 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800458
Yi Kongaed415c2018-07-13 18:15:16 -0700459 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700460 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800461 return -1;
462 }
463
Josh Gao116aa0a2018-04-05 17:55:25 -0700464 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800465}
466
Josh Gao116aa0a2018-04-05 17:55:25 -0700467int adb_write(int fd, const void* buf, int len) {
468 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800469
Yi Kongaed415c2018-07-13 18:15:16 -0700470 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700471 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800472 return -1;
473 }
474
475 return f->clazz->_fh_write(f, buf, len);
476}
477
Josh Gao116aa0a2018-04-05 17:55:25 -0700478ssize_t adb_writev(int fd, const adb_iovec* iov, int iovcnt) {
479 FH f = _fh_from_int(fd, __func__);
480
Yi Kongaed415c2018-07-13 18:15:16 -0700481 if (f == nullptr) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700482 errno = EBADF;
483 return -1;
484 }
485
486 return f->clazz->_fh_writev(f, iov, iovcnt);
487}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800488
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700489int64_t adb_lseek(int fd, int64_t pos, int where) {
Josh Gao64a63ac2018-04-05 18:09:02 -0700490 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700492 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493 return -1;
494 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800495 return f->clazz->_fh_lseek(f, pos, where);
496}
497
Josh Gao64a63ac2018-04-05 18:09:02 -0700498int adb_close(int fd) {
499 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500
501 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700502 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800503 return -1;
504 }
505
Josh Gao64a63ac2018-04-05 18:09:02 -0700506 D("adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507 _fh_close(f);
508 return 0;
509}
510
511/**************************************************************************/
512/**************************************************************************/
513/***** *****/
514/***** socket-based file descriptors *****/
515/***** *****/
516/**************************************************************************/
517/**************************************************************************/
518
Spencer Lowf055c192015-01-25 14:40:16 -0800519#undef setsockopt
520
Spencer Low5200c662015-07-30 23:07:55 -0700521static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700522 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
523 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gaoa3577e12016-12-05 13:24:48 -0800524 // are mapped to strings by adb_strerror().
Spencer Low5200c662015-07-30 23:07:55 -0700525 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700527 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
528 // case WSAEINTR: errno = EINTR; break;
529 case WSAEFAULT: errno = EFAULT; break;
530 case WSAEINVAL: errno = EINVAL; break;
531 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700532 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
533 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
534 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800535 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700536 case WSAENOTSOCK: errno = ENOTSOCK; break;
537 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
538 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
539 case WSAENETDOWN: errno = ENETDOWN; break;
540 case WSAENETRESET: errno = ENETRESET; break;
541 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
542 // to use EPIPE for these situations and there are some callers that look
543 // for EPIPE.
544 case WSAECONNABORTED: errno = EPIPE; break;
545 case WSAECONNRESET: errno = ECONNRESET; break;
546 case WSAENOBUFS: errno = ENOBUFS; break;
547 case WSAENOTCONN: errno = ENOTCONN; break;
548 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
549 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
550 // considerations: Reportedly send() can return zero on timeout, and POSIX
551 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
552 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
553 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800555 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700556 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700557 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558 }
559}
560
Josh Gao3777d2e2016-02-16 17:34:53 -0800561extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
562 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
563 int skipped = 0;
564 std::vector<WSAPOLLFD> sockets;
565 std::vector<adb_pollfd*> original;
Josh Gao05fb45b2018-03-29 12:34:28 -0700566
Josh Gao3777d2e2016-02-16 17:34:53 -0800567 for (size_t i = 0; i < nfds; ++i) {
568 FH fh = _fh_from_int(fds[i].fd, __func__);
569 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
570 D("adb_poll received bad FD %d", fds[i].fd);
571 fds[i].revents = POLLNVAL;
572 ++skipped;
573 } else {
574 WSAPOLLFD wsapollfd = {
575 .fd = fh->u.socket,
576 .events = static_cast<short>(fds[i].events)
577 };
578 sockets.push_back(wsapollfd);
579 original.push_back(&fds[i]);
580 }
Spencer Low5200c662015-07-30 23:07:55 -0700581 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800582
583 if (sockets.empty()) {
584 return skipped;
585 }
586
Josh Gao05fb45b2018-03-29 12:34:28 -0700587 // If we have any invalid FDs in our FD set, make sure to return immediately.
588 if (skipped > 0) {
589 timeout = 0;
590 }
591
Josh Gao3777d2e2016-02-16 17:34:53 -0800592 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
593 if (result == SOCKET_ERROR) {
594 _socket_set_errno(WSAGetLastError());
595 return -1;
596 }
597
598 // Map the results back onto the original set.
599 for (size_t i = 0; i < sockets.size(); ++i) {
600 original[i]->revents = sockets[i].revents;
601 }
602
Josh Gao05fb45b2018-03-29 12:34:28 -0700603 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gao3777d2e2016-02-16 17:34:53 -0800604 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
605 // to do. Ignore its result and calculate the proper return value.
606 result = 0;
607 for (size_t i = 0; i < nfds; ++i) {
608 if (fds[i].revents != 0) {
609 ++result;
610 }
611 }
612 return result;
613}
614
615static void _fh_socket_init(FH f) {
616 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800617}
618
Josh Gao116aa0a2018-04-05 17:55:25 -0700619static int _fh_socket_close(FH f) {
Spencer Low5200c662015-07-30 23:07:55 -0700620 if (f->fh_socket != INVALID_SOCKET) {
621 /* gently tell any peer that we're closing the socket */
622 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
623 // If the socket is not connected, this returns an error. We want to
624 // minimize logging spam, so don't log these errors for now.
625#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700626 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800627 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700628#endif
629 }
630 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800631 // Don't set errno here, since adb_close will ignore it.
632 const DWORD err = WSAGetLastError();
633 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700634 }
635 f->fh_socket = INVALID_SOCKET;
636 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637 return 0;
638}
639
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700640static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800641 errno = EPIPE;
642 return -1;
643}
644
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700645static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700646 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800647 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700648 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700649 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
650 // that to reduce spam and confusion.
651 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700652 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800653 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700654 }
Spencer Low5200c662015-07-30 23:07:55 -0700655 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800656 result = -1;
657 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700658 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800659}
660
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700661static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700662 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800663 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700664 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700665 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
666 // that to reduce spam and confusion.
667 if (err != WSAEWOULDBLOCK) {
668 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800669 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700670 }
Spencer Low5200c662015-07-30 23:07:55 -0700671 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800672 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700673 } else {
674 // According to https://code.google.com/p/chromium/issues/detail?id=27870
675 // Winsock Layered Service Providers may cause this.
Josh Gao116aa0a2018-04-05 17:55:25 -0700676 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
677 << result << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800678 }
679 return result;
680}
681
Josh Gao116aa0a2018-04-05 17:55:25 -0700682// Make sure that adb_iovec is compatible with WSABUF.
683static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
684static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
685static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
686
687static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
688static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
689
690static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
691 if (iovcnt <= 0) {
692 errno = EINVAL;
693 return -1;
694 }
695
696 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
697 DWORD bytes_written = 0;
698 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
699 if (result == SOCKET_ERROR) {
700 const DWORD err = WSAGetLastError();
701 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
702 // that to reduce spam and confusion.
703 if (err != WSAEWOULDBLOCK) {
704 D("send fd %d failed: %s", _fh_to_int(f),
705 android::base::SystemErrorCodeToString(err).c_str());
706 }
707 _socket_set_errno(err);
708 result = -1;
709 }
710 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
711 return static_cast<int>(bytes_written);
712}
713
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800714/**************************************************************************/
715/**************************************************************************/
716/***** *****/
717/***** replacement for libs/cutils/socket_xxxx.c *****/
718/***** *****/
719/**************************************************************************/
720/**************************************************************************/
721
Spencer Low14022c22018-08-10 16:20:57 -0700722static void _init_winsock() {
Josh Gao2e93df22018-04-05 18:10:03 -0700723 static std::once_flag once;
724 std::call_once(once, []() {
725 WSADATA wsaData;
726 int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800727 if (rc != 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -0700728 LOG(FATAL) << "could not initialize Winsock: "
729 << android::base::SystemErrorCodeToString(rc);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800730 }
Spencer Low87e97ee2015-08-12 18:19:16 -0700731
732 // Note that we do not call atexit() to register WSACleanup to be called
733 // at normal process termination because:
734 // 1) When exit() is called, there are still threads actively using
735 // Winsock because we don't cleanly shutdown all threads, so it
736 // doesn't make sense to call WSACleanup() and may cause problems
737 // with those threads.
738 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
739 // calls WSACleanup() which tries to unload a DLL, which tries to
740 // grab the LoaderLock. This conflicts with the device_poll_thread
741 // which holds the LoaderLock because AdbWinApi.dll calls
742 // setupapi.dll which tries to load wintrust.dll which tries to load
743 // crypt32.dll which calls atexit() which tries to acquire the C
744 // Runtime lock that the other thread holds.
Josh Gao2e93df22018-04-05 18:10:03 -0700745 });
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800746}
747
Spencer Low677fb432015-09-29 15:05:29 -0700748// Map a socket type to an explicit socket protocol instead of using the socket
749// protocol of 0. Explicit socket protocols are used by most apps and we should
750// do the same to reduce the chance of exercising uncommon code-paths that might
751// have problems or that might load different Winsock service providers that
752// have problems.
753static int GetSocketProtocolFromSocketType(int type) {
754 switch (type) {
755 case SOCK_STREAM:
756 return IPPROTO_TCP;
757 case SOCK_DGRAM:
758 return IPPROTO_UDP;
759 default:
760 LOG(FATAL) << "Unknown socket type: " << type;
761 return 0;
762 }
763}
764
Spencer Low5200c662015-07-30 23:07:55 -0700765int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800767 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800768
Josh Gao6487e742016-02-18 13:43:55 -0800769 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700770 if (!f) {
771 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800772 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700773 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800774
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800775 memset(&addr, 0, sizeof(addr));
776 addr.sin_family = AF_INET;
777 addr.sin_port = htons(port);
778 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
779
Spencer Low677fb432015-09-29 15:05:29 -0700780 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800781 if (s == INVALID_SOCKET) {
782 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700783 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800784 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700785 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800786 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700787 return -1;
788 }
789 f->fh_socket = s;
790
Josh Gao6487e742016-02-18 13:43:55 -0800791 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700792 // Save err just in case inet_ntoa() or ntohs() changes the last error.
793 const DWORD err = WSAGetLastError();
794 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800795 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
796 android::base::SystemErrorCodeToString(err).c_str());
797 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
798 error->c_str());
799 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800800 return -1;
801 }
802
Spencer Low5200c662015-07-30 23:07:55 -0700803 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800804 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
805 port);
806 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700807 f.release();
808 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800809}
810
Spencer Low5200c662015-07-30 23:07:55 -0700811// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800812static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800813 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800814 SOCKET s;
815 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800816
Josh Gao6487e742016-02-18 13:43:55 -0800817 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800818 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700819 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820 return -1;
821 }
822
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800823 memset(&addr, 0, sizeof(addr));
824 addr.sin_family = AF_INET;
825 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700826 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800827
Spencer Low5200c662015-07-30 23:07:55 -0700828 // TODO: Consider using dual-stack socket that can simultaneously listen on
829 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700830 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700831 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800832 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700833 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800834 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700835 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800836 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700837 return -1;
838 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800839
840 f->fh_socket = s;
841
Spencer Lowbf7c6052015-08-11 16:45:32 -0700842 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
843 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800845 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
846 const DWORD err = WSAGetLastError();
847 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
848 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700849 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800850 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700851 return -1;
852 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853
Josh Gao6487e742016-02-18 13:43:55 -0800854 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700855 // Save err just in case inet_ntoa() or ntohs() changes the last error.
856 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800857 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
858 ntohs(addr.sin_port),
859 android::base::SystemErrorCodeToString(err).c_str());
860 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
861 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800862 return -1;
863 }
864 if (type == SOCK_STREAM) {
Josh Gaobf243a62018-03-20 14:25:03 -0700865 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800866 const DWORD err = WSAGetLastError();
867 *error = android::base::StringPrintf(
868 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
869 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
870 error->c_str());
871 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800872 return -1;
873 }
874 }
Spencer Low5200c662015-07-30 23:07:55 -0700875 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800876 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
877 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
878 port);
879 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700880 f.release();
881 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800882}
883
Spencer Low5200c662015-07-30 23:07:55 -0700884int network_loopback_server(int port, int type, std::string* error) {
885 return _network_server(port, type, INADDR_LOOPBACK, error);
886}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800887
Spencer Low5200c662015-07-30 23:07:55 -0700888int network_inaddr_any_server(int port, int type, std::string* error) {
889 return _network_server(port, type, INADDR_ANY, error);
890}
891
892int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
893 unique_fh f(_fh_alloc(&_fh_socket_class));
894 if (!f) {
895 *error = strerror(errno);
896 return -1;
897 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800898
Spencer Low5200c662015-07-30 23:07:55 -0700899 struct addrinfo hints;
900 memset(&hints, 0, sizeof(hints));
901 hints.ai_family = AF_UNSPEC;
902 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700903 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700904
905 char port_str[16];
906 snprintf(port_str, sizeof(port_str), "%d", port);
907
908 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700909
910#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800911// TODO: When the Android SDK tools increases the Windows system
912// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700913#else
Josh Gao6487e742016-02-18 13:43:55 -0800914// Otherwise, keep using getaddrinfo(), or do runtime API detection
915// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700916#endif
Spencer Low5200c662015-07-30 23:07:55 -0700917 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800918 const DWORD err = WSAGetLastError();
919 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
920 host.c_str(), port_str,
921 android::base::SystemErrorCodeToString(err).c_str());
922
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700923 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800924 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800925 return -1;
926 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700927 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700928 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800929
Spencer Low5200c662015-07-30 23:07:55 -0700930 // TODO: Try all the addresses if there's more than one? This just uses
931 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
932 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800933 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
934 if (s == INVALID_SOCKET) {
935 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700936 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800937 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700938 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800939 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800940 return -1;
941 }
942 f->fh_socket = s;
943
Spencer Low5200c662015-07-30 23:07:55 -0700944 // TODO: Implement timeouts for Windows. Seems like the default in theory
945 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800946 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700947 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800948 const DWORD err = WSAGetLastError();
949 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
950 android::base::SystemErrorCodeToString(err).c_str());
951 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
952 port_str, error->c_str());
953 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800954 return -1;
955 }
956
Spencer Low5200c662015-07-30 23:07:55 -0700957 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800958 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
959 port);
960 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
961 fd);
Spencer Low5200c662015-07-30 23:07:55 -0700962 f.release();
963 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800964}
965
Josh Gao64a63ac2018-04-05 18:09:02 -0700966int adb_register_socket(SOCKET s) {
967 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin2fe9b602016-09-21 14:03:39 -0700968 f->fh_socket = s;
969 return _fh_to_int(f);
970}
971
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800972#undef accept
Josh Gao64a63ac2018-04-05 18:09:02 -0700973int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t* addrlen) {
974 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200975
Josh Gao64a63ac2018-04-05 18:09:02 -0700976 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700977 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -0700978 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800979 return -1;
980 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200981
Josh Gao64a63ac2018-04-05 18:09:02 -0700982 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800983 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -0700984 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
985 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800986 return -1;
987 }
988
Josh Gao64a63ac2018-04-05 18:09:02 -0700989 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800990 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700991 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -0700992 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd
993 << " failed: " + android::base::SystemErrorCodeToString(err);
994 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800995 return -1;
996 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200997
Spencer Low5200c662015-07-30 23:07:55 -0700998 const int fd = _fh_to_int(fh.get());
Josh Gao64a63ac2018-04-05 18:09:02 -0700999 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
1000 D("adb_socket_accept on fd %d returns fd %d", serverfd, fd);
Spencer Low5200c662015-07-30 23:07:55 -07001001 fh.release();
Josh Gao64a63ac2018-04-05 18:09:02 -07001002 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001003}
1004
Josh Gao64a63ac2018-04-05 18:09:02 -07001005int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) {
1006 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001007
Josh Gao64a63ac2018-04-05 18:09:02 -07001008 if (!fh || fh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001009 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001010 errno = EBADF;
1011 return -1;
1012 }
Spencer Low677fb432015-09-29 15:05:29 -07001013
1014 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1015 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1016 // auto-tuning.
1017
Josh Gao64a63ac2018-04-05 18:09:02 -07001018 int result =
1019 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1020 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001021 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -07001022 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd, level,
1023 optname, android::base::SystemErrorCodeToString(err).c_str());
1024 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -07001025 result = -1;
1026 }
1027 return result;
1028}
1029
Josh Gao3777d2e2016-02-16 17:34:53 -08001030int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1031 FH fh = _fh_from_int(fd, __func__);
1032
1033 if (!fh || fh->clazz != &_fh_socket_class) {
1034 D("adb_getsockname: invalid fd %d", fd);
1035 errno = EBADF;
1036 return -1;
1037 }
1038
Josh Gao3726a012017-03-30 13:04:35 -07001039 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001040 if (result == SOCKET_ERROR) {
1041 const DWORD err = WSAGetLastError();
1042 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1043 android::base::SystemErrorCodeToString(err).c_str());
1044 _socket_set_errno(err);
1045 result = -1;
1046 }
1047 return result;
1048}
Spencer Low5200c662015-07-30 23:07:55 -07001049
David Purselleaae97e2016-04-07 11:25:48 -07001050int adb_socket_get_local_port(int fd) {
1051 sockaddr_storage addr_storage;
1052 socklen_t addr_len = sizeof(addr_storage);
1053
1054 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1055 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1056 return -1;
1057 }
1058
1059 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1060 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1061 errno = ECONNABORTED;
1062 return -1;
1063 }
1064
1065 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1066}
1067
Josh Gao2e1e7892018-03-23 13:03:28 -07001068int adb_shutdown(int fd, int direction) {
1069 FH f = _fh_from_int(fd, __func__);
Spencer Low5200c662015-07-30 23:07:55 -07001070
1071 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001072 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001073 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001074 return -1;
1075 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001076
Josh Gao2e1e7892018-03-23 13:03:28 -07001077 D("adb_shutdown: %s", f->name);
1078 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001079 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001080 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001081 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001082 _socket_set_errno(err);
1083 return -1;
1084 }
1085 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001086}
1087
Josh Gao3777d2e2016-02-16 17:34:53 -08001088// Emulate socketpair(2) by binding and connecting to a socket.
1089int adb_socketpair(int sv[2]) {
1090 int server = -1;
1091 int client = -1;
1092 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001093 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001094 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001095
Josh Gao3777d2e2016-02-16 17:34:53 -08001096 server = network_loopback_server(0, SOCK_STREAM, &error);
1097 if (server < 0) {
1098 D("adb_socketpair: failed to create server: %s", error.c_str());
1099 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001100 }
1101
David Purselleaae97e2016-04-07 11:25:48 -07001102 local_port = adb_socket_get_local_port(server);
1103 if (local_port < 0) {
1104 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001105 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001106 }
David Purselleaae97e2016-04-07 11:25:48 -07001107 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001108
David Purselleaae97e2016-04-07 11:25:48 -07001109 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001110 if (client < 0) {
1111 D("adb_socketpair: failed to connect client: %s", error.c_str());
1112 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001113 }
1114
Josh Gao3726a012017-03-30 13:04:35 -07001115 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gao3777d2e2016-02-16 17:34:53 -08001116 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001117 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001118 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001119 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001120 adb_close(server);
1121 sv[0] = client;
1122 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001123 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001124
Josh Gao3777d2e2016-02-16 17:34:53 -08001125fail:
1126 if (server >= 0) {
1127 adb_close(server);
1128 }
1129 if (client >= 0) {
1130 adb_close(client);
1131 }
1132 if (accepted >= 0) {
1133 adb_close(accepted);
1134 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001135 return -1;
1136}
1137
Josh Gao3777d2e2016-02-16 17:34:53 -08001138bool set_file_block_mode(int fd, bool block) {
1139 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001140
Josh Gao3777d2e2016-02-16 17:34:53 -08001141 if (!fh || !fh->used) {
1142 errno = EBADF;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001143 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001144 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001145 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001146
Josh Gao3777d2e2016-02-16 17:34:53 -08001147 if (fh->clazz == &_fh_socket_class) {
1148 u_long x = !block;
1149 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001150 int error = WSAGetLastError();
1151 _socket_set_errno(error);
1152 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001153 return false;
1154 }
1155 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001156 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001157 errno = ENOTSOCK;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001158 D("Setting nonblocking on non-socket %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001159 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001160 }
1161}
1162
David Pursellbfd95032016-02-22 14:27:23 -08001163bool set_tcp_keepalive(int fd, int interval_sec) {
1164 FH fh = _fh_from_int(fd, __func__);
1165
1166 if (!fh || fh->clazz != &_fh_socket_class) {
1167 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1168 errno = EBADF;
1169 return false;
1170 }
1171
1172 tcp_keepalive keepalive;
1173 keepalive.onoff = (interval_sec > 0);
1174 keepalive.keepalivetime = interval_sec * 1000;
1175 keepalive.keepaliveinterval = interval_sec * 1000;
1176
1177 DWORD bytes_returned = 0;
1178 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1179 &bytes_returned, nullptr, nullptr) != 0) {
1180 const DWORD err = WSAGetLastError();
1181 D("set_tcp_keepalive(%d) failed: %s", fd,
1182 android::base::SystemErrorCodeToString(err).c_str());
1183 _socket_set_errno(err);
1184 return false;
1185 }
1186
1187 return true;
1188}
1189
Spencer Low50184062015-03-01 15:06:21 -08001190/**************************************************************************/
1191/**************************************************************************/
1192/***** *****/
1193/***** Console Window Terminal Emulation *****/
1194/***** *****/
1195/**************************************************************************/
1196/**************************************************************************/
1197
1198// This reads input from a Win32 console window and translates it into Unix
1199// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1200// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1201// is emulated instead of xterm because it is probably more popular than xterm:
1202// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1203// supports modern fonts, etc. It seems best to emulate the terminal that most
1204// Android developers use because they'll fix apps (the shell, etc.) to keep
1205// working with that terminal's emulation.
1206//
1207// The point of this emulation is not to be perfect or to solve all issues with
1208// console windows on Windows, but to be better than the original code which
1209// just called read() (which called ReadFile(), which called ReadConsoleA())
1210// which did not support Ctrl-C, tab completion, shell input line editing
1211// keys, server echo, and more.
1212//
1213// This implementation reconfigures the console with SetConsoleMode(), then
1214// calls ReadConsoleInput() to get raw input which it remaps to Unix
1215// terminal-style sequences which is returned via unix_read() which is used
1216// by the 'adb shell' command.
1217//
1218// Code organization:
1219//
David Pursellc5b8ad82015-10-28 14:29:51 -07001220// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001221// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1222// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1223// * _console_read() is the main code of the emulation.
1224
David Pursellc5b8ad82015-10-28 14:29:51 -07001225// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1226// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1227// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1228static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1229 // First check isatty(); this is very fast and eliminates most non-console
1230 // FDs, but returns 1 for both consoles and character devices like NUL.
1231#pragma push_macro("isatty")
1232#undef isatty
1233 if (!isatty(fd)) {
1234 return nullptr;
1235 }
1236#pragma pop_macro("isatty")
1237
1238 // To differentiate between character devices and consoles we need to get
1239 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1240 // GENERIC_READ permissions.
1241 const intptr_t intptr_handle = _get_osfhandle(fd);
1242 if (intptr_handle == -1) {
1243 return nullptr;
1244 }
1245 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1246 DWORD temp_mode = 0;
1247 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1248 return nullptr;
1249 }
1250
1251 return handle;
1252}
1253
1254// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1255static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001256 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1257 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001258 const int fd = fileno(stream);
1259 if (fd < 0) {
1260 return nullptr;
1261 }
1262 return _get_console_handle(fd);
1263}
1264
1265int unix_isatty(int fd) {
1266 return _get_console_handle(fd) ? 1 : 0;
1267}
Spencer Low50184062015-03-01 15:06:21 -08001268
Spencer Low32762f42015-11-10 19:17:16 -08001269// Get the next KEY_EVENT_RECORD that should be processed.
1270static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001271 for (;;) {
1272 DWORD read_count = 0;
1273 memset(input_record, 0, sizeof(*input_record));
1274 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001275 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001276 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001277 errno = EIO;
1278 return false;
1279 }
1280
1281 if (read_count == 0) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001282 LOG(FATAL) << "ReadConsoleInputA returned 0";
Spencer Low50184062015-03-01 15:06:21 -08001283 }
1284
1285 if (read_count != 1) { // should be impossible
Elliott Hughes4679a392018-10-19 13:59:44 -07001286 LOG(FATAL) << "ReadConsoleInputA did not return one input record";
Spencer Low50184062015-03-01 15:06:21 -08001287 }
1288
Spencer Low2e02dc62015-11-07 17:34:39 -08001289 // If the console window is resized, emulate SIGWINCH by breaking out
1290 // of read() with errno == EINTR. Note that there is no event on
1291 // vertical resize because we don't give the console our own custom
1292 // screen buffer (with CreateConsoleScreenBuffer() +
1293 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1294 // supports scrollback, but doesn't seem to raise an event for vertical
1295 // window resize.
1296 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1297 errno = EINTR;
1298 return false;
1299 }
1300
Spencer Low50184062015-03-01 15:06:21 -08001301 if ((input_record->EventType == KEY_EVENT) &&
1302 (input_record->Event.KeyEvent.bKeyDown)) {
1303 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
Elliott Hughes4679a392018-10-19 13:59:44 -07001304 LOG(FATAL) << "ReadConsoleInputA returned a key event with zero repeat count";
Spencer Low50184062015-03-01 15:06:21 -08001305 }
1306
1307 // Got an interesting INPUT_RECORD, so return
1308 return true;
1309 }
1310 }
1311}
1312
Spencer Low50184062015-03-01 15:06:21 -08001313static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1314 return (control_key_state & SHIFT_PRESSED) != 0;
1315}
1316
1317static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1318 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1319}
1320
1321static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1322 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1323}
1324
1325static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1326 return (control_key_state & NUMLOCK_ON) != 0;
1327}
1328
1329static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1330 return (control_key_state & CAPSLOCK_ON) != 0;
1331}
1332
1333static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1334 return (control_key_state & ENHANCED_KEY) != 0;
1335}
1336
1337// Constants from MSDN for ToAscii().
1338static const BYTE TOASCII_KEY_OFF = 0x00;
1339static const BYTE TOASCII_KEY_DOWN = 0x80;
1340static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1341
1342// Given a key event, ignore a modifier key and return the character that was
1343// entered without the modifier. Writes to *ch and returns the number of bytes
1344// written.
1345static size_t _get_char_ignoring_modifier(char* const ch,
1346 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1347 const WORD modifier) {
1348 // If there is no character from Windows, try ignoring the specified
1349 // modifier and look for a character. Note that if AltGr is being used,
1350 // there will be a character from Windows.
1351 if (key_event->uChar.AsciiChar == '\0') {
1352 // Note that we read the control key state from the passed in argument
1353 // instead of from key_event since the argument has been normalized.
1354 if (((modifier == VK_SHIFT) &&
1355 _is_shift_pressed(control_key_state)) ||
1356 ((modifier == VK_CONTROL) &&
1357 _is_ctrl_pressed(control_key_state)) ||
1358 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1359
1360 BYTE key_state[256] = {0};
1361 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1362 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1363 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1364 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1365 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1366 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1367 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1368 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1369
1370 // cause this modifier to be ignored
1371 key_state[modifier] = TOASCII_KEY_OFF;
1372
1373 WORD translated = 0;
1374 if (ToAscii(key_event->wVirtualKeyCode,
1375 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1376 // Ignoring the modifier, we found a character.
1377 *ch = (CHAR)translated;
1378 return 1;
1379 }
1380 }
1381 }
1382
1383 // Just use whatever Windows told us originally.
1384 *ch = key_event->uChar.AsciiChar;
1385
1386 // If the character from Windows is NULL, return a size of zero.
1387 return (*ch == '\0') ? 0 : 1;
1388}
1389
1390// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1391// but taking into account the shift key. This is because for a sequence like
1392// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1393// we want to find the character ')'.
1394//
1395// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1396// because it is the default key-sequence to switch the input language.
1397// This is configurable in the Region and Language control panel.
1398static __inline__ size_t _get_non_control_char(char* const ch,
1399 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1400 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1401 VK_CONTROL);
1402}
1403
1404// Get without Alt.
1405static __inline__ size_t _get_non_alt_char(char* const ch,
1406 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1407 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1408 VK_MENU);
1409}
1410
1411// Ignore the control key, find the character from Windows, and apply any
1412// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1413// *pch and returns number of bytes written.
1414static size_t _get_control_character(char* const pch,
1415 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1416 const size_t len = _get_non_control_char(pch, key_event,
1417 control_key_state);
1418
1419 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1420 char ch = *pch;
1421 switch (ch) {
1422 case '2':
1423 case '@':
1424 case '`':
1425 ch = '\0';
1426 break;
1427 case '3':
1428 case '[':
1429 case '{':
1430 ch = '\x1b';
1431 break;
1432 case '4':
1433 case '\\':
1434 case '|':
1435 ch = '\x1c';
1436 break;
1437 case '5':
1438 case ']':
1439 case '}':
1440 ch = '\x1d';
1441 break;
1442 case '6':
1443 case '^':
1444 case '~':
1445 ch = '\x1e';
1446 break;
1447 case '7':
1448 case '-':
1449 case '_':
1450 ch = '\x1f';
1451 break;
1452 case '8':
1453 ch = '\x7f';
1454 break;
1455 case '/':
1456 if (!_is_alt_pressed(control_key_state)) {
1457 ch = '\x1f';
1458 }
1459 break;
1460 case '?':
1461 if (!_is_alt_pressed(control_key_state)) {
1462 ch = '\x7f';
1463 }
1464 break;
1465 }
1466 *pch = ch;
1467 }
1468
1469 return len;
1470}
1471
1472static DWORD _normalize_altgr_control_key_state(
1473 const KEY_EVENT_RECORD* const key_event) {
1474 DWORD control_key_state = key_event->dwControlKeyState;
1475
1476 // If we're in an AltGr situation where the AltGr key is down (depending on
1477 // the keyboard layout, that might be the physical right alt key which
1478 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1479 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1480 // a character (which indicates that there was an AltGr mapping), then act
1481 // as if alt and control are not really down for the purposes of modifiers.
1482 // This makes it so that if the user with, say, a German keyboard layout
1483 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1484 // output the key and we don't see the Alt and Ctrl keys.
1485 if (_is_ctrl_pressed(control_key_state) &&
1486 _is_alt_pressed(control_key_state)
1487 && (key_event->uChar.AsciiChar != '\0')) {
1488 // Try to remove as few bits as possible to improve our chances of
1489 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1490 // Left-Alt + Right-Ctrl + AltGr.
1491 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1492 // Remove Right-Alt.
1493 control_key_state &= ~RIGHT_ALT_PRESSED;
1494 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1495 // pressed, Left-Ctrl is almost always set, except if the user
1496 // presses Right-Ctrl, then AltGr (in that specific order) for
1497 // whatever reason. At any rate, make sure the bit is not set.
1498 control_key_state &= ~LEFT_CTRL_PRESSED;
1499 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1500 // Remove Left-Alt.
1501 control_key_state &= ~LEFT_ALT_PRESSED;
1502 // Whichever Ctrl key is down, remove it from the state. We only
1503 // remove one key, to improve our chances of detecting the
1504 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1505 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1506 // Remove Left-Ctrl.
1507 control_key_state &= ~LEFT_CTRL_PRESSED;
1508 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1509 // Remove Right-Ctrl.
1510 control_key_state &= ~RIGHT_CTRL_PRESSED;
1511 }
1512 }
1513
1514 // Note that this logic isn't 100% perfect because Windows doesn't
1515 // allow us to detect all combinations because a physical AltGr key
1516 // press shows up as two bits, plus some combinations are ambiguous
1517 // about what is actually physically pressed.
1518 }
1519
1520 return control_key_state;
1521}
1522
1523// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1524// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1525// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1526// appropriately.
1527static DWORD _normalize_keypad_control_key_state(const WORD vk,
1528 const DWORD control_key_state) {
1529 if (!_is_numlock_on(control_key_state)) {
1530 return control_key_state;
1531 }
1532 if (!_is_enhanced_key(control_key_state)) {
1533 switch (vk) {
1534 case VK_INSERT: // 0
1535 case VK_DELETE: // .
1536 case VK_END: // 1
1537 case VK_DOWN: // 2
1538 case VK_NEXT: // 3
1539 case VK_LEFT: // 4
1540 case VK_CLEAR: // 5
1541 case VK_RIGHT: // 6
1542 case VK_HOME: // 7
1543 case VK_UP: // 8
1544 case VK_PRIOR: // 9
1545 return control_key_state | SHIFT_PRESSED;
1546 }
1547 }
1548
1549 return control_key_state;
1550}
1551
1552static const char* _get_keypad_sequence(const DWORD control_key_state,
1553 const char* const normal, const char* const shifted) {
1554 if (_is_shift_pressed(control_key_state)) {
1555 // Shift is pressed and NumLock is off
1556 return shifted;
1557 } else {
1558 // Shift is not pressed and NumLock is off, or,
1559 // Shift is pressed and NumLock is on, in which case we want the
1560 // NumLock and Shift to neutralize each other, thus, we want the normal
1561 // sequence.
1562 return normal;
1563 }
1564 // If Shift is not pressed and NumLock is on, a different virtual key code
1565 // is returned by Windows, which can be taken care of by a different case
1566 // statement in _console_read().
1567}
1568
1569// Write sequence to buf and return the number of bytes written.
1570static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1571 DWORD control_key_state, const char* const normal) {
1572 // Copy the base sequence into buf.
1573 const size_t len = strlen(normal);
1574 memcpy(buf, normal, len);
1575
1576 int code = 0;
1577
1578 control_key_state = _normalize_keypad_control_key_state(vk,
1579 control_key_state);
1580
1581 if (_is_shift_pressed(control_key_state)) {
1582 code |= 0x1;
1583 }
1584 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1585 code |= 0x2;
1586 }
1587 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1588 code |= 0x4;
1589 }
1590 // If some modifier was held down, then we need to insert the modifier code
1591 if (code != 0) {
1592 if (len == 0) {
1593 // Should be impossible because caller should pass a string of
1594 // non-zero length.
1595 return 0;
1596 }
1597 size_t index = len - 1;
1598 const char lastChar = buf[index];
1599 if (lastChar != '~') {
1600 buf[index++] = '1';
1601 }
1602 buf[index++] = ';'; // modifier separator
1603 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1604 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1605 buf[index++] = '1' + code;
1606 buf[index++] = lastChar; // move ~ (or other last char) to the end
1607 return index;
1608 }
1609 return len;
1610}
1611
1612// Write sequence to buf and return the number of bytes written.
1613static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1614 const DWORD control_key_state, const char* const normal,
1615 const char shifted) {
1616 if (_is_shift_pressed(control_key_state)) {
1617 // Shift is pressed and NumLock is off
1618 if (shifted != '\0') {
1619 buf[0] = shifted;
1620 return sizeof(buf[0]);
1621 } else {
1622 return 0;
1623 }
1624 } else {
1625 // Shift is not pressed and NumLock is off, or,
1626 // Shift is pressed and NumLock is on, in which case we want the
1627 // NumLock and Shift to neutralize each other, thus, we want the normal
1628 // sequence.
1629 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1630 }
1631 // If Shift is not pressed and NumLock is on, a different virtual key code
1632 // is returned by Windows, which can be taken care of by a different case
1633 // statement in _console_read().
1634}
1635
1636// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1637// Standard German. Figure this out at runtime so we know what to output for
1638// Shift-VK_DELETE.
1639static char _get_decimal_char() {
1640 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1641}
1642
1643// Prefix the len bytes in buf with the escape character, and then return the
1644// new buffer length.
1645size_t _escape_prefix(char* const buf, const size_t len) {
1646 // If nothing to prefix, don't do anything. We might be called with
1647 // len == 0, if alt was held down with a dead key which produced nothing.
1648 if (len == 0) {
1649 return 0;
1650 }
1651
1652 memmove(&buf[1], buf, len);
1653 buf[0] = '\x1b';
1654 return len + 1;
1655}
1656
Spencer Low32762f42015-11-10 19:17:16 -08001657// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001658static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001659
1660// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1661// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001662static int _console_read(const HANDLE console, void* buf, size_t len) {
1663 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001664 // Read of zero bytes should not block waiting for something from the console.
1665 if (len == 0) {
1666 return 0;
1667 }
1668
1669 // Flush as much as possible from input buffer.
1670 if (!g_console_input_buffer.empty()) {
1671 const int bytes_read = std::min(len, g_console_input_buffer.size());
1672 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1673 const auto begin = g_console_input_buffer.begin();
1674 g_console_input_buffer.erase(begin, begin + bytes_read);
1675 return bytes_read;
1676 }
1677
1678 // Read from the actual console. This may block until input.
1679 INPUT_RECORD input_record;
1680 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001681 return -1;
1682 }
1683
Spencer Low32762f42015-11-10 19:17:16 -08001684 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001685 const WORD vk = key_event->wVirtualKeyCode;
1686 const CHAR ch = key_event->uChar.AsciiChar;
1687 const DWORD control_key_state = _normalize_altgr_control_key_state(
1688 key_event);
1689
1690 // The following emulation code should write the output sequence to
1691 // either seqstr or to seqbuf and seqbuflen.
Yi Kongaed415c2018-07-13 18:15:16 -07001692 const char* seqstr = nullptr; // NULL terminated C-string
Spencer Low50184062015-03-01 15:06:21 -08001693 // Enough space for max sequence string below, plus modifiers and/or
1694 // escape prefix.
1695 char seqbuf[16];
1696 size_t seqbuflen = 0; // Space used in seqbuf.
1697
1698#define MATCH(vk, normal) \
1699 case (vk): \
1700 { \
1701 seqstr = (normal); \
1702 } \
1703 break;
1704
1705 // Modifier keys should affect the output sequence.
1706#define MATCH_MODIFIER(vk, normal) \
1707 case (vk): \
1708 { \
1709 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1710 control_key_state, (normal)); \
1711 } \
1712 break;
1713
1714 // The shift key should affect the output sequence.
1715#define MATCH_KEYPAD(vk, normal, shifted) \
1716 case (vk): \
1717 { \
1718 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1719 (shifted)); \
1720 } \
1721 break;
1722
1723 // The shift key and other modifier keys should affect the output
1724 // sequence.
1725#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1726 case (vk): \
1727 { \
1728 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1729 control_key_state, (normal), (shifted)); \
1730 } \
1731 break;
1732
1733#define ESC "\x1b"
1734#define CSI ESC "["
1735#define SS3 ESC "O"
1736
1737 // Only support normal mode, not application mode.
1738
1739 // Enhanced keys:
1740 // * 6-pack: insert, delete, home, end, page up, page down
1741 // * cursor keys: up, down, right, left
1742 // * keypad: divide, enter
1743 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1744 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1745 if (_is_enhanced_key(control_key_state)) {
1746 switch (vk) {
1747 case VK_RETURN: // Enter key on keypad
1748 if (_is_ctrl_pressed(control_key_state)) {
1749 seqstr = "\n";
1750 } else {
1751 seqstr = "\r";
1752 }
1753 break;
1754
1755 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1756 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1757
1758 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1759 // will be fixed soon to match xterm which sends CSI "F" and
1760 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1761 MATCH(VK_END, CSI "F");
1762 MATCH(VK_HOME, CSI "H");
1763
1764 MATCH_MODIFIER(VK_LEFT, CSI "D");
1765 MATCH_MODIFIER(VK_UP, CSI "A");
1766 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1767 MATCH_MODIFIER(VK_DOWN, CSI "B");
1768
1769 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1770 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1771
1772 MATCH(VK_DIVIDE, "/");
1773 }
1774 } else { // Non-enhanced keys:
1775 switch (vk) {
1776 case VK_BACK: // backspace
1777 if (_is_alt_pressed(control_key_state)) {
1778 seqstr = ESC "\x7f";
1779 } else {
1780 seqstr = "\x7f";
1781 }
1782 break;
1783
1784 case VK_TAB:
1785 if (_is_shift_pressed(control_key_state)) {
1786 seqstr = CSI "Z";
1787 } else {
1788 seqstr = "\t";
1789 }
1790 break;
1791
1792 // Number 5 key in keypad when NumLock is off, or if NumLock is
1793 // on and Shift is down.
1794 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1795
1796 case VK_RETURN: // Enter key on main keyboard
1797 if (_is_alt_pressed(control_key_state)) {
1798 seqstr = ESC "\n";
1799 } else if (_is_ctrl_pressed(control_key_state)) {
1800 seqstr = "\n";
1801 } else {
1802 seqstr = "\r";
1803 }
1804 break;
1805
1806 // VK_ESCAPE: Don't do any special handling. The OS uses many
1807 // of the sequences with Escape and many of the remaining
1808 // sequences don't produce bKeyDown messages, only !bKeyDown
1809 // for whatever reason.
1810
1811 case VK_SPACE:
1812 if (_is_alt_pressed(control_key_state)) {
1813 seqstr = ESC " ";
1814 } else if (_is_ctrl_pressed(control_key_state)) {
1815 seqbuf[0] = '\0'; // NULL char
1816 seqbuflen = 1;
1817 } else {
1818 seqstr = " ";
1819 }
1820 break;
1821
1822 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1823 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1824
1825 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1826 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1827
1828 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1829 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1830 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1831 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1832
1833 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1834 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1835 _get_decimal_char());
1836
1837 case 0x30: // 0
1838 case 0x31: // 1
1839 case 0x39: // 9
1840 case VK_OEM_1: // ;:
1841 case VK_OEM_PLUS: // =+
1842 case VK_OEM_COMMA: // ,<
1843 case VK_OEM_PERIOD: // .>
1844 case VK_OEM_7: // '"
1845 case VK_OEM_102: // depends on keyboard, could be <> or \|
1846 case VK_OEM_2: // /?
1847 case VK_OEM_3: // `~
1848 case VK_OEM_4: // [{
1849 case VK_OEM_5: // \|
1850 case VK_OEM_6: // ]}
1851 {
1852 seqbuflen = _get_control_character(seqbuf, key_event,
1853 control_key_state);
1854
1855 if (_is_alt_pressed(control_key_state)) {
1856 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1857 }
1858 }
1859 break;
1860
1861 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001862 case 0x33: // 3
1863 case 0x34: // 4
1864 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001865 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001866 case 0x37: // 7
1867 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001868 case VK_OEM_MINUS: // -_
1869 {
1870 seqbuflen = _get_control_character(seqbuf, key_event,
1871 control_key_state);
1872
1873 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1874 // prefix with escape.
1875 if (_is_alt_pressed(control_key_state) &&
1876 !(_is_ctrl_pressed(control_key_state) &&
1877 !_is_shift_pressed(control_key_state))) {
1878 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1879 }
1880 }
1881 break;
1882
Spencer Low50184062015-03-01 15:06:21 -08001883 case 0x41: // a
1884 case 0x42: // b
1885 case 0x43: // c
1886 case 0x44: // d
1887 case 0x45: // e
1888 case 0x46: // f
1889 case 0x47: // g
1890 case 0x48: // h
1891 case 0x49: // i
1892 case 0x4a: // j
1893 case 0x4b: // k
1894 case 0x4c: // l
1895 case 0x4d: // m
1896 case 0x4e: // n
1897 case 0x4f: // o
1898 case 0x50: // p
1899 case 0x51: // q
1900 case 0x52: // r
1901 case 0x53: // s
1902 case 0x54: // t
1903 case 0x55: // u
1904 case 0x56: // v
1905 case 0x57: // w
1906 case 0x58: // x
1907 case 0x59: // y
1908 case 0x5a: // z
1909 {
1910 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1911 control_key_state);
1912
1913 // If Alt is pressed, then prefix with escape.
1914 if (_is_alt_pressed(control_key_state)) {
1915 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1916 }
1917 }
1918 break;
1919
1920 // These virtual key codes are generated by the keys on the
1921 // keypad *when NumLock is on* and *Shift is up*.
1922 MATCH(VK_NUMPAD0, "0");
1923 MATCH(VK_NUMPAD1, "1");
1924 MATCH(VK_NUMPAD2, "2");
1925 MATCH(VK_NUMPAD3, "3");
1926 MATCH(VK_NUMPAD4, "4");
1927 MATCH(VK_NUMPAD5, "5");
1928 MATCH(VK_NUMPAD6, "6");
1929 MATCH(VK_NUMPAD7, "7");
1930 MATCH(VK_NUMPAD8, "8");
1931 MATCH(VK_NUMPAD9, "9");
1932
1933 MATCH(VK_MULTIPLY, "*");
1934 MATCH(VK_ADD, "+");
1935 MATCH(VK_SUBTRACT, "-");
1936 // VK_DECIMAL is generated by the . key on the keypad *when
1937 // NumLock is on* and *Shift is up* and the sequence is not
1938 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1939 // Windows Security screen to come up).
1940 case VK_DECIMAL:
1941 // U.S. English uses '.', Germany German uses ','.
1942 seqbuflen = _get_non_control_char(seqbuf, key_event,
1943 control_key_state);
1944 break;
1945
1946 MATCH_MODIFIER(VK_F1, SS3 "P");
1947 MATCH_MODIFIER(VK_F2, SS3 "Q");
1948 MATCH_MODIFIER(VK_F3, SS3 "R");
1949 MATCH_MODIFIER(VK_F4, SS3 "S");
1950 MATCH_MODIFIER(VK_F5, CSI "15~");
1951 MATCH_MODIFIER(VK_F6, CSI "17~");
1952 MATCH_MODIFIER(VK_F7, CSI "18~");
1953 MATCH_MODIFIER(VK_F8, CSI "19~");
1954 MATCH_MODIFIER(VK_F9, CSI "20~");
1955 MATCH_MODIFIER(VK_F10, CSI "21~");
1956 MATCH_MODIFIER(VK_F11, CSI "23~");
1957 MATCH_MODIFIER(VK_F12, CSI "24~");
1958
1959 MATCH_MODIFIER(VK_F13, CSI "25~");
1960 MATCH_MODIFIER(VK_F14, CSI "26~");
1961 MATCH_MODIFIER(VK_F15, CSI "28~");
1962 MATCH_MODIFIER(VK_F16, CSI "29~");
1963 MATCH_MODIFIER(VK_F17, CSI "31~");
1964 MATCH_MODIFIER(VK_F18, CSI "32~");
1965 MATCH_MODIFIER(VK_F19, CSI "33~");
1966 MATCH_MODIFIER(VK_F20, CSI "34~");
1967
1968 // MATCH_MODIFIER(VK_F21, ???);
1969 // MATCH_MODIFIER(VK_F22, ???);
1970 // MATCH_MODIFIER(VK_F23, ???);
1971 // MATCH_MODIFIER(VK_F24, ???);
1972 }
1973 }
1974
1975#undef MATCH
1976#undef MATCH_MODIFIER
1977#undef MATCH_KEYPAD
1978#undef MATCH_MODIFIER_KEYPAD
1979#undef ESC
1980#undef CSI
1981#undef SS3
1982
1983 const char* out;
1984 size_t outlen;
1985
1986 // Check for output in any of:
1987 // * seqstr is set (and strlen can be used to determine the length).
1988 // * seqbuf and seqbuflen are set
1989 // Fallback to ch from Windows.
Yi Kongaed415c2018-07-13 18:15:16 -07001990 if (seqstr != nullptr) {
Spencer Low50184062015-03-01 15:06:21 -08001991 out = seqstr;
1992 outlen = strlen(seqstr);
1993 } else if (seqbuflen > 0) {
1994 out = seqbuf;
1995 outlen = seqbuflen;
1996 } else if (ch != '\0') {
1997 // Use whatever Windows told us it is.
1998 seqbuf[0] = ch;
1999 seqbuflen = 1;
2000 out = seqbuf;
2001 outlen = seqbuflen;
2002 } else {
2003 // No special handling for the virtual key code and Windows isn't
2004 // telling us a character code, then we don't know how to translate
2005 // the key press.
2006 //
2007 // Consume the input and 'continue' to cause us to get a new key
2008 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002009 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002010 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002011 continue;
2012 }
2013
Spencer Low32762f42015-11-10 19:17:16 -08002014 // put output wRepeatCount times into g_console_input_buffer
2015 while (key_event->wRepeatCount-- > 0) {
2016 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002017 }
2018
Spencer Low32762f42015-11-10 19:17:16 -08002019 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002020 }
2021}
2022
2023static DWORD _old_console_mode; // previous GetConsoleMode() result
2024static HANDLE _console_handle; // when set, console mode should be restored
2025
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002026void stdin_raw_init() {
2027 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002028 if (in == nullptr) {
2029 return;
2030 }
Spencer Low50184062015-03-01 15:06:21 -08002031
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002032 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2033 // calling the process Ctrl-C routine (configured by
2034 // SetConsoleCtrlHandler()).
2035 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2036 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2037 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002038 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2039 ENABLE_LINE_INPUT |
2040 ENABLE_ECHO_INPUT);
2041 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2042 new_console_mode |= ENABLE_WINDOW_INPUT;
2043
2044 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002045 // This really should not fail.
2046 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002047 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002048 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002049
2050 // Once this is set, it means that stdin has been configured for
2051 // reading from and that the old console mode should be restored later.
2052 _console_handle = in;
2053
2054 // Note that we don't need to configure C Runtime line-ending
2055 // translation because _console_read() does not call the C Runtime to
2056 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002057}
2058
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002059void stdin_raw_restore() {
Yi Kongaed415c2018-07-13 18:15:16 -07002060 if (_console_handle != nullptr) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002061 const HANDLE in = _console_handle;
Yi Kongaed415c2018-07-13 18:15:16 -07002062 _console_handle = nullptr; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002063
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002064 if (!SetConsoleMode(in, _old_console_mode)) {
2065 // This really should not fail.
2066 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002067 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002068 }
2069 }
2070}
2071
Spencer Low2e02dc62015-11-07 17:34:39 -08002072// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2073int unix_read_interruptible(int fd, void* buf, size_t len) {
Yi Kongaed415c2018-07-13 18:15:16 -07002074 if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) {
Spencer Low50184062015-03-01 15:06:21 -08002075 // If it is a request to read from stdin, and stdin_raw_init() has been
2076 // called, and it successfully configured the console, then read from
2077 // the console using Win32 console APIs and partially emulate a unix
2078 // terminal.
2079 return _console_read(_console_handle, buf, len);
2080 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002081 // On older versions of Windows (definitely 7, definitely not 10),
2082 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002083 // we need to limit the read size.
2084 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002085 len = 4096;
2086 }
Spencer Low50184062015-03-01 15:06:21 -08002087 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002088 // can do LF/CR translation (which is overridable with _setmode()).
2089 // Undefine the macro that is set in sysdeps.h which bans calls to
2090 // plain read() in favor of unix_read() or adb_read().
2091#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002092#undef read
2093 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002094#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002095 }
2096}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002097
2098/**************************************************************************/
2099/**************************************************************************/
2100/***** *****/
2101/***** Unicode support *****/
2102/***** *****/
2103/**************************************************************************/
2104/**************************************************************************/
2105
2106// This implements support for using files with Unicode filenames and for
2107// outputting Unicode text to a Win32 console window. This is inspired from
2108// http://utf8everywhere.org/.
2109//
2110// Background
2111// ----------
2112//
2113// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2114// filenames to APIs such as open(). This works because filenames are largely
2115// opaque 'cookies' (perhaps excluding path separators).
2116//
2117// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2118// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2119// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2120// CreateFile() API is really just a macro that adds the W/A based on whether
2121// the UNICODE preprocessor symbol is defined).
2122//
2123// Options
2124// -------
2125//
2126// Thus, to write a portable program, there are a few options:
2127//
2128// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2129// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2130// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2131// open() API.
2132//
2133// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2134// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2135// potentially touching a lot of code.
2136//
2137// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2138// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2139// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2140// or C Runtime API.
2141//
2142// The Choice
2143// ----------
2144//
Spencer Lowd21dc822015-11-12 15:20:15 -08002145// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2146// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002147// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002148// args that are passed to main() at the beginning of program startup. We also use
2149// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002150// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2151//
2152// Unicode console output
2153// ----------------------
2154//
2155// The way to output Unicode to a Win32 console window is to call
2156// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002157// such as Lucida Console or Consolas, and in the case of East Asian languages
2158// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2159// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2160// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002161//
2162// The problem is getting the C Runtime to make fprintf and related APIs call
2163// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2164// promising, but the various modes have issues:
2165//
2166// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2167// UTF-16 do not display properly.
2168// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2169// totally wrong.
2170// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2171// handler to be called (upon a later I/O call), aborting the process.
2172// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2173// to output nothing.
2174//
2175// So the only solution is to write our own adb_fprintf() that converts UTF-8
2176// to UTF-16 and then calls WriteConsoleW().
2177
2178
Spencer Lowcf4ff642015-05-11 01:08:48 -07002179// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2180// be passed to main().
2181NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2182 narrow_args = new char*[argc + 1];
2183
2184 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002185 std::string arg_narrow;
2186 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
Elliott Hughes4679a392018-10-19 13:59:44 -07002187 PLOG(FATAL) << "cannot convert argument from UTF-16 to UTF-8";
Spencer Lowd21dc822015-11-12 15:20:15 -08002188 }
2189 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002190 }
2191 narrow_args[argc] = nullptr; // terminate
2192}
2193
2194NarrowArgs::~NarrowArgs() {
2195 if (narrow_args != nullptr) {
2196 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2197 free(*argp);
2198 }
2199 delete[] narrow_args;
2200 narrow_args = nullptr;
2201 }
2202}
2203
Josh Gao0f29cbc2018-12-12 16:12:28 -08002204int unix_open(std::string_view path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002205 std::wstring path_wide;
Josh Gao0f29cbc2018-12-12 16:12:28 -08002206 if (!android::base::UTF8ToWide(path.data(), path.size(), &path_wide)) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002207 return -1;
2208 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002209 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002210 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002211 } else {
Josh Gao0f29cbc2018-12-12 16:12:28 -08002212 int mode;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002213 va_list args;
2214 va_start(args, options);
2215 mode = va_arg(args, int);
2216 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002217 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002218 }
2219}
2220
Spencer Lowcf4ff642015-05-11 01:08:48 -07002221// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002222DIR* adb_opendir(const char* path) {
2223 std::wstring path_wide;
2224 if (!android::base::UTF8ToWide(path, &path_wide)) {
2225 return nullptr;
2226 }
2227
Spencer Lowcf4ff642015-05-11 01:08:48 -07002228 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2229 // the fields, but right now all the callers treat the structure as
2230 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002231 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002232}
2233
2234// Version of readdir() that returns UTF-8 paths.
2235struct dirent* adb_readdir(DIR* dir) {
2236 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2237 struct _wdirent* const went = _wreaddir(wdir);
2238 if (went == nullptr) {
2239 return nullptr;
2240 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002241
Spencer Lowcf4ff642015-05-11 01:08:48 -07002242 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002243 std::string name_utf8;
2244 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2245 return nullptr;
2246 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002247
2248 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2249 // space for UTF-16 wchar_t's) with UTF-8 char's.
2250 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2251
2252 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2253 // Name too big to fit in existing buffer.
2254 errno = ENOMEM;
2255 return nullptr;
2256 }
2257
2258 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2259 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2260 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2261 // bigger than the caller expects because they expect a dirent structure
2262 // which has a smaller d_name field. Ignore this since the caller should be
2263 // resilient.
2264
2265 // Rewrite the UTF-16 d_name field to UTF-8.
2266 strcpy(ent->d_name, name_utf8.c_str());
2267
2268 return ent;
2269}
2270
2271// Version of closedir() to go with our version of adb_opendir().
2272int adb_closedir(DIR* dir) {
2273 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2274}
2275
2276// Version of unlink() that takes a UTF-8 path.
2277int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002278 std::wstring wpath;
2279 if (!android::base::UTF8ToWide(path, &wpath)) {
2280 return -1;
2281 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002282
2283 int rc = _wunlink(wpath.c_str());
2284
2285 if (rc == -1 && errno == EACCES) {
2286 /* unlink returns EACCES when the file is read-only, so we first */
2287 /* try to make it writable, then unlink again... */
2288 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2289 if (rc == 0)
2290 rc = _wunlink(wpath.c_str());
2291 }
2292 return rc;
2293}
2294
2295// Version of mkdir() that takes a UTF-8 path.
2296int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002297 std::wstring path_wide;
2298 if (!android::base::UTF8ToWide(path, &path_wide)) {
2299 return -1;
2300 }
2301
2302 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002303}
2304
2305// Version of utime() that takes a UTF-8 path.
2306int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002307 std::wstring path_wide;
2308 if (!android::base::UTF8ToWide(path, &path_wide)) {
2309 return -1;
2310 }
2311
Spencer Lowcf4ff642015-05-11 01:08:48 -07002312 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2313 "utimbuf and _utimbuf should be the same size because they both "
2314 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002315 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002316}
2317
2318// Version of chmod() that takes a UTF-8 path.
2319int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002320 std::wstring path_wide;
2321 if (!android::base::UTF8ToWide(path, &path_wide)) {
2322 return -1;
2323 }
2324
2325 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002326}
2327
Spencer Lowa30b79a2015-11-15 16:29:36 -08002328// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2329static inline size_t utf8_codepoint_len(uint8_t ch) {
2330 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2331}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002332
Spencer Lowa30b79a2015-11-15 16:29:36 -08002333namespace internal {
2334
2335// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2336// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2337// remaining_bytes.
2338size_t ParseCompleteUTF8(const char* const first, const char* const last,
2339 std::vector<char>* const remaining_bytes) {
2340 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2341 // Current_after points one byte past the current byte to be examined.
2342 for (const char* current_after = last; current_after != first; --current_after) {
2343 const char* const current = current_after - 1;
2344 const char ch = *current;
2345 const char kHighBit = 0x80u;
2346 const char kTwoHighestBits = 0xC0u;
2347 if ((ch & kHighBit) == 0) { // high bit not set
2348 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2349 // bytes with no leading byte, so return the entire buffer.
2350 break;
2351 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2352 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2353 const size_t bytes_available = last - current;
2354 if (bytes_available < utf8_codepoint_len(ch)) {
2355 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2356 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2357 // to remaining_bytes.
2358 remaining_bytes->insert(remaining_bytes->end(), current, last);
2359 return current - first;
2360 } else {
2361 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2362 // trailing bytes with no lead byte, so return the entire buffer.
2363 break;
2364 }
2365 } else {
2366 // Trailing byte, so keep going backwards looking for the lead byte.
2367 }
2368 }
2369
2370 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2371 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2372 // so that they can be processed.
2373 return last - first;
2374}
2375
2376}
2377
2378// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2379// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2380// This matches the behavior of Linux.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002381
2382// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2383static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2384 HANDLE console) {
Josh Gao0cd3ae12016-09-21 12:37:10 -07002385 static std::mutex& console_output_buffer_lock = *new std::mutex();
2386 static auto& console_output_buffer = *new std::vector<char>();
2387
Spencer Lowa30b79a2015-11-15 16:29:36 -08002388 const int saved_errno = errno;
2389 std::vector<char> combined_buffer;
2390
2391 // Complete UTF-8 sequences that should be immediately written to the console.
2392 const char* utf8;
2393 size_t utf8_size;
2394
Josh Gao0cd3ae12016-09-21 12:37:10 -07002395 {
2396 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2397 if (console_output_buffer.empty()) {
2398 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2399 // common case with plain ASCII), parse buf directly.
2400 utf8 = buf;
2401 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2402 } else {
2403 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2404 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2405 // combined_buffer, then parse it all together.
2406 combined_buffer.swap(console_output_buffer);
2407 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002408
Josh Gao0cd3ae12016-09-21 12:37:10 -07002409 utf8 = combined_buffer.data();
2410 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2411 &console_output_buffer);
2412 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002413 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002414
2415 std::wstring utf16;
2416
2417 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2418 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2419 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002420 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002421 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002422
2423 // Note that this does not do \n => \r\n translation because that
2424 // doesn't seem necessary for the Windows console. For the Windows
2425 // console \r moves to the beginning of the line and \n moves to a new
2426 // line.
2427
2428 // Flush any stream buffering so that our output is afterwards which
2429 // makes sense because our call is afterwards.
2430 (void)fflush(stream);
2431
2432 // Write UTF-16 to the console.
2433 DWORD written = 0;
Yi Kongaed415c2018-07-13 18:15:16 -07002434 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002435 errno = EIO;
2436 return -1;
2437 }
2438
Spencer Lowa30b79a2015-11-15 16:29:36 -08002439 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2440 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2441 // matches the Linux behavior.
2442 errno = saved_errno;
2443 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002444}
2445
2446// Function prototype because attributes cannot be placed on func definitions.
Elliott Hughesd8a4c602018-06-26 13:06:15 -07002447static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap)
2448 __attribute__((__format__(__printf__, 3, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002449
2450// Internal function to format a UTF-8 string and write it to a Win32 console.
2451// Returns -1 on error.
2452static int _console_vfprintf(const HANDLE console, FILE* stream,
2453 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002454 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002455 std::string output_utf8;
2456
2457 // Format the string.
2458 // This could throw std::bad_alloc.
2459 android::base::StringAppendV(&output_utf8, format, ap);
2460
Spencer Lowa30b79a2015-11-15 16:29:36 -08002461 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2462 console);
2463 if (result != -1) {
2464 errno = saved_errno;
2465 } else {
2466 // If -1 was returned, errno has been set.
2467 }
2468 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002469}
2470
2471// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2472// Windows console.
2473int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2474 const HANDLE console = _get_console_handle(stream);
2475
2476 // If there is an associated Win32 console, write to it specially,
2477 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002478 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002479 return _console_vfprintf(console, stream, format, ap);
2480 } else {
2481 // If vfprintf is a macro, undefine it, so we can call the real
2482 // C Runtime API.
2483#pragma push_macro("vfprintf")
2484#undef vfprintf
2485 return vfprintf(stream, format, ap);
2486#pragma pop_macro("vfprintf")
2487 }
2488}
2489
Spencer Lowa30b79a2015-11-15 16:29:36 -08002490// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2491int adb_vprintf(const char *format, va_list ap) {
2492 return adb_vfprintf(stdout, format, ap);
2493}
2494
Spencer Lowcf4ff642015-05-11 01:08:48 -07002495// Version of fprintf() that takes UTF-8 and can write Unicode to a
2496// Windows console.
2497int adb_fprintf(FILE *stream, const char *format, ...) {
2498 va_list ap;
2499 va_start(ap, format);
2500 const int result = adb_vfprintf(stream, format, ap);
2501 va_end(ap);
2502
2503 return result;
2504}
2505
2506// Version of printf() that takes UTF-8 and can write Unicode to a
2507// Windows console.
2508int adb_printf(const char *format, ...) {
2509 va_list ap;
2510 va_start(ap, format);
2511 const int result = adb_vfprintf(stdout, format, ap);
2512 va_end(ap);
2513
2514 return result;
2515}
2516
2517// Version of fputs() that takes UTF-8 and can write Unicode to a
2518// Windows console.
2519int adb_fputs(const char* buf, FILE* stream) {
2520 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2521 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002522 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002523 return adb_fprintf(stream, "%s", buf);
2524}
2525
2526// Version of fputc() that takes UTF-8 and can write Unicode to a
2527// Windows console.
2528int adb_fputc(int ch, FILE* stream) {
2529 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002530 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002531 return EOF;
2532 }
2533 // For success, fputc returns the char, cast to unsigned char, then to int.
2534 return static_cast<unsigned char>(ch);
2535}
2536
Spencer Lowa30b79a2015-11-15 16:29:36 -08002537// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2538int adb_putchar(int ch) {
2539 return adb_fputc(ch, stdout);
2540}
2541
2542// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2543int adb_puts(const char* buf) {
2544 // adb_printf returns -1 on error, which is conveniently the same as EOF
2545 // which puts (and hence adb_puts) should return on error.
2546 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2547 return adb_printf("%s\n", buf);
2548}
2549
Spencer Lowcf4ff642015-05-11 01:08:48 -07002550// Internal function to write UTF-8 to a Win32 console. Returns the number of
2551// items (of length size) written. On error, returns a short item count or 0.
2552static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2553 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002554 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2555 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002556 if (result == -1) {
2557 return 0;
2558 }
2559 return result / size;
2560}
2561
2562// Version of fwrite() that takes UTF-8 and can write Unicode to a
2563// Windows console.
2564size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2565 const HANDLE console = _get_console_handle(stream);
2566
2567 // If there is an associated Win32 console, write to it specially,
2568 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002569 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002570 return _console_fwrite(ptr, size, nmemb, stream, console);
2571 } else {
2572 // If fwrite is a macro, undefine it, so we can call the real
2573 // C Runtime API.
2574#pragma push_macro("fwrite")
2575#undef fwrite
2576 return fwrite(ptr, size, nmemb, stream);
2577#pragma pop_macro("fwrite")
2578 }
2579}
2580
2581// Version of fopen() that takes a UTF-8 filename and can access a file with
2582// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002583FILE* adb_fopen(const char* path, const char* mode) {
2584 std::wstring path_wide;
2585 if (!android::base::UTF8ToWide(path, &path_wide)) {
2586 return nullptr;
2587 }
2588
2589 std::wstring mode_wide;
2590 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2591 return nullptr;
2592 }
2593
2594 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002595}
2596
Spencer Lowe6ae5732015-09-08 17:13:04 -07002597// Return a lowercase version of the argument. Uses C Runtime tolower() on
2598// each byte which is not UTF-8 aware, and theoretically uses the current C
2599// Runtime locale (which in practice is not changed, so this becomes a ASCII
2600// conversion).
2601static std::string ToLower(const std::string& anycase) {
2602 // copy string
2603 std::string str(anycase);
2604 // transform the copy
2605 std::transform(str.begin(), str.end(), str.begin(), tolower);
2606 return str;
2607}
2608
2609extern "C" int main(int argc, char** argv);
2610
2611// Link with -municode to cause this wmain() to be used as the program
2612// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2613// regular main() with UTF-8 args.
2614extern "C" int wmain(int argc, wchar_t **argv) {
2615 // Convert args from UTF-16 to UTF-8 and pass that to main().
2616 NarrowArgs narrow_args(argc, argv);
2617 return main(argc, narrow_args.data());
2618}
2619
Spencer Lowcf4ff642015-05-11 01:08:48 -07002620// Shadow UTF-8 environment variable name/value pairs that are created from
Spencer Low14022c22018-08-10 16:20:57 -07002621// _wenviron by _init_env(). Note that this is not currently updated if putenv, setenv, unsetenv are
2622// called. Note that no thread synchronization is done, but we're called early enough in
Spencer Lowe347c1d2015-08-02 18:13:54 -07002623// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002624static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002625
Spencer Low14022c22018-08-10 16:20:57 -07002626// Setup shadow UTF-8 environment variables.
2627static void _init_env() {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002628 // If some name/value pairs exist, then we've already done the setup below.
2629 if (g_environ_utf8.size() != 0) {
2630 return;
2631 }
2632
Spencer Lowe6ae5732015-09-08 17:13:04 -07002633 if (_wenviron == nullptr) {
2634 // If _wenviron is null, then -municode probably wasn't used. That
2635 // linker flag will cause the entry point to setup _wenviron. It will
2636 // also require an implementation of wmain() (which we provide above).
Elliott Hughes4679a392018-10-19 13:59:44 -07002637 LOG(FATAL) << "_wenviron is not set, did you link with -municode?";
Spencer Lowe6ae5732015-09-08 17:13:04 -07002638 }
2639
Spencer Lowcf4ff642015-05-11 01:08:48 -07002640 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2641 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2642 // to use the D() macro here because that tracing only works if the
2643 // ADB_TRACE environment variable is setup, but that env var can't be read
2644 // until this code completes.
2645 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2646 wchar_t* const equal = wcschr(*env, L'=');
2647 if (equal == nullptr) {
2648 // Malformed environment variable with no equal sign. Shouldn't
2649 // really happen, but we should be resilient to this.
2650 continue;
2651 }
2652
Spencer Lowd21dc822015-11-12 15:20:15 -08002653 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2654 // var because the program might never even read this particular variable.
2655 std::string name_utf8;
2656 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2657 continue;
2658 }
2659
Spencer Lowe6ae5732015-09-08 17:13:04 -07002660 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002661 name_utf8 = ToLower(name_utf8);
2662
2663 std::string value_utf8;
2664 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2665 continue;
2666 }
2667
2668 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002669
Spencer Lowe6ae5732015-09-08 17:13:04 -07002670 // Don't overwrite a previus env var with the same name. In reality,
2671 // the system probably won't let two env vars with the same name exist
2672 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002673 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002674 }
2675}
2676
2677// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002678// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002679char* adb_getenv(const char* name) {
Spencer Lowe6ae5732015-09-08 17:13:04 -07002680 // Case-insensitive search by searching for lowercase name in a map of
2681 // lowercase names.
2682 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002683 if (it == g_environ_utf8.end()) {
2684 return nullptr;
2685 }
2686
2687 return it->second;
2688}
2689
2690// Version of getcwd() that returns the current working directory in UTF-8.
2691char* adb_getcwd(char* buf, int size) {
2692 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2693 if (wbuf == nullptr) {
2694 return nullptr;
2695 }
2696
Spencer Lowd21dc822015-11-12 15:20:15 -08002697 std::string buf_utf8;
2698 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002699 free(wbuf);
2700 wbuf = nullptr;
2701
Spencer Lowd21dc822015-11-12 15:20:15 -08002702 if (!narrow_result) {
2703 return nullptr;
2704 }
2705
Spencer Lowcf4ff642015-05-11 01:08:48 -07002706 // If size was specified, make sure all the chars will fit.
2707 if (size != 0) {
2708 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2709 errno = ERANGE;
2710 return nullptr;
2711 }
2712 }
2713
2714 // If buf was not specified, allocate storage.
2715 if (buf == nullptr) {
2716 if (size == 0) {
2717 size = buf_utf8.length() + 1;
2718 }
2719 buf = reinterpret_cast<char*>(malloc(size));
2720 if (buf == nullptr) {
2721 return nullptr;
2722 }
2723 }
2724
2725 // Destination buffer was allocated with enough space, or we've already
2726 // checked an existing buffer size for enough space.
2727 strcpy(buf, buf_utf8.c_str());
2728
2729 return buf;
2730}
Spencer Low50beee32018-09-03 16:03:22 -07002731
2732// The SetThreadDescription API was brought in version 1607 of Windows 10.
2733typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);
2734
2735// Based on PlatformThread::SetName() from
2736// https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc
2737int adb_thread_setname(const std::string& name) {
2738 // The SetThreadDescription API works even if no debugger is attached.
2739 auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(
2740 ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
2741 if (set_thread_description_func) {
2742 std::wstring name_wide;
2743 if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) {
2744 return errno;
2745 }
2746 set_thread_description_func(::GetCurrentThread(), name_wide.c_str());
2747 }
2748
2749 // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions.
2750 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017
2751
2752 return 0;
2753}
Spencer Low14022c22018-08-10 16:20:57 -07002754
2755#if !defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2756#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
2757#endif
2758
2759#if !defined(DISABLE_NEWLINE_AUTO_RETURN)
2760#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
2761#endif
2762
2763static void _init_console() {
2764 DWORD old_out_console_mode;
2765
2766 const HANDLE out = _get_console_handle(STDOUT_FILENO, &old_out_console_mode);
2767 if (out == nullptr) {
2768 return;
2769 }
2770
2771 // Try to use ENABLE_VIRTUAL_TERMINAL_PROCESSING on the output console to process virtual
2772 // terminal sequences on newer versions of Windows 10 and later.
2773 // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
2774 // On older OSes that don't support the flag, SetConsoleMode() will return an error.
2775 // ENABLE_VIRTUAL_TERMINAL_PROCESSING also solves a problem where the last column of the
2776 // console cannot be overwritten.
2777 //
2778 // Note that we don't use DISABLE_NEWLINE_AUTO_RETURN because it doesn't seem to be necessary.
2779 // If we use DISABLE_NEWLINE_AUTO_RETURN, _console_write_utf8() would need to be modified to
2780 // translate \n to \r\n.
2781 if (!SetConsoleMode(out, old_out_console_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
2782 return;
2783 }
2784
2785 // If SetConsoleMode() succeeded, the console supports virtual terminal processing, so we
2786 // should set the TERM env var to match so that it will be propagated to adbd on devices.
2787 //
2788 // Below's direct manipulation of env vars and not g_environ_utf8 assumes that _init_env() has
2789 // not yet been called. If this fails, _init_env() should be called after _init_console().
2790 if (g_environ_utf8.size() > 0) {
2791 LOG(FATAL) << "environment variables have already been converted to UTF-8";
2792 }
2793
2794#pragma push_macro("getenv")
2795#undef getenv
2796#pragma push_macro("putenv")
2797#undef putenv
2798 if (getenv("TERM") == nullptr) {
2799 // This is the same TERM value used by Gnome Terminal and the version of ssh included with
2800 // Windows.
2801 putenv("TERM=xterm-256color");
2802 }
2803#pragma pop_macro("putenv")
2804#pragma pop_macro("getenv")
2805}
2806
2807static bool _init_sysdeps() {
2808 // _init_console() depends on _init_env() not being called yet.
2809 _init_console();
2810 _init_env();
2811 _init_winsock();
2812 return true;
2813}
2814
2815static bool _sysdeps_init = _init_sysdeps();