blob: 0a08fbbd9a6a5135828efe765b3214bbcb0eb8b0 [file] [log] [blame]
Dan Albert33134262015-03-19 15:21:08 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG SYSDEPS
Dan Albert33134262015-03-19 15:21:08 -070018
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Lowe6ae5732015-09-08 17:13:04 -070028#include <algorithm>
Spencer Low5200c662015-07-30 23:07:55 -070029#include <memory>
Josh Gao0cd3ae12016-09-21 12:37:10 -070030#include <mutex>
Spencer Low5200c662015-07-30 23:07:55 -070031#include <string>
Spencer Lowcf4ff642015-05-11 01:08:48 -070032#include <unordered_map>
Josh Gao3777d2e2016-02-16 17:34:53 -080033#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070034
Elliott Hughesd48dbd82015-07-24 11:35:40 -070035#include <cutils/sockets.h>
36
David Pursell5f787ed2016-01-27 08:52:53 -080037#include <android-base/errors.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080038#include <android-base/logging.h>
Josh Gao116aa0a2018-04-05 17:55:25 -070039#include <android-base/macros.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080040#include <android-base/stringprintf.h>
41#include <android-base/strings.h>
42#include <android-base/utf8.h>
Spencer Low5200c662015-07-30 23:07:55 -070043
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080044#include "adb.h"
Josh Gao3777d2e2016-02-16 17:34:53 -080045#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080046
Josh Gao116aa0a2018-04-05 17:55:25 -070047#include "sysdeps/uio.h"
48
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080049extern void fatal(const char *fmt, ...);
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
Josh Gao56e9bb92016-01-15 15:17:37 -0800101#define assert(cond) \
102 do { \
103 if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \
104 } while (0)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800105
Spencer Low2122c7a2015-08-26 18:46:09 -0700106void handle_deleter::operator()(HANDLE h) {
107 // CreateFile() is documented to return INVALID_HANDLE_FILE on error,
108 // implying that NULL is a valid handle, but this is probably impossible.
109 // Other APIs like CreateEvent() are documented to return NULL on error,
110 // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also
111 // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE
112 // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we
113 // only need to check for INVALID_HANDLE_VALUE.
114 if (h != INVALID_HANDLE_VALUE) {
115 if (!CloseHandle(h)) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700116 D("CloseHandle(%p) failed: %s", h,
David Pursell5f787ed2016-01-27 08:52:53 -0800117 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low2122c7a2015-08-26 18:46:09 -0700118 }
119 }
120}
121
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800122/**************************************************************************/
123/**************************************************************************/
124/***** *****/
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800125/***** common file descriptor handling *****/
126/***** *****/
127/**************************************************************************/
128/**************************************************************************/
129
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800130typedef struct FHRec_
131{
132 FHClass clazz;
133 int used;
134 int eof;
135 union {
136 HANDLE handle;
137 SOCKET socket;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800138 } u;
139
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800140 char name[32];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800141} FHRec;
142
143#define fh_handle u.handle
144#define fh_socket u.socket
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800145
Josh Gaob6232b92016-02-17 16:45:39 -0800146#define WIN32_FH_BASE 2048
Josh Gaob31e1712016-04-18 11:09:28 -0700147#define WIN32_MAX_FHS 2048
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148
Josh Gao0cd3ae12016-09-21 12:37:10 -0700149static std::mutex& _win32_lock = *new std::mutex();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800150static FHRec _win32_fhs[ WIN32_MAX_FHS ];
Spencer Lowc3211552015-07-24 15:38:19 -0700151static int _win32_fh_next; // where to start search for free FHRec
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800152
153static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700154_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800155{
156 FH f;
157
158 fd -= WIN32_FH_BASE;
159
Spencer Lowc3211552015-07-24 15:38:19 -0700160 if (fd < 0 || fd >= WIN32_MAX_FHS) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700161 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700162 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800163 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700164 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800165 }
166
167 f = &_win32_fhs[fd];
168
169 if (f->used == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700170 D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE,
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700171 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800172 errno = EBADF;
Yi Kongaed415c2018-07-13 18:15:16 -0700173 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800174 }
175
176 return f;
177}
178
179
180static int
181_fh_to_int( FH f )
182{
183 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
184 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
185
186 return -1;
187}
188
189static FH
190_fh_alloc( FHClass clazz )
191{
Yi Kongaed415c2018-07-13 18:15:16 -0700192 FH f = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800193
Josh Gao0cd3ae12016-09-21 12:37:10 -0700194 std::lock_guard<std::mutex> lock(_win32_lock);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800195
Josh Gaob6232b92016-02-17 16:45:39 -0800196 for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) {
Yi Kongaed415c2018-07-13 18:15:16 -0700197 if (_win32_fhs[i].clazz == nullptr) {
Josh Gaob6232b92016-02-17 16:45:39 -0800198 f = &_win32_fhs[i];
199 _win32_fh_next = i + 1;
Josh Gao0cd3ae12016-09-21 12:37:10 -0700200 f->clazz = clazz;
201 f->used = 1;
202 f->eof = 0;
203 f->name[0] = '\0';
204 clazz->_fh_init(f);
205 return f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800206 }
207 }
Josh Gao0cd3ae12016-09-21 12:37:10 -0700208
209 D("_fh_alloc: no more free file descriptors");
210 errno = EMFILE; // Too many open files
211 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800212}
213
214
215static int
216_fh_close( FH f )
217{
Spencer Lowc3211552015-07-24 15:38:19 -0700218 // Use lock so that closing only happens once and so that _fh_alloc can't
219 // allocate a FH that we're in the middle of closing.
Josh Gao0cd3ae12016-09-21 12:37:10 -0700220 std::lock_guard<std::mutex> lock(_win32_lock);
Josh Gaob6232b92016-02-17 16:45:39 -0800221
222 int offset = f - _win32_fhs;
223 if (_win32_fh_next > offset) {
224 _win32_fh_next = offset;
225 }
226
Spencer Lowc3211552015-07-24 15:38:19 -0700227 if (f->used) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800228 f->clazz->_fh_close( f );
Spencer Lowc3211552015-07-24 15:38:19 -0700229 f->name[0] = '\0';
230 f->eof = 0;
231 f->used = 0;
Yi Kongaed415c2018-07-13 18:15:16 -0700232 f->clazz = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800233 }
234 return 0;
235}
236
Spencer Low5200c662015-07-30 23:07:55 -0700237// Deleter for unique_fh.
238class fh_deleter {
239 public:
240 void operator()(struct FHRec_* fh) {
241 // We're called from a destructor and destructors should not overwrite
242 // errno because callers may do:
243 // errno = EBLAH;
244 // return -1; // calls destructor, which should not overwrite errno
245 const int saved_errno = errno;
246 _fh_close(fh);
247 errno = saved_errno;
248 }
249};
250
251// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
252typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
253
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800254/**************************************************************************/
255/**************************************************************************/
256/***** *****/
257/***** file-based descriptor handling *****/
258/***** *****/
259/**************************************************************************/
260/**************************************************************************/
261
Josh Gao116aa0a2018-04-05 17:55:25 -0700262static void _fh_file_init(FH f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800263 f->fh_handle = INVALID_HANDLE_VALUE;
264}
265
Josh Gao116aa0a2018-04-05 17:55:25 -0700266static int _fh_file_close(FH f) {
267 CloseHandle(f->fh_handle);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800268 f->fh_handle = INVALID_HANDLE_VALUE;
269 return 0;
270}
271
Josh Gao116aa0a2018-04-05 17:55:25 -0700272static int _fh_file_read(FH f, void* buf, int len) {
273 DWORD read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800274
Yi Kongaed415c2018-07-13 18:15:16 -0700275 if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700276 D("adb_read: could not read %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800277 errno = EIO;
278 return -1;
279 } else if (read_bytes < (DWORD)len) {
280 f->eof = 1;
281 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700282 return read_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800283}
284
Josh Gao116aa0a2018-04-05 17:55:25 -0700285static int _fh_file_write(FH f, const void* buf, int len) {
286 DWORD wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800287
Yi Kongaed415c2018-07-13 18:15:16 -0700288 if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700289 D("adb_file_write: could not write %d bytes from %s", len, f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800290 errno = EIO;
291 return -1;
292 } else if (wrote_bytes < (DWORD)len) {
293 f->eof = 1;
294 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700295 return wrote_bytes;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800296}
297
Josh Gao116aa0a2018-04-05 17:55:25 -0700298static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) {
299 if (iovcnt <= 0) {
300 errno = EINVAL;
301 return -1;
302 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800303
Josh Gao116aa0a2018-04-05 17:55:25 -0700304 DWORD wrote_bytes = 0;
305
306 for (int i = 0; i < iovcnt; ++i) {
307 ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len);
308 if (rc == -1) {
309 return wrote_bytes > 0 ? wrote_bytes : -1;
310 } else if (rc == 0) {
311 return wrote_bytes;
312 }
313
314 wrote_bytes += rc;
315
316 if (static_cast<size_t>(rc) < iov[i].iov_len) {
317 return wrote_bytes;
318 }
319 }
320
321 return wrote_bytes;
322}
323
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700324static int64_t _fh_file_lseek(FH f, int64_t pos, int origin) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700325 DWORD method;
Josh Gao116aa0a2018-04-05 17:55:25 -0700326 switch (origin) {
327 case SEEK_SET:
328 method = FILE_BEGIN;
329 break;
330 case SEEK_CUR:
331 method = FILE_CURRENT;
332 break;
333 case SEEK_END:
334 method = FILE_END;
335 break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800336 default:
337 errno = EINVAL;
338 return -1;
339 }
340
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700341 LARGE_INTEGER li = {.QuadPart = pos};
342 if (!SetFilePointerEx(f->fh_handle, li, &li, method)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800343 errno = EIO;
344 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800345 }
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700346 f->eof = 0;
347 return li.QuadPart;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800348}
349
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800350/**************************************************************************/
351/**************************************************************************/
352/***** *****/
353/***** file-based descriptor handling *****/
354/***** *****/
355/**************************************************************************/
356/**************************************************************************/
357
Josh Gao64a63ac2018-04-05 18:09:02 -0700358int adb_open(const char* path, int options) {
359 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800360
Josh Gao64a63ac2018-04-05 18:09:02 -0700361 DWORD desiredAccess = 0;
362 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800363
364 switch (options) {
365 case O_RDONLY:
366 desiredAccess = GENERIC_READ;
367 break;
368 case O_WRONLY:
369 desiredAccess = GENERIC_WRITE;
370 break;
371 case O_RDWR:
372 desiredAccess = GENERIC_READ | GENERIC_WRITE;
373 break;
374 default:
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700375 D("adb_open: invalid options (0x%0x)", options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800376 errno = EINVAL;
377 return -1;
378 }
379
Josh Gao64a63ac2018-04-05 18:09:02 -0700380 f = _fh_alloc(&_fh_file_class);
381 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800382 return -1;
383 }
384
Spencer Lowd21dc822015-11-12 15:20:15 -0800385 std::wstring path_wide;
386 if (!android::base::UTF8ToWide(path, &path_wide)) {
387 return -1;
388 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700389 f->fh_handle =
Yi Kongaed415c2018-07-13 18:15:16 -0700390 CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800391
Josh Gao64a63ac2018-04-05 18:09:02 -0700392 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700393 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800394 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700395 D("adb_open: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700396 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800397 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700398 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800399 errno = ENOENT;
400 return -1;
401
402 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700403 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800404 errno = ENOTDIR;
405 return -1;
406
407 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800408 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800409 errno = ENOENT;
410 return -1;
411 }
412 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800413
Josh Gao64a63ac2018-04-05 18:09:02 -0700414 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
415 D("adb_open: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800416 return _fh_to_int(f);
417}
418
419/* ignore mode on Win32 */
Josh Gao64a63ac2018-04-05 18:09:02 -0700420int adb_creat(const char* path, int mode) {
421 FH f;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422
Josh Gao64a63ac2018-04-05 18:09:02 -0700423 f = _fh_alloc(&_fh_file_class);
424 if (!f) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800425 return -1;
426 }
427
Spencer Lowd21dc822015-11-12 15:20:15 -0800428 std::wstring path_wide;
429 if (!android::base::UTF8ToWide(path, &path_wide)) {
430 return -1;
431 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700432 f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
Yi Kongaed415c2018-07-13 18:15:16 -0700433 nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434
Josh Gao64a63ac2018-04-05 18:09:02 -0700435 if (f->fh_handle == INVALID_HANDLE_VALUE) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700436 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800437 _fh_close(f);
Josh Gao64a63ac2018-04-05 18:09:02 -0700438 D("adb_creat: could not open '%s': ", path);
Spencer Low8d8126a2015-07-21 02:06:26 -0700439 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800440 case ERROR_FILE_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700441 D("file not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800442 errno = ENOENT;
443 return -1;
444
445 case ERROR_PATH_NOT_FOUND:
Josh Gao64a63ac2018-04-05 18:09:02 -0700446 D("path not found");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800447 errno = ENOTDIR;
448 return -1;
449
450 default:
David Pursell5f787ed2016-01-27 08:52:53 -0800451 D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800452 errno = ENOENT;
453 return -1;
454 }
455 }
Josh Gao64a63ac2018-04-05 18:09:02 -0700456 snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path);
457 D("adb_creat: '%s' => fd %d", path, _fh_to_int(f));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800458 return _fh_to_int(f);
459}
460
Josh Gao116aa0a2018-04-05 17:55:25 -0700461int adb_read(int fd, void* buf, int len) {
462 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800463
Yi Kongaed415c2018-07-13 18:15:16 -0700464 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700465 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800466 return -1;
467 }
468
Josh Gao116aa0a2018-04-05 17:55:25 -0700469 return f->clazz->_fh_read(f, buf, len);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800470}
471
Josh Gao116aa0a2018-04-05 17:55:25 -0700472int adb_write(int fd, const void* buf, int len) {
473 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800474
Yi Kongaed415c2018-07-13 18:15:16 -0700475 if (f == nullptr) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700476 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800477 return -1;
478 }
479
480 return f->clazz->_fh_write(f, buf, len);
481}
482
Josh Gao116aa0a2018-04-05 17:55:25 -0700483ssize_t adb_writev(int fd, const adb_iovec* iov, int iovcnt) {
484 FH f = _fh_from_int(fd, __func__);
485
Yi Kongaed415c2018-07-13 18:15:16 -0700486 if (f == nullptr) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700487 errno = EBADF;
488 return -1;
489 }
490
491 return f->clazz->_fh_writev(f, iov, iovcnt);
492}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700494int64_t adb_lseek(int fd, int64_t pos, int where) {
Josh Gao64a63ac2018-04-05 18:09:02 -0700495 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800496 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700497 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800498 return -1;
499 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500 return f->clazz->_fh_lseek(f, pos, where);
501}
502
Josh Gao64a63ac2018-04-05 18:09:02 -0700503int adb_close(int fd) {
504 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800505
506 if (!f) {
Josh Gao011ba4b2018-04-05 18:09:39 -0700507 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800508 return -1;
509 }
510
Josh Gao64a63ac2018-04-05 18:09:02 -0700511 D("adb_close: %s", f->name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800512 _fh_close(f);
513 return 0;
514}
515
516/**************************************************************************/
517/**************************************************************************/
518/***** *****/
519/***** socket-based file descriptors *****/
520/***** *****/
521/**************************************************************************/
522/**************************************************************************/
523
Spencer Lowf055c192015-01-25 14:40:16 -0800524#undef setsockopt
525
Spencer Low5200c662015-07-30 23:07:55 -0700526static void _socket_set_errno( const DWORD err ) {
Spencer Low0a796002015-10-18 16:45:09 -0700527 // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a
528 // lot of POSIX and socket error codes, some of the resulting error codes
Josh Gaoa3577e12016-12-05 13:24:48 -0800529 // are mapped to strings by adb_strerror().
Spencer Low5200c662015-07-30 23:07:55 -0700530 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800531 case 0: errno = 0; break;
Spencer Low0a796002015-10-18 16:45:09 -0700532 // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use.
533 // case WSAEINTR: errno = EINTR; break;
534 case WSAEFAULT: errno = EFAULT; break;
535 case WSAEINVAL: errno = EINVAL; break;
536 case WSAEMFILE: errno = EMFILE; break;
Spencer Lowbf7c6052015-08-11 16:45:32 -0700537 // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because
538 // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and
539 // callers check specifically for EAGAIN.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800540 case WSAEWOULDBLOCK: errno = EAGAIN; break;
Spencer Low0a796002015-10-18 16:45:09 -0700541 case WSAENOTSOCK: errno = ENOTSOCK; break;
542 case WSAENOPROTOOPT: errno = ENOPROTOOPT; break;
543 case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break;
544 case WSAENETDOWN: errno = ENETDOWN; break;
545 case WSAENETRESET: errno = ENETRESET; break;
546 // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems
547 // to use EPIPE for these situations and there are some callers that look
548 // for EPIPE.
549 case WSAECONNABORTED: errno = EPIPE; break;
550 case WSAECONNRESET: errno = ECONNRESET; break;
551 case WSAENOBUFS: errno = ENOBUFS; break;
552 case WSAENOTCONN: errno = ENOTCONN; break;
553 // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or
554 // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future
555 // considerations: Reportedly send() can return zero on timeout, and POSIX
556 // code may expect EAGAIN instead of ETIMEDOUT on timeout.
557 // case WSAETIMEDOUT: errno = ETIMEDOUT; break;
558 case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800559 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800560 errno = EINVAL;
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700561 D( "_socket_set_errno: mapping Windows error code %lu to errno %d",
Spencer Low5200c662015-07-30 23:07:55 -0700562 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800563 }
564}
565
Josh Gao3777d2e2016-02-16 17:34:53 -0800566extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
567 // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves.
568 int skipped = 0;
569 std::vector<WSAPOLLFD> sockets;
570 std::vector<adb_pollfd*> original;
Josh Gao05fb45b2018-03-29 12:34:28 -0700571
Josh Gao3777d2e2016-02-16 17:34:53 -0800572 for (size_t i = 0; i < nfds; ++i) {
573 FH fh = _fh_from_int(fds[i].fd, __func__);
574 if (!fh || !fh->used || fh->clazz != &_fh_socket_class) {
575 D("adb_poll received bad FD %d", fds[i].fd);
576 fds[i].revents = POLLNVAL;
577 ++skipped;
578 } else {
579 WSAPOLLFD wsapollfd = {
580 .fd = fh->u.socket,
581 .events = static_cast<short>(fds[i].events)
582 };
583 sockets.push_back(wsapollfd);
584 original.push_back(&fds[i]);
585 }
Spencer Low5200c662015-07-30 23:07:55 -0700586 }
Josh Gao3777d2e2016-02-16 17:34:53 -0800587
588 if (sockets.empty()) {
589 return skipped;
590 }
591
Josh Gao05fb45b2018-03-29 12:34:28 -0700592 // If we have any invalid FDs in our FD set, make sure to return immediately.
593 if (skipped > 0) {
594 timeout = 0;
595 }
596
Josh Gao3777d2e2016-02-16 17:34:53 -0800597 int result = WSAPoll(sockets.data(), sockets.size(), timeout);
598 if (result == SOCKET_ERROR) {
599 _socket_set_errno(WSAGetLastError());
600 return -1;
601 }
602
603 // Map the results back onto the original set.
604 for (size_t i = 0; i < sockets.size(); ++i) {
605 original[i]->revents = sockets[i].revents;
606 }
607
Josh Gao05fb45b2018-03-29 12:34:28 -0700608 // WSAPoll appears to return the number of unique FDs with available events, instead of how many
Josh Gao3777d2e2016-02-16 17:34:53 -0800609 // of the pollfd elements have a non-zero revents field, which is what it and poll are specified
610 // to do. Ignore its result and calculate the proper return value.
611 result = 0;
612 for (size_t i = 0; i < nfds; ++i) {
613 if (fds[i].revents != 0) {
614 ++result;
615 }
616 }
617 return result;
618}
619
620static void _fh_socket_init(FH f) {
621 f->fh_socket = INVALID_SOCKET;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622}
623
Josh Gao116aa0a2018-04-05 17:55:25 -0700624static int _fh_socket_close(FH f) {
Spencer Low5200c662015-07-30 23:07:55 -0700625 if (f->fh_socket != INVALID_SOCKET) {
626 /* gently tell any peer that we're closing the socket */
627 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
628 // If the socket is not connected, this returns an error. We want to
629 // minimize logging spam, so don't log these errors for now.
630#if 0
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700631 D("socket shutdown failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -0800632 android::base::SystemErrorCodeToString(WSAGetLastError()).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700633#endif
634 }
635 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800636 // Don't set errno here, since adb_close will ignore it.
637 const DWORD err = WSAGetLastError();
638 D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -0700639 }
640 f->fh_socket = INVALID_SOCKET;
641 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800642 return 0;
643}
644
Elliott Hughescabfc3d2018-09-20 13:59:49 -0700645static int64_t _fh_socket_lseek(FH f, int64_t pos, int origin) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800646 errno = EPIPE;
647 return -1;
648}
649
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700650static int _fh_socket_read(FH f, void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700651 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800652 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700653 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700654 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
655 // that to reduce spam and confusion.
656 if (err != WSAEWOULDBLOCK) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700657 D("recv fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800658 android::base::SystemErrorCodeToString(err).c_str());
Spencer Lowbf7c6052015-08-11 16:45:32 -0700659 }
Spencer Low5200c662015-07-30 23:07:55 -0700660 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800661 result = -1;
662 }
Josh Gao116aa0a2018-04-05 17:55:25 -0700663 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800664}
665
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700666static int _fh_socket_write(FH f, const void* buf, int len) {
Josh Gao116aa0a2018-04-05 17:55:25 -0700667 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800668 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700669 const DWORD err = WSAGetLastError();
Spencer Low0a796002015-10-18 16:45:09 -0700670 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
671 // that to reduce spam and confusion.
672 if (err != WSAEWOULDBLOCK) {
673 D("send fd %d failed: %s", _fh_to_int(f),
David Pursell5f787ed2016-01-27 08:52:53 -0800674 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low0a796002015-10-18 16:45:09 -0700675 }
Spencer Low5200c662015-07-30 23:07:55 -0700676 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677 result = -1;
Spencer Low677fb432015-09-29 15:05:29 -0700678 } else {
679 // According to https://code.google.com/p/chromium/issues/detail?id=27870
680 // Winsock Layered Service Providers may cause this.
Josh Gao116aa0a2018-04-05 17:55:25 -0700681 CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but "
682 << result << " bytes reportedly written";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800683 }
684 return result;
685}
686
Josh Gao116aa0a2018-04-05 17:55:25 -0700687// Make sure that adb_iovec is compatible with WSABUF.
688static_assert(sizeof(adb_iovec) == sizeof(WSABUF), "");
689static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), "");
690static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), "");
691
692static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), "");
693static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), "");
694
695static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) {
696 if (iovcnt <= 0) {
697 errno = EINVAL;
698 return -1;
699 }
700
701 WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov));
702 DWORD bytes_written = 0;
703 int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr);
704 if (result == SOCKET_ERROR) {
705 const DWORD err = WSAGetLastError();
706 // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace
707 // that to reduce spam and confusion.
708 if (err != WSAEWOULDBLOCK) {
709 D("send fd %d failed: %s", _fh_to_int(f),
710 android::base::SystemErrorCodeToString(err).c_str());
711 }
712 _socket_set_errno(err);
713 result = -1;
714 }
715 CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written);
716 return static_cast<int>(bytes_written);
717}
718
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800719/**************************************************************************/
720/**************************************************************************/
721/***** *****/
722/***** replacement for libs/cutils/socket_xxxx.c *****/
723/***** *****/
724/**************************************************************************/
725/**************************************************************************/
726
Josh Gao2e93df22018-04-05 18:10:03 -0700727static int _init_winsock(void) {
728 static std::once_flag once;
729 std::call_once(once, []() {
730 WSADATA wsaData;
731 int rc = WSAStartup(MAKEWORD(2, 2), &wsaData);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800732 if (rc != 0) {
David Pursell5f787ed2016-01-27 08:52:53 -0800733 fatal("adb: could not initialize Winsock: %s",
734 android::base::SystemErrorCodeToString(rc).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800735 }
Spencer Low87e97ee2015-08-12 18:19:16 -0700736
737 // Note that we do not call atexit() to register WSACleanup to be called
738 // at normal process termination because:
739 // 1) When exit() is called, there are still threads actively using
740 // Winsock because we don't cleanly shutdown all threads, so it
741 // doesn't make sense to call WSACleanup() and may cause problems
742 // with those threads.
743 // 2) A deadlock can occur when exit() holds a C Runtime lock, then it
744 // calls WSACleanup() which tries to unload a DLL, which tries to
745 // grab the LoaderLock. This conflicts with the device_poll_thread
746 // which holds the LoaderLock because AdbWinApi.dll calls
747 // setupapi.dll which tries to load wintrust.dll which tries to load
748 // crypt32.dll which calls atexit() which tries to acquire the C
749 // Runtime lock that the other thread holds.
Josh Gao2e93df22018-04-05 18:10:03 -0700750 });
751 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800752}
753
Josh Gao2e93df22018-04-05 18:10:03 -0700754static int _winsock_init = _init_winsock();
755
Spencer Low677fb432015-09-29 15:05:29 -0700756// Map a socket type to an explicit socket protocol instead of using the socket
757// protocol of 0. Explicit socket protocols are used by most apps and we should
758// do the same to reduce the chance of exercising uncommon code-paths that might
759// have problems or that might load different Winsock service providers that
760// have problems.
761static int GetSocketProtocolFromSocketType(int type) {
762 switch (type) {
763 case SOCK_STREAM:
764 return IPPROTO_TCP;
765 case SOCK_DGRAM:
766 return IPPROTO_UDP;
767 default:
768 LOG(FATAL) << "Unknown socket type: " << type;
769 return 0;
770 }
771}
772
Spencer Low5200c662015-07-30 23:07:55 -0700773int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800774 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800775 SOCKET s;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800776
Josh Gao6487e742016-02-18 13:43:55 -0800777 unique_fh f(_fh_alloc(&_fh_socket_class));
Spencer Low5200c662015-07-30 23:07:55 -0700778 if (!f) {
779 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800780 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700781 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800782
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800783 memset(&addr, 0, sizeof(addr));
784 addr.sin_family = AF_INET;
785 addr.sin_port = htons(port);
786 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
787
Spencer Low677fb432015-09-29 15:05:29 -0700788 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Josh Gao6487e742016-02-18 13:43:55 -0800789 if (s == INVALID_SOCKET) {
790 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700791 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800792 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700793 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800794 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700795 return -1;
796 }
797 f->fh_socket = s;
798
Josh Gao6487e742016-02-18 13:43:55 -0800799 if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700800 // Save err just in case inet_ntoa() or ntohs() changes the last error.
801 const DWORD err = WSAGetLastError();
802 *error = android::base::StringPrintf("cannot connect to %s:%u: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800803 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
804 android::base::SystemErrorCodeToString(err).c_str());
805 D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
806 error->c_str());
807 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800808 return -1;
809 }
810
Spencer Low5200c662015-07-30 23:07:55 -0700811 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800812 snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
813 port);
814 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700815 f.release();
816 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800817}
818
Spencer Low5200c662015-07-30 23:07:55 -0700819// interface_address is INADDR_LOOPBACK or INADDR_ANY.
Josh Gao6487e742016-02-18 13:43:55 -0800820static int _network_server(int port, int type, u_long interface_address, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800821 struct sockaddr_in addr;
Josh Gao6487e742016-02-18 13:43:55 -0800822 SOCKET s;
823 int n;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824
Josh Gao6487e742016-02-18 13:43:55 -0800825 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800826 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700827 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828 return -1;
829 }
830
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800831 memset(&addr, 0, sizeof(addr));
832 addr.sin_family = AF_INET;
833 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700834 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800835
Spencer Low5200c662015-07-30 23:07:55 -0700836 // TODO: Consider using dual-stack socket that can simultaneously listen on
837 // IPv4 and IPv6.
Spencer Low677fb432015-09-29 15:05:29 -0700838 s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type));
Spencer Low5200c662015-07-30 23:07:55 -0700839 if (s == INVALID_SOCKET) {
Josh Gao6487e742016-02-18 13:43:55 -0800840 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700841 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800842 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700843 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800844 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700845 return -1;
846 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800847
848 f->fh_socket = s;
849
Spencer Lowbf7c6052015-08-11 16:45:32 -0700850 // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the
851 // same port, so instead use SO_EXCLUSIVEADDRUSE.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800852 n = 1;
Josh Gao6487e742016-02-18 13:43:55 -0800853 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) {
854 const DWORD err = WSAGetLastError();
855 *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s",
856 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700857 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800858 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -0700859 return -1;
860 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800861
Josh Gao6487e742016-02-18 13:43:55 -0800862 if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700863 // Save err just in case inet_ntoa() or ntohs() changes the last error.
864 const DWORD err = WSAGetLastError();
Josh Gao6487e742016-02-18 13:43:55 -0800865 *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr),
866 ntohs(addr.sin_port),
867 android::base::SystemErrorCodeToString(err).c_str());
868 D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
869 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800870 return -1;
871 }
872 if (type == SOCK_STREAM) {
Josh Gaobf243a62018-03-20 14:25:03 -0700873 if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
Josh Gao6487e742016-02-18 13:43:55 -0800874 const DWORD err = WSAGetLastError();
875 *error = android::base::StringPrintf(
876 "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str());
877 D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port,
878 error->c_str());
879 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800880 return -1;
881 }
882 }
Spencer Low5200c662015-07-30 23:07:55 -0700883 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800884 snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
885 interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "",
886 port);
887 D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700888 f.release();
889 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800890}
891
Spencer Low5200c662015-07-30 23:07:55 -0700892int network_loopback_server(int port, int type, std::string* error) {
893 return _network_server(port, type, INADDR_LOOPBACK, error);
894}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800895
Spencer Low5200c662015-07-30 23:07:55 -0700896int network_inaddr_any_server(int port, int type, std::string* error) {
897 return _network_server(port, type, INADDR_ANY, error);
898}
899
900int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
901 unique_fh f(_fh_alloc(&_fh_socket_class));
902 if (!f) {
903 *error = strerror(errno);
904 return -1;
905 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800906
Spencer Low5200c662015-07-30 23:07:55 -0700907 struct addrinfo hints;
908 memset(&hints, 0, sizeof(hints));
909 hints.ai_family = AF_UNSPEC;
910 hints.ai_socktype = type;
Spencer Low677fb432015-09-29 15:05:29 -0700911 hints.ai_protocol = GetSocketProtocolFromSocketType(type);
Spencer Low5200c662015-07-30 23:07:55 -0700912
913 char port_str[16];
914 snprintf(port_str, sizeof(port_str), "%d", port);
915
916 struct addrinfo* addrinfo_ptr = nullptr;
Spencer Lowe347c1d2015-08-02 18:13:54 -0700917
918#if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03)
Josh Gao6487e742016-02-18 13:43:55 -0800919// TODO: When the Android SDK tools increases the Windows system
920// requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW().
Spencer Lowe347c1d2015-08-02 18:13:54 -0700921#else
Josh Gao6487e742016-02-18 13:43:55 -0800922// Otherwise, keep using getaddrinfo(), or do runtime API detection
923// with GetProcAddress("GetAddrInfoW").
Spencer Lowe347c1d2015-08-02 18:13:54 -0700924#endif
Spencer Low5200c662015-07-30 23:07:55 -0700925 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
Josh Gao6487e742016-02-18 13:43:55 -0800926 const DWORD err = WSAGetLastError();
927 *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s",
928 host.c_str(), port_str,
929 android::base::SystemErrorCodeToString(err).c_str());
930
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700931 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800932 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800933 return -1;
934 }
Elliott Hughesaea16832016-08-08 12:52:37 -0700935 std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo);
Spencer Low5200c662015-07-30 23:07:55 -0700936 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800937
Spencer Low5200c662015-07-30 23:07:55 -0700938 // TODO: Try all the addresses if there's more than one? This just uses
939 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
940 // which tries all addresses, takes a timeout and more.
Josh Gao6487e742016-02-18 13:43:55 -0800941 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol);
942 if (s == INVALID_SOCKET) {
943 const DWORD err = WSAGetLastError();
Spencer Lowbf7c6052015-08-11 16:45:32 -0700944 *error = android::base::StringPrintf("cannot create socket: %s",
Josh Gao6487e742016-02-18 13:43:55 -0800945 android::base::SystemErrorCodeToString(err).c_str());
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700946 D("%s", error->c_str());
Josh Gao6487e742016-02-18 13:43:55 -0800947 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800948 return -1;
949 }
950 f->fh_socket = s;
951
Spencer Low5200c662015-07-30 23:07:55 -0700952 // TODO: Implement timeouts for Windows. Seems like the default in theory
953 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
Josh Gao6487e742016-02-18 13:43:55 -0800954 if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
Spencer Lowbf7c6052015-08-11 16:45:32 -0700955 // TODO: Use WSAAddressToString or inet_ntop on address.
Josh Gao6487e742016-02-18 13:43:55 -0800956 const DWORD err = WSAGetLastError();
957 *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str,
958 android::base::SystemErrorCodeToString(err).c_str());
959 D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(),
960 port_str, error->c_str());
961 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800962 return -1;
963 }
964
Spencer Low5200c662015-07-30 23:07:55 -0700965 const int fd = _fh_to_int(f.get());
Josh Gao6487e742016-02-18 13:43:55 -0800966 snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "",
967 port);
968 D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp",
969 fd);
Spencer Low5200c662015-07-30 23:07:55 -0700970 f.release();
971 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800972}
973
Josh Gao64a63ac2018-04-05 18:09:02 -0700974int adb_register_socket(SOCKET s) {
975 FH f = _fh_alloc(&_fh_socket_class);
Casey Dahlin2fe9b602016-09-21 14:03:39 -0700976 f->fh_socket = s;
977 return _fh_to_int(f);
978}
979
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800980#undef accept
Josh Gao64a63ac2018-04-05 18:09:02 -0700981int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t* addrlen) {
982 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200983
Josh Gao64a63ac2018-04-05 18:09:02 -0700984 if (!serverfh || serverfh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700985 D("adb_socket_accept: invalid fd %d", serverfd);
Spencer Low5200c662015-07-30 23:07:55 -0700986 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800987 return -1;
988 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200989
Josh Gao64a63ac2018-04-05 18:09:02 -0700990 unique_fh fh(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800991 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -0700992 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
993 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800994 return -1;
995 }
996
Josh Gao64a63ac2018-04-05 18:09:02 -0700997 fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800998 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700999 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -07001000 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd
1001 << " failed: " + android::base::SystemErrorCodeToString(err);
1002 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001003 return -1;
1004 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02001005
Spencer Low5200c662015-07-30 23:07:55 -07001006 const int fd = _fh_to_int(fh.get());
Josh Gao64a63ac2018-04-05 18:09:02 -07001007 snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name);
1008 D("adb_socket_accept on fd %d returns fd %d", serverfd, fd);
Spencer Low5200c662015-07-30 23:07:55 -07001009 fh.release();
Josh Gao64a63ac2018-04-05 18:09:02 -07001010 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001011}
1012
Josh Gao64a63ac2018-04-05 18:09:02 -07001013int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) {
1014 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001015
Josh Gao64a63ac2018-04-05 18:09:02 -07001016 if (!fh || fh->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001017 D("adb_setsockopt: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001018 errno = EBADF;
1019 return -1;
1020 }
Spencer Low677fb432015-09-29 15:05:29 -07001021
1022 // TODO: Once we can assume Windows Vista or later, if the caller is trying
1023 // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has
1024 // auto-tuning.
1025
Josh Gao64a63ac2018-04-05 18:09:02 -07001026 int result =
1027 setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen);
1028 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001029 const DWORD err = WSAGetLastError();
Josh Gao64a63ac2018-04-05 18:09:02 -07001030 D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd, level,
1031 optname, android::base::SystemErrorCodeToString(err).c_str());
1032 _socket_set_errno(err);
Spencer Low5200c662015-07-30 23:07:55 -07001033 result = -1;
1034 }
1035 return result;
1036}
1037
Josh Gao3777d2e2016-02-16 17:34:53 -08001038int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) {
1039 FH fh = _fh_from_int(fd, __func__);
1040
1041 if (!fh || fh->clazz != &_fh_socket_class) {
1042 D("adb_getsockname: invalid fd %d", fd);
1043 errno = EBADF;
1044 return -1;
1045 }
1046
Josh Gao3726a012017-03-30 13:04:35 -07001047 int result = getsockname(fh->fh_socket, sockaddr, optlen);
Josh Gao3777d2e2016-02-16 17:34:53 -08001048 if (result == SOCKET_ERROR) {
1049 const DWORD err = WSAGetLastError();
1050 D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd,
1051 android::base::SystemErrorCodeToString(err).c_str());
1052 _socket_set_errno(err);
1053 result = -1;
1054 }
1055 return result;
1056}
Spencer Low5200c662015-07-30 23:07:55 -07001057
David Purselleaae97e2016-04-07 11:25:48 -07001058int adb_socket_get_local_port(int fd) {
1059 sockaddr_storage addr_storage;
1060 socklen_t addr_len = sizeof(addr_storage);
1061
1062 if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) {
1063 D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno));
1064 return -1;
1065 }
1066
1067 if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) {
1068 D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family);
1069 errno = ECONNABORTED;
1070 return -1;
1071 }
1072
1073 return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port);
1074}
1075
Josh Gao2e1e7892018-03-23 13:03:28 -07001076int adb_shutdown(int fd, int direction) {
1077 FH f = _fh_from_int(fd, __func__);
Spencer Low5200c662015-07-30 23:07:55 -07001078
1079 if (!f || f->clazz != &_fh_socket_class) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001080 D("adb_shutdown: invalid fd %d", fd);
Spencer Low5200c662015-07-30 23:07:55 -07001081 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -08001082 return -1;
1083 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001084
Josh Gao2e1e7892018-03-23 13:03:28 -07001085 D("adb_shutdown: %s", f->name);
1086 if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -07001087 const DWORD err = WSAGetLastError();
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001088 D("socket shutdown fd %d failed: %s", fd,
David Pursell5f787ed2016-01-27 08:52:53 -08001089 android::base::SystemErrorCodeToString(err).c_str());
Spencer Low5200c662015-07-30 23:07:55 -07001090 _socket_set_errno(err);
1091 return -1;
1092 }
1093 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001094}
1095
Josh Gao3777d2e2016-02-16 17:34:53 -08001096// Emulate socketpair(2) by binding and connecting to a socket.
1097int adb_socketpair(int sv[2]) {
1098 int server = -1;
1099 int client = -1;
1100 int accepted = -1;
David Purselleaae97e2016-04-07 11:25:48 -07001101 int local_port = -1;
Josh Gao3777d2e2016-02-16 17:34:53 -08001102 std::string error;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001103
Josh Gao3777d2e2016-02-16 17:34:53 -08001104 server = network_loopback_server(0, SOCK_STREAM, &error);
1105 if (server < 0) {
1106 D("adb_socketpair: failed to create server: %s", error.c_str());
1107 goto fail;
David Pursellb404dec2015-09-11 16:06:59 -07001108 }
1109
David Purselleaae97e2016-04-07 11:25:48 -07001110 local_port = adb_socket_get_local_port(server);
1111 if (local_port < 0) {
1112 D("adb_socketpair: failed to get server port number: %s", error.c_str());
Josh Gao3777d2e2016-02-16 17:34:53 -08001113 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001114 }
David Purselleaae97e2016-04-07 11:25:48 -07001115 D("adb_socketpair: bound on port %d", local_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001116
David Purselleaae97e2016-04-07 11:25:48 -07001117 client = network_loopback_client(local_port, SOCK_STREAM, &error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001118 if (client < 0) {
1119 D("adb_socketpair: failed to connect client: %s", error.c_str());
1120 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001121 }
1122
Josh Gao3726a012017-03-30 13:04:35 -07001123 accepted = adb_socket_accept(server, nullptr, nullptr);
Josh Gao3777d2e2016-02-16 17:34:53 -08001124 if (accepted < 0) {
Josh Gao6487e742016-02-18 13:43:55 -08001125 D("adb_socketpair: failed to accept: %s", strerror(errno));
Josh Gao3777d2e2016-02-16 17:34:53 -08001126 goto fail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001127 }
Josh Gao3777d2e2016-02-16 17:34:53 -08001128 adb_close(server);
1129 sv[0] = client;
1130 sv[1] = accepted;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001131 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001132
Josh Gao3777d2e2016-02-16 17:34:53 -08001133fail:
1134 if (server >= 0) {
1135 adb_close(server);
1136 }
1137 if (client >= 0) {
1138 adb_close(client);
1139 }
1140 if (accepted >= 0) {
1141 adb_close(accepted);
1142 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001143 return -1;
1144}
1145
Josh Gao3777d2e2016-02-16 17:34:53 -08001146bool set_file_block_mode(int fd, bool block) {
1147 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001148
Josh Gao3777d2e2016-02-16 17:34:53 -08001149 if (!fh || !fh->used) {
1150 errno = EBADF;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001151 D("Setting nonblocking on bad file descriptor %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001152 return false;
Spencer Low5200c662015-07-30 23:07:55 -07001153 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154
Josh Gao3777d2e2016-02-16 17:34:53 -08001155 if (fh->clazz == &_fh_socket_class) {
1156 u_long x = !block;
1157 if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) {
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001158 int error = WSAGetLastError();
1159 _socket_set_errno(error);
1160 D("Setting %d nonblocking failed (%d)", fd, error);
Josh Gao3777d2e2016-02-16 17:34:53 -08001161 return false;
1162 }
1163 return true;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001164 } else {
Josh Gao3777d2e2016-02-16 17:34:53 -08001165 errno = ENOTSOCK;
Casey Dahlin2fe9b602016-09-21 14:03:39 -07001166 D("Setting nonblocking on non-socket %d", fd);
Josh Gao3777d2e2016-02-16 17:34:53 -08001167 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001168 }
1169}
1170
David Pursellbfd95032016-02-22 14:27:23 -08001171bool set_tcp_keepalive(int fd, int interval_sec) {
1172 FH fh = _fh_from_int(fd, __func__);
1173
1174 if (!fh || fh->clazz != &_fh_socket_class) {
1175 D("set_tcp_keepalive(%d) failed: invalid fd", fd);
1176 errno = EBADF;
1177 return false;
1178 }
1179
1180 tcp_keepalive keepalive;
1181 keepalive.onoff = (interval_sec > 0);
1182 keepalive.keepalivetime = interval_sec * 1000;
1183 keepalive.keepaliveinterval = interval_sec * 1000;
1184
1185 DWORD bytes_returned = 0;
1186 if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0,
1187 &bytes_returned, nullptr, nullptr) != 0) {
1188 const DWORD err = WSAGetLastError();
1189 D("set_tcp_keepalive(%d) failed: %s", fd,
1190 android::base::SystemErrorCodeToString(err).c_str());
1191 _socket_set_errno(err);
1192 return false;
1193 }
1194
1195 return true;
1196}
1197
Spencer Low50184062015-03-01 15:06:21 -08001198/**************************************************************************/
1199/**************************************************************************/
1200/***** *****/
1201/***** Console Window Terminal Emulation *****/
1202/***** *****/
1203/**************************************************************************/
1204/**************************************************************************/
1205
1206// This reads input from a Win32 console window and translates it into Unix
1207// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
1208// mode, not Application mode), which itself emulates xterm. Gnome Terminal
1209// is emulated instead of xterm because it is probably more popular than xterm:
1210// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
1211// supports modern fonts, etc. It seems best to emulate the terminal that most
1212// Android developers use because they'll fix apps (the shell, etc.) to keep
1213// working with that terminal's emulation.
1214//
1215// The point of this emulation is not to be perfect or to solve all issues with
1216// console windows on Windows, but to be better than the original code which
1217// just called read() (which called ReadFile(), which called ReadConsoleA())
1218// which did not support Ctrl-C, tab completion, shell input line editing
1219// keys, server echo, and more.
1220//
1221// This implementation reconfigures the console with SetConsoleMode(), then
1222// calls ReadConsoleInput() to get raw input which it remaps to Unix
1223// terminal-style sequences which is returned via unix_read() which is used
1224// by the 'adb shell' command.
1225//
1226// Code organization:
1227//
David Pursellc5b8ad82015-10-28 14:29:51 -07001228// * _get_console_handle() and unix_isatty() provide console information.
Spencer Low50184062015-03-01 15:06:21 -08001229// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
1230// * unix_read() detects console windows (as opposed to pipes, files, etc.).
1231// * _console_read() is the main code of the emulation.
1232
David Pursellc5b8ad82015-10-28 14:29:51 -07001233// Returns a console HANDLE if |fd| is a console, otherwise returns nullptr.
1234// If a valid HANDLE is returned and |mode| is not null, |mode| is also filled
1235// with the console mode. Requires GENERIC_READ access to the underlying HANDLE.
1236static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) {
1237 // First check isatty(); this is very fast and eliminates most non-console
1238 // FDs, but returns 1 for both consoles and character devices like NUL.
1239#pragma push_macro("isatty")
1240#undef isatty
1241 if (!isatty(fd)) {
1242 return nullptr;
1243 }
1244#pragma pop_macro("isatty")
1245
1246 // To differentiate between character devices and consoles we need to get
1247 // the underlying HANDLE and use GetConsoleMode(), which is what requires
1248 // GENERIC_READ permissions.
1249 const intptr_t intptr_handle = _get_osfhandle(fd);
1250 if (intptr_handle == -1) {
1251 return nullptr;
1252 }
1253 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
1254 DWORD temp_mode = 0;
1255 if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) {
1256 return nullptr;
1257 }
1258
1259 return handle;
1260}
1261
1262// Returns a console handle if |stream| is a console, otherwise returns nullptr.
1263static HANDLE _get_console_handle(FILE* const stream) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08001264 // Save and restore errno to make it easier for callers to prevent from overwriting errno.
1265 android::base::ErrnoRestorer er;
David Pursellc5b8ad82015-10-28 14:29:51 -07001266 const int fd = fileno(stream);
1267 if (fd < 0) {
1268 return nullptr;
1269 }
1270 return _get_console_handle(fd);
1271}
1272
1273int unix_isatty(int fd) {
1274 return _get_console_handle(fd) ? 1 : 0;
1275}
Spencer Low50184062015-03-01 15:06:21 -08001276
Spencer Low32762f42015-11-10 19:17:16 -08001277// Get the next KEY_EVENT_RECORD that should be processed.
1278static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) {
Spencer Low50184062015-03-01 15:06:21 -08001279 for (;;) {
1280 DWORD read_count = 0;
1281 memset(input_record, 0, sizeof(*input_record));
1282 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
Spencer Low32762f42015-11-10 19:17:16 -08001283 D("_get_key_event_record: ReadConsoleInputA() failed: %s\n",
David Pursell5f787ed2016-01-27 08:52:53 -08001284 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08001285 errno = EIO;
1286 return false;
1287 }
1288
1289 if (read_count == 0) { // should be impossible
1290 fatal("ReadConsoleInputA returned 0");
1291 }
1292
1293 if (read_count != 1) { // should be impossible
1294 fatal("ReadConsoleInputA did not return one input record");
1295 }
1296
Spencer Low2e02dc62015-11-07 17:34:39 -08001297 // If the console window is resized, emulate SIGWINCH by breaking out
1298 // of read() with errno == EINTR. Note that there is no event on
1299 // vertical resize because we don't give the console our own custom
1300 // screen buffer (with CreateConsoleScreenBuffer() +
1301 // SetConsoleActiveScreenBuffer()). Instead, we use the default which
1302 // supports scrollback, but doesn't seem to raise an event for vertical
1303 // window resize.
1304 if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) {
1305 errno = EINTR;
1306 return false;
1307 }
1308
Spencer Low50184062015-03-01 15:06:21 -08001309 if ((input_record->EventType == KEY_EVENT) &&
1310 (input_record->Event.KeyEvent.bKeyDown)) {
1311 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
1312 fatal("ReadConsoleInputA returned a key event with zero repeat"
1313 " count");
1314 }
1315
1316 // Got an interesting INPUT_RECORD, so return
1317 return true;
1318 }
1319 }
1320}
1321
Spencer Low50184062015-03-01 15:06:21 -08001322static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
1323 return (control_key_state & SHIFT_PRESSED) != 0;
1324}
1325
1326static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
1327 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
1328}
1329
1330static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
1331 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
1332}
1333
1334static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
1335 return (control_key_state & NUMLOCK_ON) != 0;
1336}
1337
1338static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
1339 return (control_key_state & CAPSLOCK_ON) != 0;
1340}
1341
1342static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
1343 return (control_key_state & ENHANCED_KEY) != 0;
1344}
1345
1346// Constants from MSDN for ToAscii().
1347static const BYTE TOASCII_KEY_OFF = 0x00;
1348static const BYTE TOASCII_KEY_DOWN = 0x80;
1349static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
1350
1351// Given a key event, ignore a modifier key and return the character that was
1352// entered without the modifier. Writes to *ch and returns the number of bytes
1353// written.
1354static size_t _get_char_ignoring_modifier(char* const ch,
1355 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
1356 const WORD modifier) {
1357 // If there is no character from Windows, try ignoring the specified
1358 // modifier and look for a character. Note that if AltGr is being used,
1359 // there will be a character from Windows.
1360 if (key_event->uChar.AsciiChar == '\0') {
1361 // Note that we read the control key state from the passed in argument
1362 // instead of from key_event since the argument has been normalized.
1363 if (((modifier == VK_SHIFT) &&
1364 _is_shift_pressed(control_key_state)) ||
1365 ((modifier == VK_CONTROL) &&
1366 _is_ctrl_pressed(control_key_state)) ||
1367 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
1368
1369 BYTE key_state[256] = {0};
1370 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
1371 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1372 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
1373 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1374 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
1375 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
1376 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
1377 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
1378
1379 // cause this modifier to be ignored
1380 key_state[modifier] = TOASCII_KEY_OFF;
1381
1382 WORD translated = 0;
1383 if (ToAscii(key_event->wVirtualKeyCode,
1384 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
1385 // Ignoring the modifier, we found a character.
1386 *ch = (CHAR)translated;
1387 return 1;
1388 }
1389 }
1390 }
1391
1392 // Just use whatever Windows told us originally.
1393 *ch = key_event->uChar.AsciiChar;
1394
1395 // If the character from Windows is NULL, return a size of zero.
1396 return (*ch == '\0') ? 0 : 1;
1397}
1398
1399// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
1400// but taking into account the shift key. This is because for a sequence like
1401// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
1402// we want to find the character ')'.
1403//
1404// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
1405// because it is the default key-sequence to switch the input language.
1406// This is configurable in the Region and Language control panel.
1407static __inline__ size_t _get_non_control_char(char* const ch,
1408 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1409 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1410 VK_CONTROL);
1411}
1412
1413// Get without Alt.
1414static __inline__ size_t _get_non_alt_char(char* const ch,
1415 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1416 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
1417 VK_MENU);
1418}
1419
1420// Ignore the control key, find the character from Windows, and apply any
1421// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
1422// *pch and returns number of bytes written.
1423static size_t _get_control_character(char* const pch,
1424 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
1425 const size_t len = _get_non_control_char(pch, key_event,
1426 control_key_state);
1427
1428 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
1429 char ch = *pch;
1430 switch (ch) {
1431 case '2':
1432 case '@':
1433 case '`':
1434 ch = '\0';
1435 break;
1436 case '3':
1437 case '[':
1438 case '{':
1439 ch = '\x1b';
1440 break;
1441 case '4':
1442 case '\\':
1443 case '|':
1444 ch = '\x1c';
1445 break;
1446 case '5':
1447 case ']':
1448 case '}':
1449 ch = '\x1d';
1450 break;
1451 case '6':
1452 case '^':
1453 case '~':
1454 ch = '\x1e';
1455 break;
1456 case '7':
1457 case '-':
1458 case '_':
1459 ch = '\x1f';
1460 break;
1461 case '8':
1462 ch = '\x7f';
1463 break;
1464 case '/':
1465 if (!_is_alt_pressed(control_key_state)) {
1466 ch = '\x1f';
1467 }
1468 break;
1469 case '?':
1470 if (!_is_alt_pressed(control_key_state)) {
1471 ch = '\x7f';
1472 }
1473 break;
1474 }
1475 *pch = ch;
1476 }
1477
1478 return len;
1479}
1480
1481static DWORD _normalize_altgr_control_key_state(
1482 const KEY_EVENT_RECORD* const key_event) {
1483 DWORD control_key_state = key_event->dwControlKeyState;
1484
1485 // If we're in an AltGr situation where the AltGr key is down (depending on
1486 // the keyboard layout, that might be the physical right alt key which
1487 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
1488 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
1489 // a character (which indicates that there was an AltGr mapping), then act
1490 // as if alt and control are not really down for the purposes of modifiers.
1491 // This makes it so that if the user with, say, a German keyboard layout
1492 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
1493 // output the key and we don't see the Alt and Ctrl keys.
1494 if (_is_ctrl_pressed(control_key_state) &&
1495 _is_alt_pressed(control_key_state)
1496 && (key_event->uChar.AsciiChar != '\0')) {
1497 // Try to remove as few bits as possible to improve our chances of
1498 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
1499 // Left-Alt + Right-Ctrl + AltGr.
1500 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
1501 // Remove Right-Alt.
1502 control_key_state &= ~RIGHT_ALT_PRESSED;
1503 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
1504 // pressed, Left-Ctrl is almost always set, except if the user
1505 // presses Right-Ctrl, then AltGr (in that specific order) for
1506 // whatever reason. At any rate, make sure the bit is not set.
1507 control_key_state &= ~LEFT_CTRL_PRESSED;
1508 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
1509 // Remove Left-Alt.
1510 control_key_state &= ~LEFT_ALT_PRESSED;
1511 // Whichever Ctrl key is down, remove it from the state. We only
1512 // remove one key, to improve our chances of detecting the
1513 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
1514 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
1515 // Remove Left-Ctrl.
1516 control_key_state &= ~LEFT_CTRL_PRESSED;
1517 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
1518 // Remove Right-Ctrl.
1519 control_key_state &= ~RIGHT_CTRL_PRESSED;
1520 }
1521 }
1522
1523 // Note that this logic isn't 100% perfect because Windows doesn't
1524 // allow us to detect all combinations because a physical AltGr key
1525 // press shows up as two bits, plus some combinations are ambiguous
1526 // about what is actually physically pressed.
1527 }
1528
1529 return control_key_state;
1530}
1531
1532// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
1533// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
1534// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
1535// appropriately.
1536static DWORD _normalize_keypad_control_key_state(const WORD vk,
1537 const DWORD control_key_state) {
1538 if (!_is_numlock_on(control_key_state)) {
1539 return control_key_state;
1540 }
1541 if (!_is_enhanced_key(control_key_state)) {
1542 switch (vk) {
1543 case VK_INSERT: // 0
1544 case VK_DELETE: // .
1545 case VK_END: // 1
1546 case VK_DOWN: // 2
1547 case VK_NEXT: // 3
1548 case VK_LEFT: // 4
1549 case VK_CLEAR: // 5
1550 case VK_RIGHT: // 6
1551 case VK_HOME: // 7
1552 case VK_UP: // 8
1553 case VK_PRIOR: // 9
1554 return control_key_state | SHIFT_PRESSED;
1555 }
1556 }
1557
1558 return control_key_state;
1559}
1560
1561static const char* _get_keypad_sequence(const DWORD control_key_state,
1562 const char* const normal, const char* const shifted) {
1563 if (_is_shift_pressed(control_key_state)) {
1564 // Shift is pressed and NumLock is off
1565 return shifted;
1566 } else {
1567 // Shift is not pressed and NumLock is off, or,
1568 // Shift is pressed and NumLock is on, in which case we want the
1569 // NumLock and Shift to neutralize each other, thus, we want the normal
1570 // sequence.
1571 return normal;
1572 }
1573 // If Shift is not pressed and NumLock is on, a different virtual key code
1574 // is returned by Windows, which can be taken care of by a different case
1575 // statement in _console_read().
1576}
1577
1578// Write sequence to buf and return the number of bytes written.
1579static size_t _get_modifier_sequence(char* const buf, const WORD vk,
1580 DWORD control_key_state, const char* const normal) {
1581 // Copy the base sequence into buf.
1582 const size_t len = strlen(normal);
1583 memcpy(buf, normal, len);
1584
1585 int code = 0;
1586
1587 control_key_state = _normalize_keypad_control_key_state(vk,
1588 control_key_state);
1589
1590 if (_is_shift_pressed(control_key_state)) {
1591 code |= 0x1;
1592 }
1593 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
1594 code |= 0x2;
1595 }
1596 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
1597 code |= 0x4;
1598 }
1599 // If some modifier was held down, then we need to insert the modifier code
1600 if (code != 0) {
1601 if (len == 0) {
1602 // Should be impossible because caller should pass a string of
1603 // non-zero length.
1604 return 0;
1605 }
1606 size_t index = len - 1;
1607 const char lastChar = buf[index];
1608 if (lastChar != '~') {
1609 buf[index++] = '1';
1610 }
1611 buf[index++] = ';'; // modifier separator
1612 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
1613 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
1614 buf[index++] = '1' + code;
1615 buf[index++] = lastChar; // move ~ (or other last char) to the end
1616 return index;
1617 }
1618 return len;
1619}
1620
1621// Write sequence to buf and return the number of bytes written.
1622static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
1623 const DWORD control_key_state, const char* const normal,
1624 const char shifted) {
1625 if (_is_shift_pressed(control_key_state)) {
1626 // Shift is pressed and NumLock is off
1627 if (shifted != '\0') {
1628 buf[0] = shifted;
1629 return sizeof(buf[0]);
1630 } else {
1631 return 0;
1632 }
1633 } else {
1634 // Shift is not pressed and NumLock is off, or,
1635 // Shift is pressed and NumLock is on, in which case we want the
1636 // NumLock and Shift to neutralize each other, thus, we want the normal
1637 // sequence.
1638 return _get_modifier_sequence(buf, vk, control_key_state, normal);
1639 }
1640 // If Shift is not pressed and NumLock is on, a different virtual key code
1641 // is returned by Windows, which can be taken care of by a different case
1642 // statement in _console_read().
1643}
1644
1645// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
1646// Standard German. Figure this out at runtime so we know what to output for
1647// Shift-VK_DELETE.
1648static char _get_decimal_char() {
1649 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
1650}
1651
1652// Prefix the len bytes in buf with the escape character, and then return the
1653// new buffer length.
1654size_t _escape_prefix(char* const buf, const size_t len) {
1655 // If nothing to prefix, don't do anything. We might be called with
1656 // len == 0, if alt was held down with a dead key which produced nothing.
1657 if (len == 0) {
1658 return 0;
1659 }
1660
1661 memmove(&buf[1], buf, len);
1662 buf[0] = '\x1b';
1663 return len + 1;
1664}
1665
Spencer Low32762f42015-11-10 19:17:16 -08001666// Internal buffer to satisfy future _console_read() calls.
Josh Gaob7b1edf2015-11-11 17:56:12 -08001667static auto& g_console_input_buffer = *new std::vector<char>();
Spencer Low32762f42015-11-10 19:17:16 -08001668
1669// Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never
1670// returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell).
Spencer Low50184062015-03-01 15:06:21 -08001671static int _console_read(const HANDLE console, void* buf, size_t len) {
1672 for (;;) {
Spencer Low32762f42015-11-10 19:17:16 -08001673 // Read of zero bytes should not block waiting for something from the console.
1674 if (len == 0) {
1675 return 0;
1676 }
1677
1678 // Flush as much as possible from input buffer.
1679 if (!g_console_input_buffer.empty()) {
1680 const int bytes_read = std::min(len, g_console_input_buffer.size());
1681 memcpy(buf, g_console_input_buffer.data(), bytes_read);
1682 const auto begin = g_console_input_buffer.begin();
1683 g_console_input_buffer.erase(begin, begin + bytes_read);
1684 return bytes_read;
1685 }
1686
1687 // Read from the actual console. This may block until input.
1688 INPUT_RECORD input_record;
1689 if (!_get_key_event_record(console, &input_record)) {
Spencer Low50184062015-03-01 15:06:21 -08001690 return -1;
1691 }
1692
Spencer Low32762f42015-11-10 19:17:16 -08001693 KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent;
Spencer Low50184062015-03-01 15:06:21 -08001694 const WORD vk = key_event->wVirtualKeyCode;
1695 const CHAR ch = key_event->uChar.AsciiChar;
1696 const DWORD control_key_state = _normalize_altgr_control_key_state(
1697 key_event);
1698
1699 // The following emulation code should write the output sequence to
1700 // either seqstr or to seqbuf and seqbuflen.
Yi Kongaed415c2018-07-13 18:15:16 -07001701 const char* seqstr = nullptr; // NULL terminated C-string
Spencer Low50184062015-03-01 15:06:21 -08001702 // Enough space for max sequence string below, plus modifiers and/or
1703 // escape prefix.
1704 char seqbuf[16];
1705 size_t seqbuflen = 0; // Space used in seqbuf.
1706
1707#define MATCH(vk, normal) \
1708 case (vk): \
1709 { \
1710 seqstr = (normal); \
1711 } \
1712 break;
1713
1714 // Modifier keys should affect the output sequence.
1715#define MATCH_MODIFIER(vk, normal) \
1716 case (vk): \
1717 { \
1718 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
1719 control_key_state, (normal)); \
1720 } \
1721 break;
1722
1723 // The shift key should affect the output sequence.
1724#define MATCH_KEYPAD(vk, normal, shifted) \
1725 case (vk): \
1726 { \
1727 seqstr = _get_keypad_sequence(control_key_state, (normal), \
1728 (shifted)); \
1729 } \
1730 break;
1731
1732 // The shift key and other modifier keys should affect the output
1733 // sequence.
1734#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
1735 case (vk): \
1736 { \
1737 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
1738 control_key_state, (normal), (shifted)); \
1739 } \
1740 break;
1741
1742#define ESC "\x1b"
1743#define CSI ESC "["
1744#define SS3 ESC "O"
1745
1746 // Only support normal mode, not application mode.
1747
1748 // Enhanced keys:
1749 // * 6-pack: insert, delete, home, end, page up, page down
1750 // * cursor keys: up, down, right, left
1751 // * keypad: divide, enter
1752 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
1753 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
1754 if (_is_enhanced_key(control_key_state)) {
1755 switch (vk) {
1756 case VK_RETURN: // Enter key on keypad
1757 if (_is_ctrl_pressed(control_key_state)) {
1758 seqstr = "\n";
1759 } else {
1760 seqstr = "\r";
1761 }
1762 break;
1763
1764 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
1765 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
1766
1767 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
1768 // will be fixed soon to match xterm which sends CSI "F" and
1769 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
1770 MATCH(VK_END, CSI "F");
1771 MATCH(VK_HOME, CSI "H");
1772
1773 MATCH_MODIFIER(VK_LEFT, CSI "D");
1774 MATCH_MODIFIER(VK_UP, CSI "A");
1775 MATCH_MODIFIER(VK_RIGHT, CSI "C");
1776 MATCH_MODIFIER(VK_DOWN, CSI "B");
1777
1778 MATCH_MODIFIER(VK_INSERT, CSI "2~");
1779 MATCH_MODIFIER(VK_DELETE, CSI "3~");
1780
1781 MATCH(VK_DIVIDE, "/");
1782 }
1783 } else { // Non-enhanced keys:
1784 switch (vk) {
1785 case VK_BACK: // backspace
1786 if (_is_alt_pressed(control_key_state)) {
1787 seqstr = ESC "\x7f";
1788 } else {
1789 seqstr = "\x7f";
1790 }
1791 break;
1792
1793 case VK_TAB:
1794 if (_is_shift_pressed(control_key_state)) {
1795 seqstr = CSI "Z";
1796 } else {
1797 seqstr = "\t";
1798 }
1799 break;
1800
1801 // Number 5 key in keypad when NumLock is off, or if NumLock is
1802 // on and Shift is down.
1803 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
1804
1805 case VK_RETURN: // Enter key on main keyboard
1806 if (_is_alt_pressed(control_key_state)) {
1807 seqstr = ESC "\n";
1808 } else if (_is_ctrl_pressed(control_key_state)) {
1809 seqstr = "\n";
1810 } else {
1811 seqstr = "\r";
1812 }
1813 break;
1814
1815 // VK_ESCAPE: Don't do any special handling. The OS uses many
1816 // of the sequences with Escape and many of the remaining
1817 // sequences don't produce bKeyDown messages, only !bKeyDown
1818 // for whatever reason.
1819
1820 case VK_SPACE:
1821 if (_is_alt_pressed(control_key_state)) {
1822 seqstr = ESC " ";
1823 } else if (_is_ctrl_pressed(control_key_state)) {
1824 seqbuf[0] = '\0'; // NULL char
1825 seqbuflen = 1;
1826 } else {
1827 seqstr = " ";
1828 }
1829 break;
1830
1831 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
1832 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
1833
1834 MATCH_KEYPAD(VK_END, CSI "4~", "1");
1835 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
1836
1837 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
1838 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
1839 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
1840 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
1841
1842 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
1843 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
1844 _get_decimal_char());
1845
1846 case 0x30: // 0
1847 case 0x31: // 1
1848 case 0x39: // 9
1849 case VK_OEM_1: // ;:
1850 case VK_OEM_PLUS: // =+
1851 case VK_OEM_COMMA: // ,<
1852 case VK_OEM_PERIOD: // .>
1853 case VK_OEM_7: // '"
1854 case VK_OEM_102: // depends on keyboard, could be <> or \|
1855 case VK_OEM_2: // /?
1856 case VK_OEM_3: // `~
1857 case VK_OEM_4: // [{
1858 case VK_OEM_5: // \|
1859 case VK_OEM_6: // ]}
1860 {
1861 seqbuflen = _get_control_character(seqbuf, key_event,
1862 control_key_state);
1863
1864 if (_is_alt_pressed(control_key_state)) {
1865 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1866 }
1867 }
1868 break;
1869
1870 case 0x32: // 2
Spencer Low32762f42015-11-10 19:17:16 -08001871 case 0x33: // 3
1872 case 0x34: // 4
1873 case 0x35: // 5
Spencer Low50184062015-03-01 15:06:21 -08001874 case 0x36: // 6
Spencer Low32762f42015-11-10 19:17:16 -08001875 case 0x37: // 7
1876 case 0x38: // 8
Spencer Low50184062015-03-01 15:06:21 -08001877 case VK_OEM_MINUS: // -_
1878 {
1879 seqbuflen = _get_control_character(seqbuf, key_event,
1880 control_key_state);
1881
1882 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
1883 // prefix with escape.
1884 if (_is_alt_pressed(control_key_state) &&
1885 !(_is_ctrl_pressed(control_key_state) &&
1886 !_is_shift_pressed(control_key_state))) {
1887 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1888 }
1889 }
1890 break;
1891
Spencer Low50184062015-03-01 15:06:21 -08001892 case 0x41: // a
1893 case 0x42: // b
1894 case 0x43: // c
1895 case 0x44: // d
1896 case 0x45: // e
1897 case 0x46: // f
1898 case 0x47: // g
1899 case 0x48: // h
1900 case 0x49: // i
1901 case 0x4a: // j
1902 case 0x4b: // k
1903 case 0x4c: // l
1904 case 0x4d: // m
1905 case 0x4e: // n
1906 case 0x4f: // o
1907 case 0x50: // p
1908 case 0x51: // q
1909 case 0x52: // r
1910 case 0x53: // s
1911 case 0x54: // t
1912 case 0x55: // u
1913 case 0x56: // v
1914 case 0x57: // w
1915 case 0x58: // x
1916 case 0x59: // y
1917 case 0x5a: // z
1918 {
1919 seqbuflen = _get_non_alt_char(seqbuf, key_event,
1920 control_key_state);
1921
1922 // If Alt is pressed, then prefix with escape.
1923 if (_is_alt_pressed(control_key_state)) {
1924 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
1925 }
1926 }
1927 break;
1928
1929 // These virtual key codes are generated by the keys on the
1930 // keypad *when NumLock is on* and *Shift is up*.
1931 MATCH(VK_NUMPAD0, "0");
1932 MATCH(VK_NUMPAD1, "1");
1933 MATCH(VK_NUMPAD2, "2");
1934 MATCH(VK_NUMPAD3, "3");
1935 MATCH(VK_NUMPAD4, "4");
1936 MATCH(VK_NUMPAD5, "5");
1937 MATCH(VK_NUMPAD6, "6");
1938 MATCH(VK_NUMPAD7, "7");
1939 MATCH(VK_NUMPAD8, "8");
1940 MATCH(VK_NUMPAD9, "9");
1941
1942 MATCH(VK_MULTIPLY, "*");
1943 MATCH(VK_ADD, "+");
1944 MATCH(VK_SUBTRACT, "-");
1945 // VK_DECIMAL is generated by the . key on the keypad *when
1946 // NumLock is on* and *Shift is up* and the sequence is not
1947 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
1948 // Windows Security screen to come up).
1949 case VK_DECIMAL:
1950 // U.S. English uses '.', Germany German uses ','.
1951 seqbuflen = _get_non_control_char(seqbuf, key_event,
1952 control_key_state);
1953 break;
1954
1955 MATCH_MODIFIER(VK_F1, SS3 "P");
1956 MATCH_MODIFIER(VK_F2, SS3 "Q");
1957 MATCH_MODIFIER(VK_F3, SS3 "R");
1958 MATCH_MODIFIER(VK_F4, SS3 "S");
1959 MATCH_MODIFIER(VK_F5, CSI "15~");
1960 MATCH_MODIFIER(VK_F6, CSI "17~");
1961 MATCH_MODIFIER(VK_F7, CSI "18~");
1962 MATCH_MODIFIER(VK_F8, CSI "19~");
1963 MATCH_MODIFIER(VK_F9, CSI "20~");
1964 MATCH_MODIFIER(VK_F10, CSI "21~");
1965 MATCH_MODIFIER(VK_F11, CSI "23~");
1966 MATCH_MODIFIER(VK_F12, CSI "24~");
1967
1968 MATCH_MODIFIER(VK_F13, CSI "25~");
1969 MATCH_MODIFIER(VK_F14, CSI "26~");
1970 MATCH_MODIFIER(VK_F15, CSI "28~");
1971 MATCH_MODIFIER(VK_F16, CSI "29~");
1972 MATCH_MODIFIER(VK_F17, CSI "31~");
1973 MATCH_MODIFIER(VK_F18, CSI "32~");
1974 MATCH_MODIFIER(VK_F19, CSI "33~");
1975 MATCH_MODIFIER(VK_F20, CSI "34~");
1976
1977 // MATCH_MODIFIER(VK_F21, ???);
1978 // MATCH_MODIFIER(VK_F22, ???);
1979 // MATCH_MODIFIER(VK_F23, ???);
1980 // MATCH_MODIFIER(VK_F24, ???);
1981 }
1982 }
1983
1984#undef MATCH
1985#undef MATCH_MODIFIER
1986#undef MATCH_KEYPAD
1987#undef MATCH_MODIFIER_KEYPAD
1988#undef ESC
1989#undef CSI
1990#undef SS3
1991
1992 const char* out;
1993 size_t outlen;
1994
1995 // Check for output in any of:
1996 // * seqstr is set (and strlen can be used to determine the length).
1997 // * seqbuf and seqbuflen are set
1998 // Fallback to ch from Windows.
Yi Kongaed415c2018-07-13 18:15:16 -07001999 if (seqstr != nullptr) {
Spencer Low50184062015-03-01 15:06:21 -08002000 out = seqstr;
2001 outlen = strlen(seqstr);
2002 } else if (seqbuflen > 0) {
2003 out = seqbuf;
2004 outlen = seqbuflen;
2005 } else if (ch != '\0') {
2006 // Use whatever Windows told us it is.
2007 seqbuf[0] = ch;
2008 seqbuflen = 1;
2009 out = seqbuf;
2010 outlen = seqbuflen;
2011 } else {
2012 // No special handling for the virtual key code and Windows isn't
2013 // telling us a character code, then we don't know how to translate
2014 // the key press.
2015 //
2016 // Consume the input and 'continue' to cause us to get a new key
2017 // event.
Yabin Cui7a3f8d62015-09-02 17:44:28 -07002018 D("_console_read: unknown virtual key code: %d, enhanced: %s",
Spencer Low50184062015-03-01 15:06:21 -08002019 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
Spencer Low50184062015-03-01 15:06:21 -08002020 continue;
2021 }
2022
Spencer Low32762f42015-11-10 19:17:16 -08002023 // put output wRepeatCount times into g_console_input_buffer
2024 while (key_event->wRepeatCount-- > 0) {
2025 g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen);
Spencer Low50184062015-03-01 15:06:21 -08002026 }
2027
Spencer Low32762f42015-11-10 19:17:16 -08002028 // Loop around and try to flush g_console_input_buffer
Spencer Low50184062015-03-01 15:06:21 -08002029 }
2030}
2031
2032static DWORD _old_console_mode; // previous GetConsoleMode() result
2033static HANDLE _console_handle; // when set, console mode should be restored
2034
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002035void stdin_raw_init() {
2036 const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002037 if (in == nullptr) {
2038 return;
2039 }
Spencer Low50184062015-03-01 15:06:21 -08002040
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002041 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
2042 // calling the process Ctrl-C routine (configured by
2043 // SetConsoleCtrlHandler()).
2044 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
2045 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
2046 // flag also seems necessary to have proper line-ending processing.
Spencer Low2e02dc62015-11-07 17:34:39 -08002047 DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
2048 ENABLE_LINE_INPUT |
2049 ENABLE_ECHO_INPUT);
2050 // Enable ENABLE_WINDOW_INPUT to get window resizes.
2051 new_console_mode |= ENABLE_WINDOW_INPUT;
2052
2053 if (!SetConsoleMode(in, new_console_mode)) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002054 // This really should not fail.
2055 D("stdin_raw_init: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002056 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002057 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002058
2059 // Once this is set, it means that stdin has been configured for
2060 // reading from and that the old console mode should be restored later.
2061 _console_handle = in;
2062
2063 // Note that we don't need to configure C Runtime line-ending
2064 // translation because _console_read() does not call the C Runtime to
2065 // read from the console.
Spencer Low50184062015-03-01 15:06:21 -08002066}
2067
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002068void stdin_raw_restore() {
Yi Kongaed415c2018-07-13 18:15:16 -07002069 if (_console_handle != nullptr) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002070 const HANDLE in = _console_handle;
Yi Kongaed415c2018-07-13 18:15:16 -07002071 _console_handle = nullptr; // clear state
Spencer Low50184062015-03-01 15:06:21 -08002072
Elliott Hughesc15b17f2015-11-03 11:18:40 -08002073 if (!SetConsoleMode(in, _old_console_mode)) {
2074 // This really should not fail.
2075 D("stdin_raw_restore: SetConsoleMode() failed: %s",
David Pursell5f787ed2016-01-27 08:52:53 -08002076 android::base::SystemErrorCodeToString(GetLastError()).c_str());
Spencer Low50184062015-03-01 15:06:21 -08002077 }
2078 }
2079}
2080
Spencer Low2e02dc62015-11-07 17:34:39 -08002081// Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin.
2082int unix_read_interruptible(int fd, void* buf, size_t len) {
Yi Kongaed415c2018-07-13 18:15:16 -07002083 if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) {
Spencer Low50184062015-03-01 15:06:21 -08002084 // If it is a request to read from stdin, and stdin_raw_init() has been
2085 // called, and it successfully configured the console, then read from
2086 // the console using Win32 console APIs and partially emulate a unix
2087 // terminal.
2088 return _console_read(_console_handle, buf, len);
2089 } else {
David Pursell1ed57f02015-10-06 15:30:03 -07002090 // On older versions of Windows (definitely 7, definitely not 10),
2091 // ReadConsole() with a size >= 31367 fails, so if |fd| is a console
David Pursellc5b8ad82015-10-28 14:29:51 -07002092 // we need to limit the read size.
2093 if (len > 4096 && unix_isatty(fd)) {
David Pursell1ed57f02015-10-06 15:30:03 -07002094 len = 4096;
2095 }
Spencer Low50184062015-03-01 15:06:21 -08002096 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002097 // can do LF/CR translation (which is overridable with _setmode()).
2098 // Undefine the macro that is set in sysdeps.h which bans calls to
2099 // plain read() in favor of unix_read() or adb_read().
2100#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002101#undef read
2102 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07002103#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08002104 }
2105}
Spencer Lowcf4ff642015-05-11 01:08:48 -07002106
2107/**************************************************************************/
2108/**************************************************************************/
2109/***** *****/
2110/***** Unicode support *****/
2111/***** *****/
2112/**************************************************************************/
2113/**************************************************************************/
2114
2115// This implements support for using files with Unicode filenames and for
2116// outputting Unicode text to a Win32 console window. This is inspired from
2117// http://utf8everywhere.org/.
2118//
2119// Background
2120// ----------
2121//
2122// On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8
2123// filenames to APIs such as open(). This works because filenames are largely
2124// opaque 'cookies' (perhaps excluding path separators).
2125//
2126// On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t
2127// UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char
2128// strings, but the strings are in the ANSI codepage and not UTF-8. (The
2129// CreateFile() API is really just a macro that adds the W/A based on whether
2130// the UNICODE preprocessor symbol is defined).
2131//
2132// Options
2133// -------
2134//
2135// Thus, to write a portable program, there are a few options:
2136//
2137// 1. Write the program with wchar_t filenames (wchar_t path[256];).
2138// For Windows, just call CreateFileW(). For POSIX, write a wrapper openW()
2139// that takes a wchar_t string, converts it to UTF-8 and then calls the real
2140// open() API.
2141//
2142// 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and
2143// 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those,
2144// potentially touching a lot of code.
2145//
2146// 3. Write the program with a 1-byte char filenames (char path[256];) that are
2147// UTF-8. For POSIX, just call open(). For Windows, write a wrapper that
2148// takes a UTF-8 string, converts it to UTF-16 and then calls the real OS
2149// or C Runtime API.
2150//
2151// The Choice
2152// ----------
2153//
Spencer Lowd21dc822015-11-12 15:20:15 -08002154// The code below chooses option 3, the UTF-8 everywhere strategy. It uses
2155// android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the
Spencer Lowcf4ff642015-05-11 01:08:48 -07002156// NarrowArgs helper class that is used to convert wmain() args into UTF-8
Spencer Lowd21dc822015-11-12 15:20:15 -08002157// args that are passed to main() at the beginning of program startup. We also use
2158// android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to
Spencer Lowcf4ff642015-05-11 01:08:48 -07002159// implement wrappers below that call UTF-16 OS and C Runtime APIs.
2160//
2161// Unicode console output
2162// ----------------------
2163//
2164// The way to output Unicode to a Win32 console window is to call
2165// WriteConsoleW() with UTF-16 text. (The user must also choose a proper font
Spencer Lowe347c1d2015-08-02 18:13:54 -07002166// such as Lucida Console or Consolas, and in the case of East Asian languages
2167// (such as Chinese, Japanese, Korean), the user must go to the Control Panel
2168// and change the "system locale" to Chinese, etc., which allows a Chinese, etc.
2169// font to be used in console windows.)
Spencer Lowcf4ff642015-05-11 01:08:48 -07002170//
2171// The problem is getting the C Runtime to make fprintf and related APIs call
2172// WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds
2173// promising, but the various modes have issues:
2174//
2175// 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and
2176// UTF-16 do not display properly.
2177// 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out
2178// totally wrong.
2179// 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter
2180// handler to be called (upon a later I/O call), aborting the process.
2181// 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf
2182// to output nothing.
2183//
2184// So the only solution is to write our own adb_fprintf() that converts UTF-8
2185// to UTF-16 and then calls WriteConsoleW().
2186
2187
Spencer Lowcf4ff642015-05-11 01:08:48 -07002188// Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to
2189// be passed to main().
2190NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) {
2191 narrow_args = new char*[argc + 1];
2192
2193 for (int i = 0; i < argc; ++i) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002194 std::string arg_narrow;
2195 if (!android::base::WideToUTF8(argv[i], &arg_narrow)) {
2196 fatal_errno("cannot convert argument from UTF-16 to UTF-8");
2197 }
2198 narrow_args[i] = strdup(arg_narrow.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002199 }
2200 narrow_args[argc] = nullptr; // terminate
2201}
2202
2203NarrowArgs::~NarrowArgs() {
2204 if (narrow_args != nullptr) {
2205 for (char** argp = narrow_args; *argp != nullptr; ++argp) {
2206 free(*argp);
2207 }
2208 delete[] narrow_args;
2209 narrow_args = nullptr;
2210 }
2211}
2212
2213int unix_open(const char* path, int options, ...) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002214 std::wstring path_wide;
2215 if (!android::base::UTF8ToWide(path, &path_wide)) {
2216 return -1;
2217 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002218 if ((options & O_CREAT) == 0) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002219 return _wopen(path_wide.c_str(), options);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002220 } else {
2221 int mode;
2222 va_list args;
2223 va_start(args, options);
2224 mode = va_arg(args, int);
2225 va_end(args);
Spencer Lowd21dc822015-11-12 15:20:15 -08002226 return _wopen(path_wide.c_str(), options, mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002227 }
2228}
2229
Spencer Lowcf4ff642015-05-11 01:08:48 -07002230// Version of opendir() that takes a UTF-8 path.
Spencer Lowd21dc822015-11-12 15:20:15 -08002231DIR* adb_opendir(const char* path) {
2232 std::wstring path_wide;
2233 if (!android::base::UTF8ToWide(path, &path_wide)) {
2234 return nullptr;
2235 }
2236
Spencer Lowcf4ff642015-05-11 01:08:48 -07002237 // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of
2238 // the fields, but right now all the callers treat the structure as
2239 // opaque.
Spencer Lowd21dc822015-11-12 15:20:15 -08002240 return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str()));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002241}
2242
2243// Version of readdir() that returns UTF-8 paths.
2244struct dirent* adb_readdir(DIR* dir) {
2245 _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir);
2246 struct _wdirent* const went = _wreaddir(wdir);
2247 if (went == nullptr) {
2248 return nullptr;
2249 }
Spencer Lowd21dc822015-11-12 15:20:15 -08002250
Spencer Lowcf4ff642015-05-11 01:08:48 -07002251 // Convert from UTF-16 to UTF-8.
Spencer Lowd21dc822015-11-12 15:20:15 -08002252 std::string name_utf8;
2253 if (!android::base::WideToUTF8(went->d_name, &name_utf8)) {
2254 return nullptr;
2255 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002256
2257 // Cast the _wdirent* to dirent* and overwrite the d_name field (which has
2258 // space for UTF-16 wchar_t's) with UTF-8 char's.
2259 struct dirent* ent = reinterpret_cast<struct dirent*>(went);
2260
2261 if (name_utf8.length() + 1 > sizeof(went->d_name)) {
2262 // Name too big to fit in existing buffer.
2263 errno = ENOMEM;
2264 return nullptr;
2265 }
2266
2267 // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name)
2268 // because _wdirent contains wchar_t instead of char. So even if name_utf8
2269 // can fit in _wdirent::d_name, the resulting dirent::d_name field may be
2270 // bigger than the caller expects because they expect a dirent structure
2271 // which has a smaller d_name field. Ignore this since the caller should be
2272 // resilient.
2273
2274 // Rewrite the UTF-16 d_name field to UTF-8.
2275 strcpy(ent->d_name, name_utf8.c_str());
2276
2277 return ent;
2278}
2279
2280// Version of closedir() to go with our version of adb_opendir().
2281int adb_closedir(DIR* dir) {
2282 return _wclosedir(reinterpret_cast<_WDIR*>(dir));
2283}
2284
2285// Version of unlink() that takes a UTF-8 path.
2286int adb_unlink(const char* path) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002287 std::wstring wpath;
2288 if (!android::base::UTF8ToWide(path, &wpath)) {
2289 return -1;
2290 }
Spencer Lowcf4ff642015-05-11 01:08:48 -07002291
2292 int rc = _wunlink(wpath.c_str());
2293
2294 if (rc == -1 && errno == EACCES) {
2295 /* unlink returns EACCES when the file is read-only, so we first */
2296 /* try to make it writable, then unlink again... */
2297 rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE);
2298 if (rc == 0)
2299 rc = _wunlink(wpath.c_str());
2300 }
2301 return rc;
2302}
2303
2304// Version of mkdir() that takes a UTF-8 path.
2305int adb_mkdir(const std::string& path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002306 std::wstring path_wide;
2307 if (!android::base::UTF8ToWide(path, &path_wide)) {
2308 return -1;
2309 }
2310
2311 return _wmkdir(path_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002312}
2313
2314// Version of utime() that takes a UTF-8 path.
2315int adb_utime(const char* path, struct utimbuf* u) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002316 std::wstring path_wide;
2317 if (!android::base::UTF8ToWide(path, &path_wide)) {
2318 return -1;
2319 }
2320
Spencer Lowcf4ff642015-05-11 01:08:48 -07002321 static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf),
2322 "utimbuf and _utimbuf should be the same size because they both "
2323 "contain the same types, namely time_t");
Spencer Lowd21dc822015-11-12 15:20:15 -08002324 return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002325}
2326
2327// Version of chmod() that takes a UTF-8 path.
2328int adb_chmod(const char* path, int mode) {
Spencer Lowd21dc822015-11-12 15:20:15 -08002329 std::wstring path_wide;
2330 if (!android::base::UTF8ToWide(path, &path_wide)) {
2331 return -1;
2332 }
2333
2334 return _wchmod(path_wide.c_str(), mode);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002335}
2336
Spencer Lowa30b79a2015-11-15 16:29:36 -08002337// From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte.
2338static inline size_t utf8_codepoint_len(uint8_t ch) {
2339 return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1;
2340}
Elliott Hughesc1fd4922015-11-11 18:02:29 +00002341
Spencer Lowa30b79a2015-11-15 16:29:36 -08002342namespace internal {
2343
2344// Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes
2345// (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to
2346// remaining_bytes.
2347size_t ParseCompleteUTF8(const char* const first, const char* const last,
2348 std::vector<char>* const remaining_bytes) {
2349 // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence.
2350 // Current_after points one byte past the current byte to be examined.
2351 for (const char* current_after = last; current_after != first; --current_after) {
2352 const char* const current = current_after - 1;
2353 const char ch = *current;
2354 const char kHighBit = 0x80u;
2355 const char kTwoHighestBits = 0xC0u;
2356 if ((ch & kHighBit) == 0) { // high bit not set
2357 // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing
2358 // bytes with no leading byte, so return the entire buffer.
2359 break;
2360 } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set
2361 // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence.
2362 const size_t bytes_available = last - current;
2363 if (bytes_available < utf8_codepoint_len(ch)) {
2364 // We don't have all the bytes in the UTF-8 sequence, so return all the bytes
2365 // preceding the current incomplete UTF-8 sequence and append the remaining bytes
2366 // to remaining_bytes.
2367 remaining_bytes->insert(remaining_bytes->end(), current, last);
2368 return current - first;
2369 } else {
2370 // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid
2371 // trailing bytes with no lead byte, so return the entire buffer.
2372 break;
2373 }
2374 } else {
2375 // Trailing byte, so keep going backwards looking for the lead byte.
2376 }
2377 }
2378
2379 // Return the size of the entire buffer. It is possible that we walked backward past invalid
2380 // trailing bytes with no lead byte, in which case we want to return all those invalid bytes
2381 // so that they can be processed.
2382 return last - first;
2383}
2384
2385}
2386
2387// Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences.
2388// Note that we use only one buffer even though stderr and stdout are logically separate streams.
2389// This matches the behavior of Linux.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002390
2391// Internal helper function to write UTF-8 bytes to a console. Returns -1 on error.
2392static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream,
2393 HANDLE console) {
Josh Gao0cd3ae12016-09-21 12:37:10 -07002394 static std::mutex& console_output_buffer_lock = *new std::mutex();
2395 static auto& console_output_buffer = *new std::vector<char>();
2396
Spencer Lowa30b79a2015-11-15 16:29:36 -08002397 const int saved_errno = errno;
2398 std::vector<char> combined_buffer;
2399
2400 // Complete UTF-8 sequences that should be immediately written to the console.
2401 const char* utf8;
2402 size_t utf8_size;
2403
Josh Gao0cd3ae12016-09-21 12:37:10 -07002404 {
2405 std::lock_guard<std::mutex> lock(console_output_buffer_lock);
2406 if (console_output_buffer.empty()) {
2407 // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the
2408 // common case with plain ASCII), parse buf directly.
2409 utf8 = buf;
2410 utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer);
2411 } else {
2412 // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to
2413 // combined_buffer (and effectively clear console_output_buffer) and append buf to
2414 // combined_buffer, then parse it all together.
2415 combined_buffer.swap(console_output_buffer);
2416 combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002417
Josh Gao0cd3ae12016-09-21 12:37:10 -07002418 utf8 = combined_buffer.data();
2419 utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(),
2420 &console_output_buffer);
2421 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002422 }
Spencer Lowa30b79a2015-11-15 16:29:36 -08002423
2424 std::wstring utf16;
2425
2426 // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux
2427 // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's
2428 // random data, runs dmesg (which might have non-UTF-8), etc.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002429 // This could throw std::bad_alloc.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002430 (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002431
2432 // Note that this does not do \n => \r\n translation because that
2433 // doesn't seem necessary for the Windows console. For the Windows
2434 // console \r moves to the beginning of the line and \n moves to a new
2435 // line.
2436
2437 // Flush any stream buffering so that our output is afterwards which
2438 // makes sense because our call is afterwards.
2439 (void)fflush(stream);
2440
2441 // Write UTF-16 to the console.
2442 DWORD written = 0;
Yi Kongaed415c2018-07-13 18:15:16 -07002443 if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002444 errno = EIO;
2445 return -1;
2446 }
2447
Spencer Lowa30b79a2015-11-15 16:29:36 -08002448 // Return the size of the original buffer passed in, signifying that we consumed it all, even
2449 // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This
2450 // matches the Linux behavior.
2451 errno = saved_errno;
2452 return buf_size;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002453}
2454
2455// Function prototype because attributes cannot be placed on func definitions.
Elliott Hughesd8a4c602018-06-26 13:06:15 -07002456static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap)
2457 __attribute__((__format__(__printf__, 3, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002458
2459// Internal function to format a UTF-8 string and write it to a Win32 console.
2460// Returns -1 on error.
2461static int _console_vfprintf(const HANDLE console, FILE* stream,
2462 const char *format, va_list ap) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002463 const int saved_errno = errno;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002464 std::string output_utf8;
2465
2466 // Format the string.
2467 // This could throw std::bad_alloc.
2468 android::base::StringAppendV(&output_utf8, format, ap);
2469
Spencer Lowa30b79a2015-11-15 16:29:36 -08002470 const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream,
2471 console);
2472 if (result != -1) {
2473 errno = saved_errno;
2474 } else {
2475 // If -1 was returned, errno has been set.
2476 }
2477 return result;
Spencer Lowcf4ff642015-05-11 01:08:48 -07002478}
2479
2480// Version of vfprintf() that takes UTF-8 and can write Unicode to a
2481// Windows console.
2482int adb_vfprintf(FILE *stream, const char *format, va_list ap) {
2483 const HANDLE console = _get_console_handle(stream);
2484
2485 // If there is an associated Win32 console, write to it specially,
2486 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002487 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002488 return _console_vfprintf(console, stream, format, ap);
2489 } else {
2490 // If vfprintf is a macro, undefine it, so we can call the real
2491 // C Runtime API.
2492#pragma push_macro("vfprintf")
2493#undef vfprintf
2494 return vfprintf(stream, format, ap);
2495#pragma pop_macro("vfprintf")
2496 }
2497}
2498
Spencer Lowa30b79a2015-11-15 16:29:36 -08002499// Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console.
2500int adb_vprintf(const char *format, va_list ap) {
2501 return adb_vfprintf(stdout, format, ap);
2502}
2503
Spencer Lowcf4ff642015-05-11 01:08:48 -07002504// Version of fprintf() that takes UTF-8 and can write Unicode to a
2505// Windows console.
2506int adb_fprintf(FILE *stream, const char *format, ...) {
2507 va_list ap;
2508 va_start(ap, format);
2509 const int result = adb_vfprintf(stream, format, ap);
2510 va_end(ap);
2511
2512 return result;
2513}
2514
2515// Version of printf() that takes UTF-8 and can write Unicode to a
2516// Windows console.
2517int adb_printf(const char *format, ...) {
2518 va_list ap;
2519 va_start(ap, format);
2520 const int result = adb_vfprintf(stdout, format, ap);
2521 va_end(ap);
2522
2523 return result;
2524}
2525
2526// Version of fputs() that takes UTF-8 and can write Unicode to a
2527// Windows console.
2528int adb_fputs(const char* buf, FILE* stream) {
2529 // adb_fprintf returns -1 on error, which is conveniently the same as EOF
2530 // which fputs (and hence adb_fputs) should return on error.
Spencer Lowa30b79a2015-11-15 16:29:36 -08002531 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
Spencer Lowcf4ff642015-05-11 01:08:48 -07002532 return adb_fprintf(stream, "%s", buf);
2533}
2534
2535// Version of fputc() that takes UTF-8 and can write Unicode to a
2536// Windows console.
2537int adb_fputc(int ch, FILE* stream) {
2538 const int result = adb_fprintf(stream, "%c", ch);
Spencer Lowa30b79a2015-11-15 16:29:36 -08002539 if (result == -1) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002540 return EOF;
2541 }
2542 // For success, fputc returns the char, cast to unsigned char, then to int.
2543 return static_cast<unsigned char>(ch);
2544}
2545
Spencer Lowa30b79a2015-11-15 16:29:36 -08002546// Version of putchar() that takes UTF-8 and can write Unicode to a Windows console.
2547int adb_putchar(int ch) {
2548 return adb_fputc(ch, stdout);
2549}
2550
2551// Version of puts() that takes UTF-8 and can write Unicode to a Windows console.
2552int adb_puts(const char* buf) {
2553 // adb_printf returns -1 on error, which is conveniently the same as EOF
2554 // which puts (and hence adb_puts) should return on error.
2555 static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed");
2556 return adb_printf("%s\n", buf);
2557}
2558
Spencer Lowcf4ff642015-05-11 01:08:48 -07002559// Internal function to write UTF-8 to a Win32 console. Returns the number of
2560// items (of length size) written. On error, returns a short item count or 0.
2561static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb,
2562 FILE* stream, HANDLE console) {
Spencer Lowa30b79a2015-11-15 16:29:36 -08002563 const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream,
2564 console);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002565 if (result == -1) {
2566 return 0;
2567 }
2568 return result / size;
2569}
2570
2571// Version of fwrite() that takes UTF-8 and can write Unicode to a
2572// Windows console.
2573size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) {
2574 const HANDLE console = _get_console_handle(stream);
2575
2576 // If there is an associated Win32 console, write to it specially,
2577 // otherwise defer to the regular C Runtime, passing it UTF-8.
Yi Kongaed415c2018-07-13 18:15:16 -07002578 if (console != nullptr) {
Spencer Lowcf4ff642015-05-11 01:08:48 -07002579 return _console_fwrite(ptr, size, nmemb, stream, console);
2580 } else {
2581 // If fwrite is a macro, undefine it, so we can call the real
2582 // C Runtime API.
2583#pragma push_macro("fwrite")
2584#undef fwrite
2585 return fwrite(ptr, size, nmemb, stream);
2586#pragma pop_macro("fwrite")
2587 }
2588}
2589
2590// Version of fopen() that takes a UTF-8 filename and can access a file with
2591// a Unicode filename.
Spencer Lowd21dc822015-11-12 15:20:15 -08002592FILE* adb_fopen(const char* path, const char* mode) {
2593 std::wstring path_wide;
2594 if (!android::base::UTF8ToWide(path, &path_wide)) {
2595 return nullptr;
2596 }
2597
2598 std::wstring mode_wide;
2599 if (!android::base::UTF8ToWide(mode, &mode_wide)) {
2600 return nullptr;
2601 }
2602
2603 return _wfopen(path_wide.c_str(), mode_wide.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002604}
2605
Spencer Lowe6ae5732015-09-08 17:13:04 -07002606// Return a lowercase version of the argument. Uses C Runtime tolower() on
2607// each byte which is not UTF-8 aware, and theoretically uses the current C
2608// Runtime locale (which in practice is not changed, so this becomes a ASCII
2609// conversion).
2610static std::string ToLower(const std::string& anycase) {
2611 // copy string
2612 std::string str(anycase);
2613 // transform the copy
2614 std::transform(str.begin(), str.end(), str.begin(), tolower);
2615 return str;
2616}
2617
2618extern "C" int main(int argc, char** argv);
2619
2620// Link with -municode to cause this wmain() to be used as the program
2621// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
2622// regular main() with UTF-8 args.
2623extern "C" int wmain(int argc, wchar_t **argv) {
2624 // Convert args from UTF-16 to UTF-8 and pass that to main().
2625 NarrowArgs narrow_args(argc, argv);
2626 return main(argc, narrow_args.data());
2627}
2628
Spencer Lowcf4ff642015-05-11 01:08:48 -07002629// Shadow UTF-8 environment variable name/value pairs that are created from
2630// _wenviron the first time that adb_getenv() is called. Note that this is not
Spencer Lowe347c1d2015-08-02 18:13:54 -07002631// currently updated if putenv, setenv, unsetenv are called. Note that no
2632// thread synchronization is done, but we're called early enough in
2633// single-threaded startup that things work ok.
Josh Gaob7b1edf2015-11-11 17:56:12 -08002634static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>();
Spencer Lowcf4ff642015-05-11 01:08:48 -07002635
2636// Make sure that shadow UTF-8 environment variables are setup.
2637static void _ensure_env_setup() {
2638 // If some name/value pairs exist, then we've already done the setup below.
2639 if (g_environ_utf8.size() != 0) {
2640 return;
2641 }
2642
Spencer Lowe6ae5732015-09-08 17:13:04 -07002643 if (_wenviron == nullptr) {
2644 // If _wenviron is null, then -municode probably wasn't used. That
2645 // linker flag will cause the entry point to setup _wenviron. It will
2646 // also require an implementation of wmain() (which we provide above).
2647 fatal("_wenviron is not set, did you link with -municode?");
2648 }
2649
Spencer Lowcf4ff642015-05-11 01:08:48 -07002650 // Read name/value pairs from UTF-16 _wenviron and write new name/value
2651 // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
2652 // to use the D() macro here because that tracing only works if the
2653 // ADB_TRACE environment variable is setup, but that env var can't be read
2654 // until this code completes.
2655 for (wchar_t** env = _wenviron; *env != nullptr; ++env) {
2656 wchar_t* const equal = wcschr(*env, L'=');
2657 if (equal == nullptr) {
2658 // Malformed environment variable with no equal sign. Shouldn't
2659 // really happen, but we should be resilient to this.
2660 continue;
2661 }
2662
Spencer Lowd21dc822015-11-12 15:20:15 -08002663 // If we encounter an error converting UTF-16, don't error-out on account of a single env
2664 // var because the program might never even read this particular variable.
2665 std::string name_utf8;
2666 if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) {
2667 continue;
2668 }
2669
Spencer Lowe6ae5732015-09-08 17:13:04 -07002670 // Store lowercase name so that we can do case-insensitive searches.
Spencer Lowd21dc822015-11-12 15:20:15 -08002671 name_utf8 = ToLower(name_utf8);
2672
2673 std::string value_utf8;
2674 if (!android::base::WideToUTF8(equal + 1, &value_utf8)) {
2675 continue;
2676 }
2677
2678 char* const value_dup = strdup(value_utf8.c_str());
Spencer Lowcf4ff642015-05-11 01:08:48 -07002679
Spencer Lowe6ae5732015-09-08 17:13:04 -07002680 // Don't overwrite a previus env var with the same name. In reality,
2681 // the system probably won't let two env vars with the same name exist
2682 // in _wenviron.
Spencer Lowd21dc822015-11-12 15:20:15 -08002683 g_environ_utf8.insert({name_utf8, value_dup});
Spencer Lowcf4ff642015-05-11 01:08:48 -07002684 }
2685}
2686
2687// Version of getenv() that takes a UTF-8 environment variable name and
Spencer Lowe6ae5732015-09-08 17:13:04 -07002688// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
Spencer Lowcf4ff642015-05-11 01:08:48 -07002689char* adb_getenv(const char* name) {
2690 _ensure_env_setup();
2691
Spencer Lowe6ae5732015-09-08 17:13:04 -07002692 // Case-insensitive search by searching for lowercase name in a map of
2693 // lowercase names.
2694 const auto it = g_environ_utf8.find(ToLower(std::string(name)));
Spencer Lowcf4ff642015-05-11 01:08:48 -07002695 if (it == g_environ_utf8.end()) {
2696 return nullptr;
2697 }
2698
2699 return it->second;
2700}
2701
2702// Version of getcwd() that returns the current working directory in UTF-8.
2703char* adb_getcwd(char* buf, int size) {
2704 wchar_t* wbuf = _wgetcwd(nullptr, 0);
2705 if (wbuf == nullptr) {
2706 return nullptr;
2707 }
2708
Spencer Lowd21dc822015-11-12 15:20:15 -08002709 std::string buf_utf8;
2710 const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8);
Spencer Lowcf4ff642015-05-11 01:08:48 -07002711 free(wbuf);
2712 wbuf = nullptr;
2713
Spencer Lowd21dc822015-11-12 15:20:15 -08002714 if (!narrow_result) {
2715 return nullptr;
2716 }
2717
Spencer Lowcf4ff642015-05-11 01:08:48 -07002718 // If size was specified, make sure all the chars will fit.
2719 if (size != 0) {
2720 if (size < static_cast<int>(buf_utf8.length() + 1)) {
2721 errno = ERANGE;
2722 return nullptr;
2723 }
2724 }
2725
2726 // If buf was not specified, allocate storage.
2727 if (buf == nullptr) {
2728 if (size == 0) {
2729 size = buf_utf8.length() + 1;
2730 }
2731 buf = reinterpret_cast<char*>(malloc(size));
2732 if (buf == nullptr) {
2733 return nullptr;
2734 }
2735 }
2736
2737 // Destination buffer was allocated with enough space, or we've already
2738 // checked an existing buffer size for enough space.
2739 strcpy(buf, buf_utf8.c_str());
2740
2741 return buf;
2742}
Spencer Low50beee32018-09-03 16:03:22 -07002743
2744// The SetThreadDescription API was brought in version 1607 of Windows 10.
2745typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription);
2746
2747// Based on PlatformThread::SetName() from
2748// https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc
2749int adb_thread_setname(const std::string& name) {
2750 // The SetThreadDescription API works even if no debugger is attached.
2751 auto set_thread_description_func = reinterpret_cast<SetThreadDescription>(
2752 ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription"));
2753 if (set_thread_description_func) {
2754 std::wstring name_wide;
2755 if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) {
2756 return errno;
2757 }
2758 set_thread_description_func(::GetCurrentThread(), name_wide.c_str());
2759 }
2760
2761 // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions.
2762 // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017
2763
2764 return 0;
2765}