Dan Albert | db6fe64 | 2015-03-19 15:21:08 -0700 | [diff] [blame] | 1 | /* |
| 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 Cui | 19bec5b | 2015-09-22 15:52:57 -0700 | [diff] [blame] | 17 | #define TRACE_TAG SYSDEPS |
Dan Albert | db6fe64 | 2015-03-19 15:21:08 -0700 | [diff] [blame] | 18 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 19 | #include "sysdeps.h" |
Dan Albert | db6fe64 | 2015-03-19 15:21:08 -0700 | [diff] [blame] | 20 | |
| 21 | #include <winsock2.h> /* winsock.h *must* be included before windows.h. */ |
Stephen Hines | b117085 | 2014-10-01 17:37:06 -0700 | [diff] [blame] | 22 | #include <windows.h> |
Dan Albert | db6fe64 | 2015-03-19 15:21:08 -0700 | [diff] [blame] | 23 | |
| 24 | #include <errno.h> |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 25 | #include <stdio.h> |
Christopher Ferris | 054d170 | 2014-11-06 14:34:24 -0800 | [diff] [blame] | 26 | #include <stdlib.h> |
Dan Albert | db6fe64 | 2015-03-19 15:21:08 -0700 | [diff] [blame] | 27 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 28 | #include <algorithm> |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 29 | #include <memory> |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 30 | #include <mutex> |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 31 | #include <string> |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 32 | #include <unordered_map> |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 33 | #include <vector> |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 34 | |
Elliott Hughes | fe44751 | 2015-07-24 11:35:40 -0700 | [diff] [blame] | 35 | #include <cutils/sockets.h> |
| 36 | |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 37 | #include <android-base/errors.h> |
Elliott Hughes | f55ead9 | 2015-12-04 22:00:26 -0800 | [diff] [blame] | 38 | #include <android-base/logging.h> |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 39 | #include <android-base/macros.h> |
Elliott Hughes | f55ead9 | 2015-12-04 22:00:26 -0800 | [diff] [blame] | 40 | #include <android-base/stringprintf.h> |
| 41 | #include <android-base/strings.h> |
| 42 | #include <android-base/utf8.h> |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 43 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 44 | #include "adb.h" |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 45 | #include "adb_utils.h" |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 46 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 47 | #include "sysdeps/uio.h" |
| 48 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 49 | extern void fatal(const char *fmt, ...); |
| 50 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 51 | /* forward declarations */ |
| 52 | |
| 53 | typedef const struct FHClassRec_* FHClass; |
| 54 | typedef struct FHRec_* FH; |
| 55 | typedef struct EventHookRec_* EventHook; |
| 56 | |
| 57 | typedef struct FHClassRec_ { |
| 58 | void (*_fh_init)(FH); |
| 59 | int (*_fh_close)(FH); |
| 60 | int (*_fh_lseek)(FH, int, int); |
| 61 | int (*_fh_read)(FH, void*, int); |
| 62 | int (*_fh_write)(FH, const void*, int); |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 63 | int (*_fh_writev)(FH, const adb_iovec*, int); |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 64 | } FHClassRec; |
| 65 | |
| 66 | static void _fh_file_init(FH); |
| 67 | static int _fh_file_close(FH); |
| 68 | static int _fh_file_lseek(FH, int, int); |
| 69 | static int _fh_file_read(FH, void*, int); |
| 70 | static int _fh_file_write(FH, const void*, int); |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 71 | static int _fh_file_writev(FH, const adb_iovec*, int); |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 72 | |
| 73 | static const FHClassRec _fh_file_class = { |
| 74 | _fh_file_init, |
| 75 | _fh_file_close, |
| 76 | _fh_file_lseek, |
| 77 | _fh_file_read, |
| 78 | _fh_file_write, |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 79 | _fh_file_writev, |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 80 | }; |
| 81 | |
| 82 | static void _fh_socket_init(FH); |
| 83 | static int _fh_socket_close(FH); |
| 84 | static int _fh_socket_lseek(FH, int, int); |
| 85 | static int _fh_socket_read(FH, void*, int); |
| 86 | static int _fh_socket_write(FH, const void*, int); |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 87 | static int _fh_socket_writev(FH, const adb_iovec*, int); |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 88 | |
| 89 | static const FHClassRec _fh_socket_class = { |
| 90 | _fh_socket_init, |
| 91 | _fh_socket_close, |
| 92 | _fh_socket_lseek, |
| 93 | _fh_socket_read, |
| 94 | _fh_socket_write, |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 95 | _fh_socket_writev, |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 96 | }; |
| 97 | |
Pirama Arumuga Nainar | 5231aff | 2018-08-08 10:33:24 -0700 | [diff] [blame^] | 98 | #if defined(assert) |
| 99 | #undef assert |
| 100 | #endif |
| 101 | |
Josh Gao | 2930cdc | 2016-01-15 15:17:37 -0800 | [diff] [blame] | 102 | #define assert(cond) \ |
| 103 | do { \ |
| 104 | if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \ |
| 105 | } while (0) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 106 | |
Spencer Low | 2bbb3a9 | 2015-08-26 18:46:09 -0700 | [diff] [blame] | 107 | void handle_deleter::operator()(HANDLE h) { |
| 108 | // CreateFile() is documented to return INVALID_HANDLE_FILE on error, |
| 109 | // implying that NULL is a valid handle, but this is probably impossible. |
| 110 | // Other APIs like CreateEvent() are documented to return NULL on error, |
| 111 | // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also |
| 112 | // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE |
| 113 | // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we |
| 114 | // only need to check for INVALID_HANDLE_VALUE. |
| 115 | if (h != INVALID_HANDLE_VALUE) { |
| 116 | if (!CloseHandle(h)) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 117 | D("CloseHandle(%p) failed: %s", h, |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 118 | android::base::SystemErrorCodeToString(GetLastError()).c_str()); |
Spencer Low | 2bbb3a9 | 2015-08-26 18:46:09 -0700 | [diff] [blame] | 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 123 | /**************************************************************************/ |
| 124 | /**************************************************************************/ |
| 125 | /***** *****/ |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 126 | /***** common file descriptor handling *****/ |
| 127 | /***** *****/ |
| 128 | /**************************************************************************/ |
| 129 | /**************************************************************************/ |
| 130 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 131 | typedef struct FHRec_ |
| 132 | { |
| 133 | FHClass clazz; |
| 134 | int used; |
| 135 | int eof; |
| 136 | union { |
| 137 | HANDLE handle; |
| 138 | SOCKET socket; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 139 | } u; |
| 140 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 141 | char name[32]; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 142 | } FHRec; |
| 143 | |
| 144 | #define fh_handle u.handle |
| 145 | #define fh_socket u.socket |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 146 | |
Josh Gao | 4f657a7 | 2016-02-17 16:45:39 -0800 | [diff] [blame] | 147 | #define WIN32_FH_BASE 2048 |
Josh Gao | 7c9e5fb | 2016-04-18 11:09:28 -0700 | [diff] [blame] | 148 | #define WIN32_MAX_FHS 2048 |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 149 | |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 150 | static std::mutex& _win32_lock = *new std::mutex(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 151 | static FHRec _win32_fhs[ WIN32_MAX_FHS ]; |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 152 | static int _win32_fh_next; // where to start search for free FHRec |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 153 | |
| 154 | static FH |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 155 | _fh_from_int( int fd, const char* func ) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 156 | { |
| 157 | FH f; |
| 158 | |
| 159 | fd -= WIN32_FH_BASE; |
| 160 | |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 161 | if (fd < 0 || fd >= WIN32_MAX_FHS) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 162 | D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 163 | func ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 164 | errno = EBADF; |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 165 | return nullptr; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 166 | } |
| 167 | |
| 168 | f = &_win32_fhs[fd]; |
| 169 | |
| 170 | if (f->used == 0) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 171 | D( "_fh_from_int: invalid fd %d passed to %s", fd + WIN32_FH_BASE, |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 172 | func ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 173 | errno = EBADF; |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 174 | return nullptr; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 175 | } |
| 176 | |
| 177 | return f; |
| 178 | } |
| 179 | |
| 180 | |
| 181 | static int |
| 182 | _fh_to_int( FH f ) |
| 183 | { |
| 184 | if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS) |
| 185 | return (int)(f - _win32_fhs) + WIN32_FH_BASE; |
| 186 | |
| 187 | return -1; |
| 188 | } |
| 189 | |
| 190 | static FH |
| 191 | _fh_alloc( FHClass clazz ) |
| 192 | { |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 193 | FH f = nullptr; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 194 | |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 195 | std::lock_guard<std::mutex> lock(_win32_lock); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 196 | |
Josh Gao | 4f657a7 | 2016-02-17 16:45:39 -0800 | [diff] [blame] | 197 | for (int i = _win32_fh_next; i < WIN32_MAX_FHS; ++i) { |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 198 | if (_win32_fhs[i].clazz == nullptr) { |
Josh Gao | 4f657a7 | 2016-02-17 16:45:39 -0800 | [diff] [blame] | 199 | f = &_win32_fhs[i]; |
| 200 | _win32_fh_next = i + 1; |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 201 | f->clazz = clazz; |
| 202 | f->used = 1; |
| 203 | f->eof = 0; |
| 204 | f->name[0] = '\0'; |
| 205 | clazz->_fh_init(f); |
| 206 | return f; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 207 | } |
| 208 | } |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 209 | |
| 210 | D("_fh_alloc: no more free file descriptors"); |
| 211 | errno = EMFILE; // Too many open files |
| 212 | return nullptr; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 213 | } |
| 214 | |
| 215 | |
| 216 | static int |
| 217 | _fh_close( FH f ) |
| 218 | { |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 219 | // Use lock so that closing only happens once and so that _fh_alloc can't |
| 220 | // allocate a FH that we're in the middle of closing. |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 221 | std::lock_guard<std::mutex> lock(_win32_lock); |
Josh Gao | 4f657a7 | 2016-02-17 16:45:39 -0800 | [diff] [blame] | 222 | |
| 223 | int offset = f - _win32_fhs; |
| 224 | if (_win32_fh_next > offset) { |
| 225 | _win32_fh_next = offset; |
| 226 | } |
| 227 | |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 228 | if (f->used) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 229 | f->clazz->_fh_close( f ); |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 230 | f->name[0] = '\0'; |
| 231 | f->eof = 0; |
| 232 | f->used = 0; |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 233 | f->clazz = nullptr; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 234 | } |
| 235 | return 0; |
| 236 | } |
| 237 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 238 | // Deleter for unique_fh. |
| 239 | class fh_deleter { |
| 240 | public: |
| 241 | void operator()(struct FHRec_* fh) { |
| 242 | // We're called from a destructor and destructors should not overwrite |
| 243 | // errno because callers may do: |
| 244 | // errno = EBLAH; |
| 245 | // return -1; // calls destructor, which should not overwrite errno |
| 246 | const int saved_errno = errno; |
| 247 | _fh_close(fh); |
| 248 | errno = saved_errno; |
| 249 | } |
| 250 | }; |
| 251 | |
| 252 | // Like std::unique_ptr, but calls _fh_close() instead of operator delete(). |
| 253 | typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh; |
| 254 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 255 | /**************************************************************************/ |
| 256 | /**************************************************************************/ |
| 257 | /***** *****/ |
| 258 | /***** file-based descriptor handling *****/ |
| 259 | /***** *****/ |
| 260 | /**************************************************************************/ |
| 261 | /**************************************************************************/ |
| 262 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 263 | static void _fh_file_init(FH f) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 264 | f->fh_handle = INVALID_HANDLE_VALUE; |
| 265 | } |
| 266 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 267 | static int _fh_file_close(FH f) { |
| 268 | CloseHandle(f->fh_handle); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 269 | f->fh_handle = INVALID_HANDLE_VALUE; |
| 270 | return 0; |
| 271 | } |
| 272 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 273 | static int _fh_file_read(FH f, void* buf, int len) { |
| 274 | DWORD read_bytes; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 275 | |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 276 | if (!ReadFile(f->fh_handle, buf, (DWORD)len, &read_bytes, nullptr)) { |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 277 | D("adb_read: could not read %d bytes from %s", len, f->name); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 278 | errno = EIO; |
| 279 | return -1; |
| 280 | } else if (read_bytes < (DWORD)len) { |
| 281 | f->eof = 1; |
| 282 | } |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 283 | return read_bytes; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 284 | } |
| 285 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 286 | static int _fh_file_write(FH f, const void* buf, int len) { |
| 287 | DWORD wrote_bytes; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 288 | |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 289 | if (!WriteFile(f->fh_handle, buf, (DWORD)len, &wrote_bytes, nullptr)) { |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 290 | D("adb_file_write: could not write %d bytes from %s", len, f->name); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 291 | errno = EIO; |
| 292 | return -1; |
| 293 | } else if (wrote_bytes < (DWORD)len) { |
| 294 | f->eof = 1; |
| 295 | } |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 296 | return wrote_bytes; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 297 | } |
| 298 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 299 | static int _fh_file_writev(FH f, const adb_iovec* iov, int iovcnt) { |
| 300 | if (iovcnt <= 0) { |
| 301 | errno = EINVAL; |
| 302 | return -1; |
| 303 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 304 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 305 | DWORD wrote_bytes = 0; |
| 306 | |
| 307 | for (int i = 0; i < iovcnt; ++i) { |
| 308 | ssize_t rc = _fh_file_write(f, iov[i].iov_base, iov[i].iov_len); |
| 309 | if (rc == -1) { |
| 310 | return wrote_bytes > 0 ? wrote_bytes : -1; |
| 311 | } else if (rc == 0) { |
| 312 | return wrote_bytes; |
| 313 | } |
| 314 | |
| 315 | wrote_bytes += rc; |
| 316 | |
| 317 | if (static_cast<size_t>(rc) < iov[i].iov_len) { |
| 318 | return wrote_bytes; |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | return wrote_bytes; |
| 323 | } |
| 324 | |
| 325 | static int _fh_file_lseek(FH f, int pos, int origin) { |
| 326 | DWORD method; |
| 327 | DWORD result; |
| 328 | |
| 329 | switch (origin) { |
| 330 | case SEEK_SET: |
| 331 | method = FILE_BEGIN; |
| 332 | break; |
| 333 | case SEEK_CUR: |
| 334 | method = FILE_CURRENT; |
| 335 | break; |
| 336 | case SEEK_END: |
| 337 | method = FILE_END; |
| 338 | break; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 339 | default: |
| 340 | errno = EINVAL; |
| 341 | return -1; |
| 342 | } |
| 343 | |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 344 | result = SetFilePointer(f->fh_handle, pos, nullptr, method); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 345 | if (result == INVALID_SET_FILE_POINTER) { |
| 346 | errno = EIO; |
| 347 | return -1; |
| 348 | } else { |
| 349 | f->eof = 0; |
| 350 | } |
| 351 | return (int)result; |
| 352 | } |
| 353 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 354 | /**************************************************************************/ |
| 355 | /**************************************************************************/ |
| 356 | /***** *****/ |
| 357 | /***** file-based descriptor handling *****/ |
| 358 | /***** *****/ |
| 359 | /**************************************************************************/ |
| 360 | /**************************************************************************/ |
| 361 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 362 | int adb_open(const char* path, int options) { |
| 363 | FH f; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 364 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 365 | DWORD desiredAccess = 0; |
| 366 | DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 367 | |
| 368 | switch (options) { |
| 369 | case O_RDONLY: |
| 370 | desiredAccess = GENERIC_READ; |
| 371 | break; |
| 372 | case O_WRONLY: |
| 373 | desiredAccess = GENERIC_WRITE; |
| 374 | break; |
| 375 | case O_RDWR: |
| 376 | desiredAccess = GENERIC_READ | GENERIC_WRITE; |
| 377 | break; |
| 378 | default: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 379 | D("adb_open: invalid options (0x%0x)", options); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 380 | errno = EINVAL; |
| 381 | return -1; |
| 382 | } |
| 383 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 384 | f = _fh_alloc(&_fh_file_class); |
| 385 | if (!f) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 386 | return -1; |
| 387 | } |
| 388 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 389 | std::wstring path_wide; |
| 390 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 391 | return -1; |
| 392 | } |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 393 | f->fh_handle = |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 394 | CreateFileW(path_wide.c_str(), desiredAccess, shareMode, nullptr, OPEN_EXISTING, 0, nullptr); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 395 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 396 | if (f->fh_handle == INVALID_HANDLE_VALUE) { |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 397 | const DWORD err = GetLastError(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 398 | _fh_close(f); |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 399 | D("adb_open: could not open '%s': ", path); |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 400 | switch (err) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 401 | case ERROR_FILE_NOT_FOUND: |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 402 | D("file not found"); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 403 | errno = ENOENT; |
| 404 | return -1; |
| 405 | |
| 406 | case ERROR_PATH_NOT_FOUND: |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 407 | D("path not found"); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 408 | errno = ENOTDIR; |
| 409 | return -1; |
| 410 | |
| 411 | default: |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 412 | D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 413 | errno = ENOENT; |
| 414 | return -1; |
| 415 | } |
| 416 | } |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 417 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 418 | snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path); |
| 419 | D("adb_open: '%s' => fd %d", path, _fh_to_int(f)); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 420 | return _fh_to_int(f); |
| 421 | } |
| 422 | |
| 423 | /* ignore mode on Win32 */ |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 424 | int adb_creat(const char* path, int mode) { |
| 425 | FH f; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 426 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 427 | f = _fh_alloc(&_fh_file_class); |
| 428 | if (!f) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 429 | return -1; |
| 430 | } |
| 431 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 432 | std::wstring path_wide; |
| 433 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 434 | return -1; |
| 435 | } |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 436 | f->fh_handle = CreateFileW(path_wide.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 437 | nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 438 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 439 | if (f->fh_handle == INVALID_HANDLE_VALUE) { |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 440 | const DWORD err = GetLastError(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 441 | _fh_close(f); |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 442 | D("adb_creat: could not open '%s': ", path); |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 443 | switch (err) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 444 | case ERROR_FILE_NOT_FOUND: |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 445 | D("file not found"); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 446 | errno = ENOENT; |
| 447 | return -1; |
| 448 | |
| 449 | case ERROR_PATH_NOT_FOUND: |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 450 | D("path not found"); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 451 | errno = ENOTDIR; |
| 452 | return -1; |
| 453 | |
| 454 | default: |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 455 | D("unknown error: %s", android::base::SystemErrorCodeToString(err).c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 456 | errno = ENOENT; |
| 457 | return -1; |
| 458 | } |
| 459 | } |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 460 | snprintf(f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path); |
| 461 | D("adb_creat: '%s' => fd %d", path, _fh_to_int(f)); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 462 | return _fh_to_int(f); |
| 463 | } |
| 464 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 465 | int adb_read(int fd, void* buf, int len) { |
| 466 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 467 | |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 468 | if (f == nullptr) { |
Josh Gao | de16596 | 2018-04-05 18:09:39 -0700 | [diff] [blame] | 469 | errno = EBADF; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 470 | return -1; |
| 471 | } |
| 472 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 473 | return f->clazz->_fh_read(f, buf, len); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 474 | } |
| 475 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 476 | int adb_write(int fd, const void* buf, int len) { |
| 477 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 478 | |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 479 | if (f == nullptr) { |
Josh Gao | de16596 | 2018-04-05 18:09:39 -0700 | [diff] [blame] | 480 | errno = EBADF; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 481 | return -1; |
| 482 | } |
| 483 | |
| 484 | return f->clazz->_fh_write(f, buf, len); |
| 485 | } |
| 486 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 487 | ssize_t adb_writev(int fd, const adb_iovec* iov, int iovcnt) { |
| 488 | FH f = _fh_from_int(fd, __func__); |
| 489 | |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 490 | if (f == nullptr) { |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 491 | errno = EBADF; |
| 492 | return -1; |
| 493 | } |
| 494 | |
| 495 | return f->clazz->_fh_writev(f, iov, iovcnt); |
| 496 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 497 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 498 | int adb_lseek(int fd, int pos, int where) { |
| 499 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 500 | |
| 501 | if (!f) { |
Josh Gao | de16596 | 2018-04-05 18:09:39 -0700 | [diff] [blame] | 502 | errno = EBADF; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 503 | return -1; |
| 504 | } |
| 505 | |
| 506 | return f->clazz->_fh_lseek(f, pos, where); |
| 507 | } |
| 508 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 509 | int adb_close(int fd) { |
| 510 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 511 | |
| 512 | if (!f) { |
Josh Gao | de16596 | 2018-04-05 18:09:39 -0700 | [diff] [blame] | 513 | errno = EBADF; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 514 | return -1; |
| 515 | } |
| 516 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 517 | D("adb_close: %s", f->name); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 518 | _fh_close(f); |
| 519 | return 0; |
| 520 | } |
| 521 | |
| 522 | /**************************************************************************/ |
| 523 | /**************************************************************************/ |
| 524 | /***** *****/ |
| 525 | /***** socket-based file descriptors *****/ |
| 526 | /***** *****/ |
| 527 | /**************************************************************************/ |
| 528 | /**************************************************************************/ |
| 529 | |
Spencer Low | 31aafa6 | 2015-01-25 14:40:16 -0800 | [diff] [blame] | 530 | #undef setsockopt |
| 531 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 532 | static void _socket_set_errno( const DWORD err ) { |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 533 | // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a |
| 534 | // lot of POSIX and socket error codes, some of the resulting error codes |
Josh Gao | 75e96bb | 2016-12-05 13:24:48 -0800 | [diff] [blame] | 535 | // are mapped to strings by adb_strerror(). |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 536 | switch ( err ) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 537 | case 0: errno = 0; break; |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 538 | // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use. |
| 539 | // case WSAEINTR: errno = EINTR; break; |
| 540 | case WSAEFAULT: errno = EFAULT; break; |
| 541 | case WSAEINVAL: errno = EINVAL; break; |
| 542 | case WSAEMFILE: errno = EMFILE; break; |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 543 | // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because |
| 544 | // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and |
| 545 | // callers check specifically for EAGAIN. |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 546 | case WSAEWOULDBLOCK: errno = EAGAIN; break; |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 547 | case WSAENOTSOCK: errno = ENOTSOCK; break; |
| 548 | case WSAENOPROTOOPT: errno = ENOPROTOOPT; break; |
| 549 | case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break; |
| 550 | case WSAENETDOWN: errno = ENETDOWN; break; |
| 551 | case WSAENETRESET: errno = ENETRESET; break; |
| 552 | // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems |
| 553 | // to use EPIPE for these situations and there are some callers that look |
| 554 | // for EPIPE. |
| 555 | case WSAECONNABORTED: errno = EPIPE; break; |
| 556 | case WSAECONNRESET: errno = ECONNRESET; break; |
| 557 | case WSAENOBUFS: errno = ENOBUFS; break; |
| 558 | case WSAENOTCONN: errno = ENOTCONN; break; |
| 559 | // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or |
| 560 | // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future |
| 561 | // considerations: Reportedly send() can return zero on timeout, and POSIX |
| 562 | // code may expect EAGAIN instead of ETIMEDOUT on timeout. |
| 563 | // case WSAETIMEDOUT: errno = ETIMEDOUT; break; |
| 564 | case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 565 | default: |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 566 | errno = EINVAL; |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 567 | D( "_socket_set_errno: mapping Windows error code %lu to errno %d", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 568 | err, errno ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 569 | } |
| 570 | } |
| 571 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 572 | extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) { |
| 573 | // WSAPoll doesn't handle invalid/non-socket handles, so we need to handle them ourselves. |
| 574 | int skipped = 0; |
| 575 | std::vector<WSAPOLLFD> sockets; |
| 576 | std::vector<adb_pollfd*> original; |
Josh Gao | be2ee7b | 2018-03-29 12:34:28 -0700 | [diff] [blame] | 577 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 578 | for (size_t i = 0; i < nfds; ++i) { |
| 579 | FH fh = _fh_from_int(fds[i].fd, __func__); |
| 580 | if (!fh || !fh->used || fh->clazz != &_fh_socket_class) { |
| 581 | D("adb_poll received bad FD %d", fds[i].fd); |
| 582 | fds[i].revents = POLLNVAL; |
| 583 | ++skipped; |
| 584 | } else { |
| 585 | WSAPOLLFD wsapollfd = { |
| 586 | .fd = fh->u.socket, |
| 587 | .events = static_cast<short>(fds[i].events) |
| 588 | }; |
| 589 | sockets.push_back(wsapollfd); |
| 590 | original.push_back(&fds[i]); |
| 591 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 592 | } |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 593 | |
| 594 | if (sockets.empty()) { |
| 595 | return skipped; |
| 596 | } |
| 597 | |
Josh Gao | be2ee7b | 2018-03-29 12:34:28 -0700 | [diff] [blame] | 598 | // If we have any invalid FDs in our FD set, make sure to return immediately. |
| 599 | if (skipped > 0) { |
| 600 | timeout = 0; |
| 601 | } |
| 602 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 603 | int result = WSAPoll(sockets.data(), sockets.size(), timeout); |
| 604 | if (result == SOCKET_ERROR) { |
| 605 | _socket_set_errno(WSAGetLastError()); |
| 606 | return -1; |
| 607 | } |
| 608 | |
| 609 | // Map the results back onto the original set. |
| 610 | for (size_t i = 0; i < sockets.size(); ++i) { |
| 611 | original[i]->revents = sockets[i].revents; |
| 612 | } |
| 613 | |
Josh Gao | be2ee7b | 2018-03-29 12:34:28 -0700 | [diff] [blame] | 614 | // WSAPoll appears to return the number of unique FDs with available events, instead of how many |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 615 | // of the pollfd elements have a non-zero revents field, which is what it and poll are specified |
| 616 | // to do. Ignore its result and calculate the proper return value. |
| 617 | result = 0; |
| 618 | for (size_t i = 0; i < nfds; ++i) { |
| 619 | if (fds[i].revents != 0) { |
| 620 | ++result; |
| 621 | } |
| 622 | } |
| 623 | return result; |
| 624 | } |
| 625 | |
| 626 | static void _fh_socket_init(FH f) { |
| 627 | f->fh_socket = INVALID_SOCKET; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 628 | } |
| 629 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 630 | static int _fh_socket_close(FH f) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 631 | if (f->fh_socket != INVALID_SOCKET) { |
| 632 | /* gently tell any peer that we're closing the socket */ |
| 633 | if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) { |
| 634 | // If the socket is not connected, this returns an error. We want to |
| 635 | // minimize logging spam, so don't log these errors for now. |
| 636 | #if 0 |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 637 | D("socket shutdown failed: %s", |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 638 | android::base::SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 639 | #endif |
| 640 | } |
| 641 | if (closesocket(f->fh_socket) == SOCKET_ERROR) { |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 642 | // Don't set errno here, since adb_close will ignore it. |
| 643 | const DWORD err = WSAGetLastError(); |
| 644 | D("closesocket failed: %s", android::base::SystemErrorCodeToString(err).c_str()); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 645 | } |
| 646 | f->fh_socket = INVALID_SOCKET; |
| 647 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 648 | return 0; |
| 649 | } |
| 650 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 651 | static int _fh_socket_lseek(FH f, int pos, int origin) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 652 | errno = EPIPE; |
| 653 | return -1; |
| 654 | } |
| 655 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 656 | static int _fh_socket_read(FH f, void* buf, int len) { |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 657 | int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 658 | if (result == SOCKET_ERROR) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 659 | const DWORD err = WSAGetLastError(); |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 660 | // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace |
| 661 | // that to reduce spam and confusion. |
| 662 | if (err != WSAEWOULDBLOCK) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 663 | D("recv fd %d failed: %s", _fh_to_int(f), |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 664 | android::base::SystemErrorCodeToString(err).c_str()); |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 665 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 666 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 667 | result = -1; |
| 668 | } |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 669 | return result; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 670 | } |
| 671 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 672 | static int _fh_socket_write(FH f, const void* buf, int len) { |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 673 | int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 674 | if (result == SOCKET_ERROR) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 675 | const DWORD err = WSAGetLastError(); |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 676 | // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace |
| 677 | // that to reduce spam and confusion. |
| 678 | if (err != WSAEWOULDBLOCK) { |
| 679 | D("send fd %d failed: %s", _fh_to_int(f), |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 680 | android::base::SystemErrorCodeToString(err).c_str()); |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 681 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 682 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 683 | result = -1; |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 684 | } else { |
| 685 | // According to https://code.google.com/p/chromium/issues/detail?id=27870 |
| 686 | // Winsock Layered Service Providers may cause this. |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 687 | CHECK_LE(result, len) << "Tried to write " << len << " bytes to " << f->name << ", but " |
| 688 | << result << " bytes reportedly written"; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 689 | } |
| 690 | return result; |
| 691 | } |
| 692 | |
Josh Gao | 1bbdd25 | 2018-04-05 17:55:25 -0700 | [diff] [blame] | 693 | // Make sure that adb_iovec is compatible with WSABUF. |
| 694 | static_assert(sizeof(adb_iovec) == sizeof(WSABUF), ""); |
| 695 | static_assert(SIZEOF_MEMBER(adb_iovec, iov_len) == SIZEOF_MEMBER(WSABUF, len), ""); |
| 696 | static_assert(offsetof(adb_iovec, iov_len) == offsetof(WSABUF, len), ""); |
| 697 | |
| 698 | static_assert(SIZEOF_MEMBER(adb_iovec, iov_base) == SIZEOF_MEMBER(WSABUF, buf), ""); |
| 699 | static_assert(offsetof(adb_iovec, iov_base) == offsetof(WSABUF, buf), ""); |
| 700 | |
| 701 | static int _fh_socket_writev(FH f, const adb_iovec* iov, int iovcnt) { |
| 702 | if (iovcnt <= 0) { |
| 703 | errno = EINVAL; |
| 704 | return -1; |
| 705 | } |
| 706 | |
| 707 | WSABUF* wsabuf = reinterpret_cast<WSABUF*>(const_cast<adb_iovec*>(iov)); |
| 708 | DWORD bytes_written = 0; |
| 709 | int result = WSASend(f->fh_socket, wsabuf, iovcnt, &bytes_written, 0, nullptr, nullptr); |
| 710 | if (result == SOCKET_ERROR) { |
| 711 | const DWORD err = WSAGetLastError(); |
| 712 | // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace |
| 713 | // that to reduce spam and confusion. |
| 714 | if (err != WSAEWOULDBLOCK) { |
| 715 | D("send fd %d failed: %s", _fh_to_int(f), |
| 716 | android::base::SystemErrorCodeToString(err).c_str()); |
| 717 | } |
| 718 | _socket_set_errno(err); |
| 719 | result = -1; |
| 720 | } |
| 721 | CHECK_GE(static_cast<DWORD>(std::numeric_limits<int>::max()), bytes_written); |
| 722 | return static_cast<int>(bytes_written); |
| 723 | } |
| 724 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 725 | /**************************************************************************/ |
| 726 | /**************************************************************************/ |
| 727 | /***** *****/ |
| 728 | /***** replacement for libs/cutils/socket_xxxx.c *****/ |
| 729 | /***** *****/ |
| 730 | /**************************************************************************/ |
| 731 | /**************************************************************************/ |
| 732 | |
Josh Gao | caeda2c | 2018-04-05 18:10:03 -0700 | [diff] [blame] | 733 | static int _init_winsock(void) { |
| 734 | static std::once_flag once; |
| 735 | std::call_once(once, []() { |
| 736 | WSADATA wsaData; |
| 737 | int rc = WSAStartup(MAKEWORD(2, 2), &wsaData); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 738 | if (rc != 0) { |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 739 | fatal("adb: could not initialize Winsock: %s", |
| 740 | android::base::SystemErrorCodeToString(rc).c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 741 | } |
Spencer Low | c7c1ca6 | 2015-08-12 18:19:16 -0700 | [diff] [blame] | 742 | |
| 743 | // Note that we do not call atexit() to register WSACleanup to be called |
| 744 | // at normal process termination because: |
| 745 | // 1) When exit() is called, there are still threads actively using |
| 746 | // Winsock because we don't cleanly shutdown all threads, so it |
| 747 | // doesn't make sense to call WSACleanup() and may cause problems |
| 748 | // with those threads. |
| 749 | // 2) A deadlock can occur when exit() holds a C Runtime lock, then it |
| 750 | // calls WSACleanup() which tries to unload a DLL, which tries to |
| 751 | // grab the LoaderLock. This conflicts with the device_poll_thread |
| 752 | // which holds the LoaderLock because AdbWinApi.dll calls |
| 753 | // setupapi.dll which tries to load wintrust.dll which tries to load |
| 754 | // crypt32.dll which calls atexit() which tries to acquire the C |
| 755 | // Runtime lock that the other thread holds. |
Josh Gao | caeda2c | 2018-04-05 18:10:03 -0700 | [diff] [blame] | 756 | }); |
| 757 | return 0; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 758 | } |
| 759 | |
Josh Gao | caeda2c | 2018-04-05 18:10:03 -0700 | [diff] [blame] | 760 | static int _winsock_init = _init_winsock(); |
| 761 | |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 762 | // Map a socket type to an explicit socket protocol instead of using the socket |
| 763 | // protocol of 0. Explicit socket protocols are used by most apps and we should |
| 764 | // do the same to reduce the chance of exercising uncommon code-paths that might |
| 765 | // have problems or that might load different Winsock service providers that |
| 766 | // have problems. |
| 767 | static int GetSocketProtocolFromSocketType(int type) { |
| 768 | switch (type) { |
| 769 | case SOCK_STREAM: |
| 770 | return IPPROTO_TCP; |
| 771 | case SOCK_DGRAM: |
| 772 | return IPPROTO_UDP; |
| 773 | default: |
| 774 | LOG(FATAL) << "Unknown socket type: " << type; |
| 775 | return 0; |
| 776 | } |
| 777 | } |
| 778 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 779 | int network_loopback_client(int port, int type, std::string* error) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 780 | struct sockaddr_in addr; |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 781 | SOCKET s; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 782 | |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 783 | unique_fh f(_fh_alloc(&_fh_socket_class)); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 784 | if (!f) { |
| 785 | *error = strerror(errno); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 786 | return -1; |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 787 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 788 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 789 | memset(&addr, 0, sizeof(addr)); |
| 790 | addr.sin_family = AF_INET; |
| 791 | addr.sin_port = htons(port); |
| 792 | addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); |
| 793 | |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 794 | s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type)); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 795 | if (s == INVALID_SOCKET) { |
| 796 | const DWORD err = WSAGetLastError(); |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 797 | *error = android::base::StringPrintf("cannot create socket: %s", |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 798 | android::base::SystemErrorCodeToString(err).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 799 | D("%s", error->c_str()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 800 | _socket_set_errno(err); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 801 | return -1; |
| 802 | } |
| 803 | f->fh_socket = s; |
| 804 | |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 805 | if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 806 | // Save err just in case inet_ntoa() or ntohs() changes the last error. |
| 807 | const DWORD err = WSAGetLastError(); |
| 808 | *error = android::base::StringPrintf("cannot connect to %s:%u: %s", |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 809 | inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), |
| 810 | android::base::SystemErrorCodeToString(err).c_str()); |
| 811 | D("could not connect to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, |
| 812 | error->c_str()); |
| 813 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 814 | return -1; |
| 815 | } |
| 816 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 817 | const int fd = _fh_to_int(f.get()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 818 | snprintf(f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "", |
| 819 | port); |
| 820 | D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 821 | f.release(); |
| 822 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 823 | } |
| 824 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 825 | // interface_address is INADDR_LOOPBACK or INADDR_ANY. |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 826 | static int _network_server(int port, int type, u_long interface_address, std::string* error) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 827 | struct sockaddr_in addr; |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 828 | SOCKET s; |
| 829 | int n; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 830 | |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 831 | unique_fh f(_fh_alloc(&_fh_socket_class)); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 832 | if (!f) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 833 | *error = strerror(errno); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 834 | return -1; |
| 835 | } |
| 836 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 837 | memset(&addr, 0, sizeof(addr)); |
| 838 | addr.sin_family = AF_INET; |
| 839 | addr.sin_port = htons(port); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 840 | addr.sin_addr.s_addr = htonl(interface_address); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 841 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 842 | // TODO: Consider using dual-stack socket that can simultaneously listen on |
| 843 | // IPv4 and IPv6. |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 844 | s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type)); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 845 | if (s == INVALID_SOCKET) { |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 846 | const DWORD err = WSAGetLastError(); |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 847 | *error = android::base::StringPrintf("cannot create socket: %s", |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 848 | android::base::SystemErrorCodeToString(err).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 849 | D("%s", error->c_str()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 850 | _socket_set_errno(err); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 851 | return -1; |
| 852 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 853 | |
| 854 | f->fh_socket = s; |
| 855 | |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 856 | // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the |
| 857 | // same port, so instead use SO_EXCLUSIVEADDRUSE. |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 858 | n = 1; |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 859 | if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, sizeof(n)) == SOCKET_ERROR) { |
| 860 | const DWORD err = WSAGetLastError(); |
| 861 | *error = android::base::StringPrintf("cannot set socket option SO_EXCLUSIVEADDRUSE: %s", |
| 862 | android::base::SystemErrorCodeToString(err).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 863 | D("%s", error->c_str()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 864 | _socket_set_errno(err); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 865 | return -1; |
| 866 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 867 | |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 868 | if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 869 | // Save err just in case inet_ntoa() or ntohs() changes the last error. |
| 870 | const DWORD err = WSAGetLastError(); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 871 | *error = android::base::StringPrintf("cannot bind to %s:%u: %s", inet_ntoa(addr.sin_addr), |
| 872 | ntohs(addr.sin_port), |
| 873 | android::base::SystemErrorCodeToString(err).c_str()); |
| 874 | D("could not bind to %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str()); |
| 875 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 876 | return -1; |
| 877 | } |
| 878 | if (type == SOCK_STREAM) { |
Josh Gao | a076b15 | 2018-03-20 14:25:03 -0700 | [diff] [blame] | 879 | if (listen(s, SOMAXCONN) == SOCKET_ERROR) { |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 880 | const DWORD err = WSAGetLastError(); |
| 881 | *error = android::base::StringPrintf( |
| 882 | "cannot listen on socket: %s", android::base::SystemErrorCodeToString(err).c_str()); |
| 883 | D("could not listen on %s:%d: %s", type != SOCK_STREAM ? "udp" : "tcp", port, |
| 884 | error->c_str()); |
| 885 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 886 | return -1; |
| 887 | } |
| 888 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 889 | const int fd = _fh_to_int(f.get()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 890 | snprintf(f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd, |
| 891 | interface_address == INADDR_LOOPBACK ? "lo" : "any", type != SOCK_STREAM ? "udp:" : "", |
| 892 | port); |
| 893 | D("port %d type %s => fd %d", port, type != SOCK_STREAM ? "udp" : "tcp", fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 894 | f.release(); |
| 895 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 896 | } |
| 897 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 898 | int network_loopback_server(int port, int type, std::string* error) { |
| 899 | return _network_server(port, type, INADDR_LOOPBACK, error); |
| 900 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 901 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 902 | int network_inaddr_any_server(int port, int type, std::string* error) { |
| 903 | return _network_server(port, type, INADDR_ANY, error); |
| 904 | } |
| 905 | |
| 906 | int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) { |
| 907 | unique_fh f(_fh_alloc(&_fh_socket_class)); |
| 908 | if (!f) { |
| 909 | *error = strerror(errno); |
| 910 | return -1; |
| 911 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 912 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 913 | struct addrinfo hints; |
| 914 | memset(&hints, 0, sizeof(hints)); |
| 915 | hints.ai_family = AF_UNSPEC; |
| 916 | hints.ai_socktype = type; |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 917 | hints.ai_protocol = GetSocketProtocolFromSocketType(type); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 918 | |
| 919 | char port_str[16]; |
| 920 | snprintf(port_str, sizeof(port_str), "%d", port); |
| 921 | |
| 922 | struct addrinfo* addrinfo_ptr = nullptr; |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 923 | |
| 924 | #if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03) |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 925 | // TODO: When the Android SDK tools increases the Windows system |
| 926 | // requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW(). |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 927 | #else |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 928 | // Otherwise, keep using getaddrinfo(), or do runtime API detection |
| 929 | // with GetProcAddress("GetAddrInfoW"). |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 930 | #endif |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 931 | if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) { |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 932 | const DWORD err = WSAGetLastError(); |
| 933 | *error = android::base::StringPrintf("cannot resolve host '%s' and port %s: %s", |
| 934 | host.c_str(), port_str, |
| 935 | android::base::SystemErrorCodeToString(err).c_str()); |
| 936 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 937 | D("%s", error->c_str()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 938 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 939 | return -1; |
| 940 | } |
Elliott Hughes | 8ac4599 | 2016-08-08 12:52:37 -0700 | [diff] [blame] | 941 | std::unique_ptr<struct addrinfo, decltype(&freeaddrinfo)> addrinfo(addrinfo_ptr, freeaddrinfo); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 942 | addrinfo_ptr = nullptr; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 943 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 944 | // TODO: Try all the addresses if there's more than one? This just uses |
| 945 | // the first. Or, could call WSAConnectByName() (Windows Vista and newer) |
| 946 | // which tries all addresses, takes a timeout and more. |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 947 | SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol); |
| 948 | if (s == INVALID_SOCKET) { |
| 949 | const DWORD err = WSAGetLastError(); |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 950 | *error = android::base::StringPrintf("cannot create socket: %s", |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 951 | android::base::SystemErrorCodeToString(err).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 952 | D("%s", error->c_str()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 953 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 954 | return -1; |
| 955 | } |
| 956 | f->fh_socket = s; |
| 957 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 958 | // TODO: Implement timeouts for Windows. Seems like the default in theory |
| 959 | // (according to http://serverfault.com/a/671453) and in practice is 21 sec. |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 960 | if (connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 961 | // TODO: Use WSAAddressToString or inet_ntop on address. |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 962 | const DWORD err = WSAGetLastError(); |
| 963 | *error = android::base::StringPrintf("cannot connect to %s:%s: %s", host.c_str(), port_str, |
| 964 | android::base::SystemErrorCodeToString(err).c_str()); |
| 965 | D("could not connect to %s:%s:%s: %s", type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), |
| 966 | port_str, error->c_str()); |
| 967 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 968 | return -1; |
| 969 | } |
| 970 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 971 | const int fd = _fh_to_int(f.get()); |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 972 | snprintf(f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, type != SOCK_STREAM ? "udp:" : "", |
| 973 | port); |
| 974 | D("host '%s' port %d type %s => fd %d", host.c_str(), port, type != SOCK_STREAM ? "udp" : "tcp", |
| 975 | fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 976 | f.release(); |
| 977 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 978 | } |
| 979 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 980 | int adb_register_socket(SOCKET s) { |
| 981 | FH f = _fh_alloc(&_fh_socket_class); |
Casey Dahlin | 20238f2 | 2016-09-21 14:03:39 -0700 | [diff] [blame] | 982 | f->fh_socket = s; |
| 983 | return _fh_to_int(f); |
| 984 | } |
| 985 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 986 | #undef accept |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 987 | int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t* addrlen) { |
| 988 | FH serverfh = _fh_from_int(serverfd, __func__); |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 989 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 990 | if (!serverfh || serverfh->clazz != &_fh_socket_class) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 991 | D("adb_socket_accept: invalid fd %d", serverfd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 992 | errno = EBADF; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 993 | return -1; |
| 994 | } |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 995 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 996 | unique_fh fh(_fh_alloc(&_fh_socket_class)); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 997 | if (!fh) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 998 | PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket " |
| 999 | "descriptor"; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1000 | return -1; |
| 1001 | } |
| 1002 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1003 | fh->fh_socket = accept(serverfh->fh_socket, addr, addrlen); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1004 | if (fh->fh_socket == INVALID_SOCKET) { |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 1005 | const DWORD err = WSAGetLastError(); |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1006 | LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd |
| 1007 | << " failed: " + android::base::SystemErrorCodeToString(err); |
| 1008 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1009 | return -1; |
| 1010 | } |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 1011 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1012 | const int fd = _fh_to_int(fh.get()); |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1013 | snprintf(fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name); |
| 1014 | D("adb_socket_accept on fd %d returns fd %d", serverfd, fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1015 | fh.release(); |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1016 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1017 | } |
| 1018 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1019 | int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) { |
| 1020 | FH fh = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1021 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1022 | if (!fh || fh->clazz != &_fh_socket_class) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1023 | D("adb_setsockopt: invalid fd %d", fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1024 | errno = EBADF; |
| 1025 | return -1; |
| 1026 | } |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 1027 | |
| 1028 | // TODO: Once we can assume Windows Vista or later, if the caller is trying |
| 1029 | // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has |
| 1030 | // auto-tuning. |
| 1031 | |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1032 | int result = |
| 1033 | setsockopt(fh->fh_socket, level, optname, reinterpret_cast<const char*>(optval), optlen); |
| 1034 | if (result == SOCKET_ERROR) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1035 | const DWORD err = WSAGetLastError(); |
Josh Gao | 08229f6 | 2018-04-05 18:09:02 -0700 | [diff] [blame] | 1036 | D("adb_setsockopt: setsockopt on fd %d level %d optname %d failed: %s\n", fd, level, |
| 1037 | optname, android::base::SystemErrorCodeToString(err).c_str()); |
| 1038 | _socket_set_errno(err); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1039 | result = -1; |
| 1040 | } |
| 1041 | return result; |
| 1042 | } |
| 1043 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1044 | int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen) { |
| 1045 | FH fh = _fh_from_int(fd, __func__); |
| 1046 | |
| 1047 | if (!fh || fh->clazz != &_fh_socket_class) { |
| 1048 | D("adb_getsockname: invalid fd %d", fd); |
| 1049 | errno = EBADF; |
| 1050 | return -1; |
| 1051 | } |
| 1052 | |
Josh Gao | 4f6f442 | 2017-03-30 13:04:35 -0700 | [diff] [blame] | 1053 | int result = getsockname(fh->fh_socket, sockaddr, optlen); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1054 | if (result == SOCKET_ERROR) { |
| 1055 | const DWORD err = WSAGetLastError(); |
| 1056 | D("adb_getsockname: setsockopt on fd %d failed: %s\n", fd, |
| 1057 | android::base::SystemErrorCodeToString(err).c_str()); |
| 1058 | _socket_set_errno(err); |
| 1059 | result = -1; |
| 1060 | } |
| 1061 | return result; |
| 1062 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1063 | |
David Pursell | 19d0c23 | 2016-04-07 11:25:48 -0700 | [diff] [blame] | 1064 | int adb_socket_get_local_port(int fd) { |
| 1065 | sockaddr_storage addr_storage; |
| 1066 | socklen_t addr_len = sizeof(addr_storage); |
| 1067 | |
| 1068 | if (adb_getsockname(fd, reinterpret_cast<sockaddr*>(&addr_storage), &addr_len) < 0) { |
| 1069 | D("adb_socket_get_local_port: adb_getsockname failed: %s", strerror(errno)); |
| 1070 | return -1; |
| 1071 | } |
| 1072 | |
| 1073 | if (!(addr_storage.ss_family == AF_INET || addr_storage.ss_family == AF_INET6)) { |
| 1074 | D("adb_socket_get_local_port: unknown address family received: %d", addr_storage.ss_family); |
| 1075 | errno = ECONNABORTED; |
| 1076 | return -1; |
| 1077 | } |
| 1078 | |
| 1079 | return ntohs(reinterpret_cast<sockaddr_in*>(&addr_storage)->sin_port); |
| 1080 | } |
| 1081 | |
Josh Gao | 96049b9 | 2018-03-23 13:03:28 -0700 | [diff] [blame] | 1082 | int adb_shutdown(int fd, int direction) { |
| 1083 | FH f = _fh_from_int(fd, __func__); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1084 | |
| 1085 | if (!f || f->clazz != &_fh_socket_class) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1086 | D("adb_shutdown: invalid fd %d", fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1087 | errno = EBADF; |
Spencer Low | 31aafa6 | 2015-01-25 14:40:16 -0800 | [diff] [blame] | 1088 | return -1; |
| 1089 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1090 | |
Josh Gao | 96049b9 | 2018-03-23 13:03:28 -0700 | [diff] [blame] | 1091 | D("adb_shutdown: %s", f->name); |
| 1092 | if (shutdown(f->fh_socket, direction) == SOCKET_ERROR) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1093 | const DWORD err = WSAGetLastError(); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1094 | D("socket shutdown fd %d failed: %s", fd, |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 1095 | android::base::SystemErrorCodeToString(err).c_str()); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1096 | _socket_set_errno(err); |
| 1097 | return -1; |
| 1098 | } |
| 1099 | return 0; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1100 | } |
| 1101 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1102 | // Emulate socketpair(2) by binding and connecting to a socket. |
| 1103 | int adb_socketpair(int sv[2]) { |
| 1104 | int server = -1; |
| 1105 | int client = -1; |
| 1106 | int accepted = -1; |
David Pursell | 19d0c23 | 2016-04-07 11:25:48 -0700 | [diff] [blame] | 1107 | int local_port = -1; |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1108 | std::string error; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1109 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1110 | server = network_loopback_server(0, SOCK_STREAM, &error); |
| 1111 | if (server < 0) { |
| 1112 | D("adb_socketpair: failed to create server: %s", error.c_str()); |
| 1113 | goto fail; |
David Pursell | 7616ae1 | 2015-09-11 16:06:59 -0700 | [diff] [blame] | 1114 | } |
| 1115 | |
David Pursell | 19d0c23 | 2016-04-07 11:25:48 -0700 | [diff] [blame] | 1116 | local_port = adb_socket_get_local_port(server); |
| 1117 | if (local_port < 0) { |
| 1118 | D("adb_socketpair: failed to get server port number: %s", error.c_str()); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1119 | goto fail; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1120 | } |
David Pursell | 19d0c23 | 2016-04-07 11:25:48 -0700 | [diff] [blame] | 1121 | D("adb_socketpair: bound on port %d", local_port); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1122 | |
David Pursell | 19d0c23 | 2016-04-07 11:25:48 -0700 | [diff] [blame] | 1123 | client = network_loopback_client(local_port, SOCK_STREAM, &error); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1124 | if (client < 0) { |
| 1125 | D("adb_socketpair: failed to connect client: %s", error.c_str()); |
| 1126 | goto fail; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1127 | } |
| 1128 | |
Josh Gao | 4f6f442 | 2017-03-30 13:04:35 -0700 | [diff] [blame] | 1129 | accepted = adb_socket_accept(server, nullptr, nullptr); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1130 | if (accepted < 0) { |
Josh Gao | 61eda8d | 2016-02-18 13:43:55 -0800 | [diff] [blame] | 1131 | D("adb_socketpair: failed to accept: %s", strerror(errno)); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1132 | goto fail; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1133 | } |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1134 | adb_close(server); |
| 1135 | sv[0] = client; |
| 1136 | sv[1] = accepted; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1137 | return 0; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1138 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1139 | fail: |
| 1140 | if (server >= 0) { |
| 1141 | adb_close(server); |
| 1142 | } |
| 1143 | if (client >= 0) { |
| 1144 | adb_close(client); |
| 1145 | } |
| 1146 | if (accepted >= 0) { |
| 1147 | adb_close(accepted); |
| 1148 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1149 | return -1; |
| 1150 | } |
| 1151 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1152 | bool set_file_block_mode(int fd, bool block) { |
| 1153 | FH fh = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1154 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1155 | if (!fh || !fh->used) { |
| 1156 | errno = EBADF; |
Casey Dahlin | 20238f2 | 2016-09-21 14:03:39 -0700 | [diff] [blame] | 1157 | D("Setting nonblocking on bad file descriptor %d", fd); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1158 | return false; |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1159 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1160 | |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1161 | if (fh->clazz == &_fh_socket_class) { |
| 1162 | u_long x = !block; |
| 1163 | if (ioctlsocket(fh->u.socket, FIONBIO, &x) != 0) { |
Casey Dahlin | 20238f2 | 2016-09-21 14:03:39 -0700 | [diff] [blame] | 1164 | int error = WSAGetLastError(); |
| 1165 | _socket_set_errno(error); |
| 1166 | D("Setting %d nonblocking failed (%d)", fd, error); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1167 | return false; |
| 1168 | } |
| 1169 | return true; |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 1170 | } else { |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1171 | errno = ENOTSOCK; |
Casey Dahlin | 20238f2 | 2016-09-21 14:03:39 -0700 | [diff] [blame] | 1172 | D("Setting nonblocking on non-socket %d", fd); |
Josh Gao | e738812 | 2016-02-16 17:34:53 -0800 | [diff] [blame] | 1173 | return false; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1174 | } |
| 1175 | } |
| 1176 | |
David Pursell | c25a34e | 2016-02-22 14:27:23 -0800 | [diff] [blame] | 1177 | bool set_tcp_keepalive(int fd, int interval_sec) { |
| 1178 | FH fh = _fh_from_int(fd, __func__); |
| 1179 | |
| 1180 | if (!fh || fh->clazz != &_fh_socket_class) { |
| 1181 | D("set_tcp_keepalive(%d) failed: invalid fd", fd); |
| 1182 | errno = EBADF; |
| 1183 | return false; |
| 1184 | } |
| 1185 | |
| 1186 | tcp_keepalive keepalive; |
| 1187 | keepalive.onoff = (interval_sec > 0); |
| 1188 | keepalive.keepalivetime = interval_sec * 1000; |
| 1189 | keepalive.keepaliveinterval = interval_sec * 1000; |
| 1190 | |
| 1191 | DWORD bytes_returned = 0; |
| 1192 | if (WSAIoctl(fh->fh_socket, SIO_KEEPALIVE_VALS, &keepalive, sizeof(keepalive), nullptr, 0, |
| 1193 | &bytes_returned, nullptr, nullptr) != 0) { |
| 1194 | const DWORD err = WSAGetLastError(); |
| 1195 | D("set_tcp_keepalive(%d) failed: %s", fd, |
| 1196 | android::base::SystemErrorCodeToString(err).c_str()); |
| 1197 | _socket_set_errno(err); |
| 1198 | return false; |
| 1199 | } |
| 1200 | |
| 1201 | return true; |
| 1202 | } |
| 1203 | |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1204 | /**************************************************************************/ |
| 1205 | /**************************************************************************/ |
| 1206 | /***** *****/ |
| 1207 | /***** Console Window Terminal Emulation *****/ |
| 1208 | /***** *****/ |
| 1209 | /**************************************************************************/ |
| 1210 | /**************************************************************************/ |
| 1211 | |
| 1212 | // This reads input from a Win32 console window and translates it into Unix |
| 1213 | // terminal-style sequences. This emulates mostly Gnome Terminal (in Normal |
| 1214 | // mode, not Application mode), which itself emulates xterm. Gnome Terminal |
| 1215 | // is emulated instead of xterm because it is probably more popular than xterm: |
| 1216 | // Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal |
| 1217 | // supports modern fonts, etc. It seems best to emulate the terminal that most |
| 1218 | // Android developers use because they'll fix apps (the shell, etc.) to keep |
| 1219 | // working with that terminal's emulation. |
| 1220 | // |
| 1221 | // The point of this emulation is not to be perfect or to solve all issues with |
| 1222 | // console windows on Windows, but to be better than the original code which |
| 1223 | // just called read() (which called ReadFile(), which called ReadConsoleA()) |
| 1224 | // which did not support Ctrl-C, tab completion, shell input line editing |
| 1225 | // keys, server echo, and more. |
| 1226 | // |
| 1227 | // This implementation reconfigures the console with SetConsoleMode(), then |
| 1228 | // calls ReadConsoleInput() to get raw input which it remaps to Unix |
| 1229 | // terminal-style sequences which is returned via unix_read() which is used |
| 1230 | // by the 'adb shell' command. |
| 1231 | // |
| 1232 | // Code organization: |
| 1233 | // |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 1234 | // * _get_console_handle() and unix_isatty() provide console information. |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1235 | // * stdin_raw_init() and stdin_raw_restore() reconfigure the console. |
| 1236 | // * unix_read() detects console windows (as opposed to pipes, files, etc.). |
| 1237 | // * _console_read() is the main code of the emulation. |
| 1238 | |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 1239 | // Returns a console HANDLE if |fd| is a console, otherwise returns nullptr. |
| 1240 | // If a valid HANDLE is returned and |mode| is not null, |mode| is also filled |
| 1241 | // with the console mode. Requires GENERIC_READ access to the underlying HANDLE. |
| 1242 | static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) { |
| 1243 | // First check isatty(); this is very fast and eliminates most non-console |
| 1244 | // FDs, but returns 1 for both consoles and character devices like NUL. |
| 1245 | #pragma push_macro("isatty") |
| 1246 | #undef isatty |
| 1247 | if (!isatty(fd)) { |
| 1248 | return nullptr; |
| 1249 | } |
| 1250 | #pragma pop_macro("isatty") |
| 1251 | |
| 1252 | // To differentiate between character devices and consoles we need to get |
| 1253 | // the underlying HANDLE and use GetConsoleMode(), which is what requires |
| 1254 | // GENERIC_READ permissions. |
| 1255 | const intptr_t intptr_handle = _get_osfhandle(fd); |
| 1256 | if (intptr_handle == -1) { |
| 1257 | return nullptr; |
| 1258 | } |
| 1259 | const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle); |
| 1260 | DWORD temp_mode = 0; |
| 1261 | if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) { |
| 1262 | return nullptr; |
| 1263 | } |
| 1264 | |
| 1265 | return handle; |
| 1266 | } |
| 1267 | |
| 1268 | // Returns a console handle if |stream| is a console, otherwise returns nullptr. |
| 1269 | static HANDLE _get_console_handle(FILE* const stream) { |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 1270 | // Save and restore errno to make it easier for callers to prevent from overwriting errno. |
| 1271 | android::base::ErrnoRestorer er; |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 1272 | const int fd = fileno(stream); |
| 1273 | if (fd < 0) { |
| 1274 | return nullptr; |
| 1275 | } |
| 1276 | return _get_console_handle(fd); |
| 1277 | } |
| 1278 | |
| 1279 | int unix_isatty(int fd) { |
| 1280 | return _get_console_handle(fd) ? 1 : 0; |
| 1281 | } |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1282 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1283 | // Get the next KEY_EVENT_RECORD that should be processed. |
| 1284 | static bool _get_key_event_record(const HANDLE console, INPUT_RECORD* const input_record) { |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1285 | for (;;) { |
| 1286 | DWORD read_count = 0; |
| 1287 | memset(input_record, 0, sizeof(*input_record)); |
| 1288 | if (!ReadConsoleInputA(console, input_record, 1, &read_count)) { |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1289 | D("_get_key_event_record: ReadConsoleInputA() failed: %s\n", |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 1290 | android::base::SystemErrorCodeToString(GetLastError()).c_str()); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1291 | errno = EIO; |
| 1292 | return false; |
| 1293 | } |
| 1294 | |
| 1295 | if (read_count == 0) { // should be impossible |
| 1296 | fatal("ReadConsoleInputA returned 0"); |
| 1297 | } |
| 1298 | |
| 1299 | if (read_count != 1) { // should be impossible |
| 1300 | fatal("ReadConsoleInputA did not return one input record"); |
| 1301 | } |
| 1302 | |
Spencer Low | 5544140 | 2015-11-07 17:34:39 -0800 | [diff] [blame] | 1303 | // If the console window is resized, emulate SIGWINCH by breaking out |
| 1304 | // of read() with errno == EINTR. Note that there is no event on |
| 1305 | // vertical resize because we don't give the console our own custom |
| 1306 | // screen buffer (with CreateConsoleScreenBuffer() + |
| 1307 | // SetConsoleActiveScreenBuffer()). Instead, we use the default which |
| 1308 | // supports scrollback, but doesn't seem to raise an event for vertical |
| 1309 | // window resize. |
| 1310 | if (input_record->EventType == WINDOW_BUFFER_SIZE_EVENT) { |
| 1311 | errno = EINTR; |
| 1312 | return false; |
| 1313 | } |
| 1314 | |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1315 | if ((input_record->EventType == KEY_EVENT) && |
| 1316 | (input_record->Event.KeyEvent.bKeyDown)) { |
| 1317 | if (input_record->Event.KeyEvent.wRepeatCount == 0) { |
| 1318 | fatal("ReadConsoleInputA returned a key event with zero repeat" |
| 1319 | " count"); |
| 1320 | } |
| 1321 | |
| 1322 | // Got an interesting INPUT_RECORD, so return |
| 1323 | return true; |
| 1324 | } |
| 1325 | } |
| 1326 | } |
| 1327 | |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1328 | static __inline__ bool _is_shift_pressed(const DWORD control_key_state) { |
| 1329 | return (control_key_state & SHIFT_PRESSED) != 0; |
| 1330 | } |
| 1331 | |
| 1332 | static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) { |
| 1333 | return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0; |
| 1334 | } |
| 1335 | |
| 1336 | static __inline__ bool _is_alt_pressed(const DWORD control_key_state) { |
| 1337 | return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0; |
| 1338 | } |
| 1339 | |
| 1340 | static __inline__ bool _is_numlock_on(const DWORD control_key_state) { |
| 1341 | return (control_key_state & NUMLOCK_ON) != 0; |
| 1342 | } |
| 1343 | |
| 1344 | static __inline__ bool _is_capslock_on(const DWORD control_key_state) { |
| 1345 | return (control_key_state & CAPSLOCK_ON) != 0; |
| 1346 | } |
| 1347 | |
| 1348 | static __inline__ bool _is_enhanced_key(const DWORD control_key_state) { |
| 1349 | return (control_key_state & ENHANCED_KEY) != 0; |
| 1350 | } |
| 1351 | |
| 1352 | // Constants from MSDN for ToAscii(). |
| 1353 | static const BYTE TOASCII_KEY_OFF = 0x00; |
| 1354 | static const BYTE TOASCII_KEY_DOWN = 0x80; |
| 1355 | static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock |
| 1356 | |
| 1357 | // Given a key event, ignore a modifier key and return the character that was |
| 1358 | // entered without the modifier. Writes to *ch and returns the number of bytes |
| 1359 | // written. |
| 1360 | static size_t _get_char_ignoring_modifier(char* const ch, |
| 1361 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state, |
| 1362 | const WORD modifier) { |
| 1363 | // If there is no character from Windows, try ignoring the specified |
| 1364 | // modifier and look for a character. Note that if AltGr is being used, |
| 1365 | // there will be a character from Windows. |
| 1366 | if (key_event->uChar.AsciiChar == '\0') { |
| 1367 | // Note that we read the control key state from the passed in argument |
| 1368 | // instead of from key_event since the argument has been normalized. |
| 1369 | if (((modifier == VK_SHIFT) && |
| 1370 | _is_shift_pressed(control_key_state)) || |
| 1371 | ((modifier == VK_CONTROL) && |
| 1372 | _is_ctrl_pressed(control_key_state)) || |
| 1373 | ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) { |
| 1374 | |
| 1375 | BYTE key_state[256] = {0}; |
| 1376 | key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ? |
| 1377 | TOASCII_KEY_DOWN : TOASCII_KEY_OFF; |
| 1378 | key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ? |
| 1379 | TOASCII_KEY_DOWN : TOASCII_KEY_OFF; |
| 1380 | key_state[VK_MENU] = _is_alt_pressed(control_key_state) ? |
| 1381 | TOASCII_KEY_DOWN : TOASCII_KEY_OFF; |
| 1382 | key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ? |
| 1383 | TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF; |
| 1384 | |
| 1385 | // cause this modifier to be ignored |
| 1386 | key_state[modifier] = TOASCII_KEY_OFF; |
| 1387 | |
| 1388 | WORD translated = 0; |
| 1389 | if (ToAscii(key_event->wVirtualKeyCode, |
| 1390 | key_event->wVirtualScanCode, key_state, &translated, 0) == 1) { |
| 1391 | // Ignoring the modifier, we found a character. |
| 1392 | *ch = (CHAR)translated; |
| 1393 | return 1; |
| 1394 | } |
| 1395 | } |
| 1396 | } |
| 1397 | |
| 1398 | // Just use whatever Windows told us originally. |
| 1399 | *ch = key_event->uChar.AsciiChar; |
| 1400 | |
| 1401 | // If the character from Windows is NULL, return a size of zero. |
| 1402 | return (*ch == '\0') ? 0 : 1; |
| 1403 | } |
| 1404 | |
| 1405 | // If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key, |
| 1406 | // but taking into account the shift key. This is because for a sequence like |
| 1407 | // Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0, |
| 1408 | // we want to find the character ')'. |
| 1409 | // |
| 1410 | // Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0 |
| 1411 | // because it is the default key-sequence to switch the input language. |
| 1412 | // This is configurable in the Region and Language control panel. |
| 1413 | static __inline__ size_t _get_non_control_char(char* const ch, |
| 1414 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) { |
| 1415 | return _get_char_ignoring_modifier(ch, key_event, control_key_state, |
| 1416 | VK_CONTROL); |
| 1417 | } |
| 1418 | |
| 1419 | // Get without Alt. |
| 1420 | static __inline__ size_t _get_non_alt_char(char* const ch, |
| 1421 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) { |
| 1422 | return _get_char_ignoring_modifier(ch, key_event, control_key_state, |
| 1423 | VK_MENU); |
| 1424 | } |
| 1425 | |
| 1426 | // Ignore the control key, find the character from Windows, and apply any |
| 1427 | // Control key mappings (for example, Ctrl-2 is a NULL character). Writes to |
| 1428 | // *pch and returns number of bytes written. |
| 1429 | static size_t _get_control_character(char* const pch, |
| 1430 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) { |
| 1431 | const size_t len = _get_non_control_char(pch, key_event, |
| 1432 | control_key_state); |
| 1433 | |
| 1434 | if ((len == 1) && _is_ctrl_pressed(control_key_state)) { |
| 1435 | char ch = *pch; |
| 1436 | switch (ch) { |
| 1437 | case '2': |
| 1438 | case '@': |
| 1439 | case '`': |
| 1440 | ch = '\0'; |
| 1441 | break; |
| 1442 | case '3': |
| 1443 | case '[': |
| 1444 | case '{': |
| 1445 | ch = '\x1b'; |
| 1446 | break; |
| 1447 | case '4': |
| 1448 | case '\\': |
| 1449 | case '|': |
| 1450 | ch = '\x1c'; |
| 1451 | break; |
| 1452 | case '5': |
| 1453 | case ']': |
| 1454 | case '}': |
| 1455 | ch = '\x1d'; |
| 1456 | break; |
| 1457 | case '6': |
| 1458 | case '^': |
| 1459 | case '~': |
| 1460 | ch = '\x1e'; |
| 1461 | break; |
| 1462 | case '7': |
| 1463 | case '-': |
| 1464 | case '_': |
| 1465 | ch = '\x1f'; |
| 1466 | break; |
| 1467 | case '8': |
| 1468 | ch = '\x7f'; |
| 1469 | break; |
| 1470 | case '/': |
| 1471 | if (!_is_alt_pressed(control_key_state)) { |
| 1472 | ch = '\x1f'; |
| 1473 | } |
| 1474 | break; |
| 1475 | case '?': |
| 1476 | if (!_is_alt_pressed(control_key_state)) { |
| 1477 | ch = '\x7f'; |
| 1478 | } |
| 1479 | break; |
| 1480 | } |
| 1481 | *pch = ch; |
| 1482 | } |
| 1483 | |
| 1484 | return len; |
| 1485 | } |
| 1486 | |
| 1487 | static DWORD _normalize_altgr_control_key_state( |
| 1488 | const KEY_EVENT_RECORD* const key_event) { |
| 1489 | DWORD control_key_state = key_event->dwControlKeyState; |
| 1490 | |
| 1491 | // If we're in an AltGr situation where the AltGr key is down (depending on |
| 1492 | // the keyboard layout, that might be the physical right alt key which |
| 1493 | // produces a control_key_state where Right-Alt and Left-Ctrl are down) or |
| 1494 | // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have |
| 1495 | // a character (which indicates that there was an AltGr mapping), then act |
| 1496 | // as if alt and control are not really down for the purposes of modifiers. |
| 1497 | // This makes it so that if the user with, say, a German keyboard layout |
| 1498 | // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just |
| 1499 | // output the key and we don't see the Alt and Ctrl keys. |
| 1500 | if (_is_ctrl_pressed(control_key_state) && |
| 1501 | _is_alt_pressed(control_key_state) |
| 1502 | && (key_event->uChar.AsciiChar != '\0')) { |
| 1503 | // Try to remove as few bits as possible to improve our chances of |
| 1504 | // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or |
| 1505 | // Left-Alt + Right-Ctrl + AltGr. |
| 1506 | if ((control_key_state & RIGHT_ALT_PRESSED) != 0) { |
| 1507 | // Remove Right-Alt. |
| 1508 | control_key_state &= ~RIGHT_ALT_PRESSED; |
| 1509 | // If uChar is set, a Ctrl key is pressed, and Right-Alt is |
| 1510 | // pressed, Left-Ctrl is almost always set, except if the user |
| 1511 | // presses Right-Ctrl, then AltGr (in that specific order) for |
| 1512 | // whatever reason. At any rate, make sure the bit is not set. |
| 1513 | control_key_state &= ~LEFT_CTRL_PRESSED; |
| 1514 | } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) { |
| 1515 | // Remove Left-Alt. |
| 1516 | control_key_state &= ~LEFT_ALT_PRESSED; |
| 1517 | // Whichever Ctrl key is down, remove it from the state. We only |
| 1518 | // remove one key, to improve our chances of detecting the |
| 1519 | // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl. |
| 1520 | if ((control_key_state & LEFT_CTRL_PRESSED) != 0) { |
| 1521 | // Remove Left-Ctrl. |
| 1522 | control_key_state &= ~LEFT_CTRL_PRESSED; |
| 1523 | } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) { |
| 1524 | // Remove Right-Ctrl. |
| 1525 | control_key_state &= ~RIGHT_CTRL_PRESSED; |
| 1526 | } |
| 1527 | } |
| 1528 | |
| 1529 | // Note that this logic isn't 100% perfect because Windows doesn't |
| 1530 | // allow us to detect all combinations because a physical AltGr key |
| 1531 | // press shows up as two bits, plus some combinations are ambiguous |
| 1532 | // about what is actually physically pressed. |
| 1533 | } |
| 1534 | |
| 1535 | return control_key_state; |
| 1536 | } |
| 1537 | |
| 1538 | // If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in |
| 1539 | // dwControlKeyState for the following keypad keys: period, 0-9. If we detect |
| 1540 | // this scenario, set the SHIFT_PRESSED bit so we can add modifiers |
| 1541 | // appropriately. |
| 1542 | static DWORD _normalize_keypad_control_key_state(const WORD vk, |
| 1543 | const DWORD control_key_state) { |
| 1544 | if (!_is_numlock_on(control_key_state)) { |
| 1545 | return control_key_state; |
| 1546 | } |
| 1547 | if (!_is_enhanced_key(control_key_state)) { |
| 1548 | switch (vk) { |
| 1549 | case VK_INSERT: // 0 |
| 1550 | case VK_DELETE: // . |
| 1551 | case VK_END: // 1 |
| 1552 | case VK_DOWN: // 2 |
| 1553 | case VK_NEXT: // 3 |
| 1554 | case VK_LEFT: // 4 |
| 1555 | case VK_CLEAR: // 5 |
| 1556 | case VK_RIGHT: // 6 |
| 1557 | case VK_HOME: // 7 |
| 1558 | case VK_UP: // 8 |
| 1559 | case VK_PRIOR: // 9 |
| 1560 | return control_key_state | SHIFT_PRESSED; |
| 1561 | } |
| 1562 | } |
| 1563 | |
| 1564 | return control_key_state; |
| 1565 | } |
| 1566 | |
| 1567 | static const char* _get_keypad_sequence(const DWORD control_key_state, |
| 1568 | const char* const normal, const char* const shifted) { |
| 1569 | if (_is_shift_pressed(control_key_state)) { |
| 1570 | // Shift is pressed and NumLock is off |
| 1571 | return shifted; |
| 1572 | } else { |
| 1573 | // Shift is not pressed and NumLock is off, or, |
| 1574 | // Shift is pressed and NumLock is on, in which case we want the |
| 1575 | // NumLock and Shift to neutralize each other, thus, we want the normal |
| 1576 | // sequence. |
| 1577 | return normal; |
| 1578 | } |
| 1579 | // If Shift is not pressed and NumLock is on, a different virtual key code |
| 1580 | // is returned by Windows, which can be taken care of by a different case |
| 1581 | // statement in _console_read(). |
| 1582 | } |
| 1583 | |
| 1584 | // Write sequence to buf and return the number of bytes written. |
| 1585 | static size_t _get_modifier_sequence(char* const buf, const WORD vk, |
| 1586 | DWORD control_key_state, const char* const normal) { |
| 1587 | // Copy the base sequence into buf. |
| 1588 | const size_t len = strlen(normal); |
| 1589 | memcpy(buf, normal, len); |
| 1590 | |
| 1591 | int code = 0; |
| 1592 | |
| 1593 | control_key_state = _normalize_keypad_control_key_state(vk, |
| 1594 | control_key_state); |
| 1595 | |
| 1596 | if (_is_shift_pressed(control_key_state)) { |
| 1597 | code |= 0x1; |
| 1598 | } |
| 1599 | if (_is_alt_pressed(control_key_state)) { // any alt key pressed |
| 1600 | code |= 0x2; |
| 1601 | } |
| 1602 | if (_is_ctrl_pressed(control_key_state)) { // any control key pressed |
| 1603 | code |= 0x4; |
| 1604 | } |
| 1605 | // If some modifier was held down, then we need to insert the modifier code |
| 1606 | if (code != 0) { |
| 1607 | if (len == 0) { |
| 1608 | // Should be impossible because caller should pass a string of |
| 1609 | // non-zero length. |
| 1610 | return 0; |
| 1611 | } |
| 1612 | size_t index = len - 1; |
| 1613 | const char lastChar = buf[index]; |
| 1614 | if (lastChar != '~') { |
| 1615 | buf[index++] = '1'; |
| 1616 | } |
| 1617 | buf[index++] = ';'; // modifier separator |
| 1618 | // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control, |
| 1619 | // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control |
| 1620 | buf[index++] = '1' + code; |
| 1621 | buf[index++] = lastChar; // move ~ (or other last char) to the end |
| 1622 | return index; |
| 1623 | } |
| 1624 | return len; |
| 1625 | } |
| 1626 | |
| 1627 | // Write sequence to buf and return the number of bytes written. |
| 1628 | static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk, |
| 1629 | const DWORD control_key_state, const char* const normal, |
| 1630 | const char shifted) { |
| 1631 | if (_is_shift_pressed(control_key_state)) { |
| 1632 | // Shift is pressed and NumLock is off |
| 1633 | if (shifted != '\0') { |
| 1634 | buf[0] = shifted; |
| 1635 | return sizeof(buf[0]); |
| 1636 | } else { |
| 1637 | return 0; |
| 1638 | } |
| 1639 | } else { |
| 1640 | // Shift is not pressed and NumLock is off, or, |
| 1641 | // Shift is pressed and NumLock is on, in which case we want the |
| 1642 | // NumLock and Shift to neutralize each other, thus, we want the normal |
| 1643 | // sequence. |
| 1644 | return _get_modifier_sequence(buf, vk, control_key_state, normal); |
| 1645 | } |
| 1646 | // If Shift is not pressed and NumLock is on, a different virtual key code |
| 1647 | // is returned by Windows, which can be taken care of by a different case |
| 1648 | // statement in _console_read(). |
| 1649 | } |
| 1650 | |
| 1651 | // The decimal key on the keypad produces a '.' for U.S. English and a ',' for |
| 1652 | // Standard German. Figure this out at runtime so we know what to output for |
| 1653 | // Shift-VK_DELETE. |
| 1654 | static char _get_decimal_char() { |
| 1655 | return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR); |
| 1656 | } |
| 1657 | |
| 1658 | // Prefix the len bytes in buf with the escape character, and then return the |
| 1659 | // new buffer length. |
| 1660 | size_t _escape_prefix(char* const buf, const size_t len) { |
| 1661 | // If nothing to prefix, don't do anything. We might be called with |
| 1662 | // len == 0, if alt was held down with a dead key which produced nothing. |
| 1663 | if (len == 0) { |
| 1664 | return 0; |
| 1665 | } |
| 1666 | |
| 1667 | memmove(&buf[1], buf, len); |
| 1668 | buf[0] = '\x1b'; |
| 1669 | return len + 1; |
| 1670 | } |
| 1671 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1672 | // Internal buffer to satisfy future _console_read() calls. |
Josh Gao | e3a87d0 | 2015-11-11 17:56:12 -0800 | [diff] [blame] | 1673 | static auto& g_console_input_buffer = *new std::vector<char>(); |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1674 | |
| 1675 | // Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never |
| 1676 | // returns zero on console closure because Win32 consoles are never 'closed' (as far as I can tell). |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1677 | static int _console_read(const HANDLE console, void* buf, size_t len) { |
| 1678 | for (;;) { |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1679 | // Read of zero bytes should not block waiting for something from the console. |
| 1680 | if (len == 0) { |
| 1681 | return 0; |
| 1682 | } |
| 1683 | |
| 1684 | // Flush as much as possible from input buffer. |
| 1685 | if (!g_console_input_buffer.empty()) { |
| 1686 | const int bytes_read = std::min(len, g_console_input_buffer.size()); |
| 1687 | memcpy(buf, g_console_input_buffer.data(), bytes_read); |
| 1688 | const auto begin = g_console_input_buffer.begin(); |
| 1689 | g_console_input_buffer.erase(begin, begin + bytes_read); |
| 1690 | return bytes_read; |
| 1691 | } |
| 1692 | |
| 1693 | // Read from the actual console. This may block until input. |
| 1694 | INPUT_RECORD input_record; |
| 1695 | if (!_get_key_event_record(console, &input_record)) { |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1696 | return -1; |
| 1697 | } |
| 1698 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1699 | KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent; |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1700 | const WORD vk = key_event->wVirtualKeyCode; |
| 1701 | const CHAR ch = key_event->uChar.AsciiChar; |
| 1702 | const DWORD control_key_state = _normalize_altgr_control_key_state( |
| 1703 | key_event); |
| 1704 | |
| 1705 | // The following emulation code should write the output sequence to |
| 1706 | // either seqstr or to seqbuf and seqbuflen. |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 1707 | const char* seqstr = nullptr; // NULL terminated C-string |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1708 | // Enough space for max sequence string below, plus modifiers and/or |
| 1709 | // escape prefix. |
| 1710 | char seqbuf[16]; |
| 1711 | size_t seqbuflen = 0; // Space used in seqbuf. |
| 1712 | |
| 1713 | #define MATCH(vk, normal) \ |
| 1714 | case (vk): \ |
| 1715 | { \ |
| 1716 | seqstr = (normal); \ |
| 1717 | } \ |
| 1718 | break; |
| 1719 | |
| 1720 | // Modifier keys should affect the output sequence. |
| 1721 | #define MATCH_MODIFIER(vk, normal) \ |
| 1722 | case (vk): \ |
| 1723 | { \ |
| 1724 | seqbuflen = _get_modifier_sequence(seqbuf, (vk), \ |
| 1725 | control_key_state, (normal)); \ |
| 1726 | } \ |
| 1727 | break; |
| 1728 | |
| 1729 | // The shift key should affect the output sequence. |
| 1730 | #define MATCH_KEYPAD(vk, normal, shifted) \ |
| 1731 | case (vk): \ |
| 1732 | { \ |
| 1733 | seqstr = _get_keypad_sequence(control_key_state, (normal), \ |
| 1734 | (shifted)); \ |
| 1735 | } \ |
| 1736 | break; |
| 1737 | |
| 1738 | // The shift key and other modifier keys should affect the output |
| 1739 | // sequence. |
| 1740 | #define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \ |
| 1741 | case (vk): \ |
| 1742 | { \ |
| 1743 | seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \ |
| 1744 | control_key_state, (normal), (shifted)); \ |
| 1745 | } \ |
| 1746 | break; |
| 1747 | |
| 1748 | #define ESC "\x1b" |
| 1749 | #define CSI ESC "[" |
| 1750 | #define SS3 ESC "O" |
| 1751 | |
| 1752 | // Only support normal mode, not application mode. |
| 1753 | |
| 1754 | // Enhanced keys: |
| 1755 | // * 6-pack: insert, delete, home, end, page up, page down |
| 1756 | // * cursor keys: up, down, right, left |
| 1757 | // * keypad: divide, enter |
| 1758 | // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT, |
| 1759 | // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK |
| 1760 | if (_is_enhanced_key(control_key_state)) { |
| 1761 | switch (vk) { |
| 1762 | case VK_RETURN: // Enter key on keypad |
| 1763 | if (_is_ctrl_pressed(control_key_state)) { |
| 1764 | seqstr = "\n"; |
| 1765 | } else { |
| 1766 | seqstr = "\r"; |
| 1767 | } |
| 1768 | break; |
| 1769 | |
| 1770 | MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up |
| 1771 | MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down |
| 1772 | |
| 1773 | // gnome-terminal currently sends SS3 "F" and SS3 "H", but that |
| 1774 | // will be fixed soon to match xterm which sends CSI "F" and |
| 1775 | // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764 |
| 1776 | MATCH(VK_END, CSI "F"); |
| 1777 | MATCH(VK_HOME, CSI "H"); |
| 1778 | |
| 1779 | MATCH_MODIFIER(VK_LEFT, CSI "D"); |
| 1780 | MATCH_MODIFIER(VK_UP, CSI "A"); |
| 1781 | MATCH_MODIFIER(VK_RIGHT, CSI "C"); |
| 1782 | MATCH_MODIFIER(VK_DOWN, CSI "B"); |
| 1783 | |
| 1784 | MATCH_MODIFIER(VK_INSERT, CSI "2~"); |
| 1785 | MATCH_MODIFIER(VK_DELETE, CSI "3~"); |
| 1786 | |
| 1787 | MATCH(VK_DIVIDE, "/"); |
| 1788 | } |
| 1789 | } else { // Non-enhanced keys: |
| 1790 | switch (vk) { |
| 1791 | case VK_BACK: // backspace |
| 1792 | if (_is_alt_pressed(control_key_state)) { |
| 1793 | seqstr = ESC "\x7f"; |
| 1794 | } else { |
| 1795 | seqstr = "\x7f"; |
| 1796 | } |
| 1797 | break; |
| 1798 | |
| 1799 | case VK_TAB: |
| 1800 | if (_is_shift_pressed(control_key_state)) { |
| 1801 | seqstr = CSI "Z"; |
| 1802 | } else { |
| 1803 | seqstr = "\t"; |
| 1804 | } |
| 1805 | break; |
| 1806 | |
| 1807 | // Number 5 key in keypad when NumLock is off, or if NumLock is |
| 1808 | // on and Shift is down. |
| 1809 | MATCH_KEYPAD(VK_CLEAR, CSI "E", "5"); |
| 1810 | |
| 1811 | case VK_RETURN: // Enter key on main keyboard |
| 1812 | if (_is_alt_pressed(control_key_state)) { |
| 1813 | seqstr = ESC "\n"; |
| 1814 | } else if (_is_ctrl_pressed(control_key_state)) { |
| 1815 | seqstr = "\n"; |
| 1816 | } else { |
| 1817 | seqstr = "\r"; |
| 1818 | } |
| 1819 | break; |
| 1820 | |
| 1821 | // VK_ESCAPE: Don't do any special handling. The OS uses many |
| 1822 | // of the sequences with Escape and many of the remaining |
| 1823 | // sequences don't produce bKeyDown messages, only !bKeyDown |
| 1824 | // for whatever reason. |
| 1825 | |
| 1826 | case VK_SPACE: |
| 1827 | if (_is_alt_pressed(control_key_state)) { |
| 1828 | seqstr = ESC " "; |
| 1829 | } else if (_is_ctrl_pressed(control_key_state)) { |
| 1830 | seqbuf[0] = '\0'; // NULL char |
| 1831 | seqbuflen = 1; |
| 1832 | } else { |
| 1833 | seqstr = " "; |
| 1834 | } |
| 1835 | break; |
| 1836 | |
| 1837 | MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up |
| 1838 | MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down |
| 1839 | |
| 1840 | MATCH_KEYPAD(VK_END, CSI "4~", "1"); |
| 1841 | MATCH_KEYPAD(VK_HOME, CSI "1~", "7"); |
| 1842 | |
| 1843 | MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4'); |
| 1844 | MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8'); |
| 1845 | MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6'); |
| 1846 | MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2'); |
| 1847 | |
| 1848 | MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0'); |
| 1849 | MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~", |
| 1850 | _get_decimal_char()); |
| 1851 | |
| 1852 | case 0x30: // 0 |
| 1853 | case 0x31: // 1 |
| 1854 | case 0x39: // 9 |
| 1855 | case VK_OEM_1: // ;: |
| 1856 | case VK_OEM_PLUS: // =+ |
| 1857 | case VK_OEM_COMMA: // ,< |
| 1858 | case VK_OEM_PERIOD: // .> |
| 1859 | case VK_OEM_7: // '" |
| 1860 | case VK_OEM_102: // depends on keyboard, could be <> or \| |
| 1861 | case VK_OEM_2: // /? |
| 1862 | case VK_OEM_3: // `~ |
| 1863 | case VK_OEM_4: // [{ |
| 1864 | case VK_OEM_5: // \| |
| 1865 | case VK_OEM_6: // ]} |
| 1866 | { |
| 1867 | seqbuflen = _get_control_character(seqbuf, key_event, |
| 1868 | control_key_state); |
| 1869 | |
| 1870 | if (_is_alt_pressed(control_key_state)) { |
| 1871 | seqbuflen = _escape_prefix(seqbuf, seqbuflen); |
| 1872 | } |
| 1873 | } |
| 1874 | break; |
| 1875 | |
| 1876 | case 0x32: // 2 |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1877 | case 0x33: // 3 |
| 1878 | case 0x34: // 4 |
| 1879 | case 0x35: // 5 |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1880 | case 0x36: // 6 |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 1881 | case 0x37: // 7 |
| 1882 | case 0x38: // 8 |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1883 | case VK_OEM_MINUS: // -_ |
| 1884 | { |
| 1885 | seqbuflen = _get_control_character(seqbuf, key_event, |
| 1886 | control_key_state); |
| 1887 | |
| 1888 | // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then |
| 1889 | // prefix with escape. |
| 1890 | if (_is_alt_pressed(control_key_state) && |
| 1891 | !(_is_ctrl_pressed(control_key_state) && |
| 1892 | !_is_shift_pressed(control_key_state))) { |
| 1893 | seqbuflen = _escape_prefix(seqbuf, seqbuflen); |
| 1894 | } |
| 1895 | } |
| 1896 | break; |
| 1897 | |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 1898 | case 0x41: // a |
| 1899 | case 0x42: // b |
| 1900 | case 0x43: // c |
| 1901 | case 0x44: // d |
| 1902 | case 0x45: // e |
| 1903 | case 0x46: // f |
| 1904 | case 0x47: // g |
| 1905 | case 0x48: // h |
| 1906 | case 0x49: // i |
| 1907 | case 0x4a: // j |
| 1908 | case 0x4b: // k |
| 1909 | case 0x4c: // l |
| 1910 | case 0x4d: // m |
| 1911 | case 0x4e: // n |
| 1912 | case 0x4f: // o |
| 1913 | case 0x50: // p |
| 1914 | case 0x51: // q |
| 1915 | case 0x52: // r |
| 1916 | case 0x53: // s |
| 1917 | case 0x54: // t |
| 1918 | case 0x55: // u |
| 1919 | case 0x56: // v |
| 1920 | case 0x57: // w |
| 1921 | case 0x58: // x |
| 1922 | case 0x59: // y |
| 1923 | case 0x5a: // z |
| 1924 | { |
| 1925 | seqbuflen = _get_non_alt_char(seqbuf, key_event, |
| 1926 | control_key_state); |
| 1927 | |
| 1928 | // If Alt is pressed, then prefix with escape. |
| 1929 | if (_is_alt_pressed(control_key_state)) { |
| 1930 | seqbuflen = _escape_prefix(seqbuf, seqbuflen); |
| 1931 | } |
| 1932 | } |
| 1933 | break; |
| 1934 | |
| 1935 | // These virtual key codes are generated by the keys on the |
| 1936 | // keypad *when NumLock is on* and *Shift is up*. |
| 1937 | MATCH(VK_NUMPAD0, "0"); |
| 1938 | MATCH(VK_NUMPAD1, "1"); |
| 1939 | MATCH(VK_NUMPAD2, "2"); |
| 1940 | MATCH(VK_NUMPAD3, "3"); |
| 1941 | MATCH(VK_NUMPAD4, "4"); |
| 1942 | MATCH(VK_NUMPAD5, "5"); |
| 1943 | MATCH(VK_NUMPAD6, "6"); |
| 1944 | MATCH(VK_NUMPAD7, "7"); |
| 1945 | MATCH(VK_NUMPAD8, "8"); |
| 1946 | MATCH(VK_NUMPAD9, "9"); |
| 1947 | |
| 1948 | MATCH(VK_MULTIPLY, "*"); |
| 1949 | MATCH(VK_ADD, "+"); |
| 1950 | MATCH(VK_SUBTRACT, "-"); |
| 1951 | // VK_DECIMAL is generated by the . key on the keypad *when |
| 1952 | // NumLock is on* and *Shift is up* and the sequence is not |
| 1953 | // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the |
| 1954 | // Windows Security screen to come up). |
| 1955 | case VK_DECIMAL: |
| 1956 | // U.S. English uses '.', Germany German uses ','. |
| 1957 | seqbuflen = _get_non_control_char(seqbuf, key_event, |
| 1958 | control_key_state); |
| 1959 | break; |
| 1960 | |
| 1961 | MATCH_MODIFIER(VK_F1, SS3 "P"); |
| 1962 | MATCH_MODIFIER(VK_F2, SS3 "Q"); |
| 1963 | MATCH_MODIFIER(VK_F3, SS3 "R"); |
| 1964 | MATCH_MODIFIER(VK_F4, SS3 "S"); |
| 1965 | MATCH_MODIFIER(VK_F5, CSI "15~"); |
| 1966 | MATCH_MODIFIER(VK_F6, CSI "17~"); |
| 1967 | MATCH_MODIFIER(VK_F7, CSI "18~"); |
| 1968 | MATCH_MODIFIER(VK_F8, CSI "19~"); |
| 1969 | MATCH_MODIFIER(VK_F9, CSI "20~"); |
| 1970 | MATCH_MODIFIER(VK_F10, CSI "21~"); |
| 1971 | MATCH_MODIFIER(VK_F11, CSI "23~"); |
| 1972 | MATCH_MODIFIER(VK_F12, CSI "24~"); |
| 1973 | |
| 1974 | MATCH_MODIFIER(VK_F13, CSI "25~"); |
| 1975 | MATCH_MODIFIER(VK_F14, CSI "26~"); |
| 1976 | MATCH_MODIFIER(VK_F15, CSI "28~"); |
| 1977 | MATCH_MODIFIER(VK_F16, CSI "29~"); |
| 1978 | MATCH_MODIFIER(VK_F17, CSI "31~"); |
| 1979 | MATCH_MODIFIER(VK_F18, CSI "32~"); |
| 1980 | MATCH_MODIFIER(VK_F19, CSI "33~"); |
| 1981 | MATCH_MODIFIER(VK_F20, CSI "34~"); |
| 1982 | |
| 1983 | // MATCH_MODIFIER(VK_F21, ???); |
| 1984 | // MATCH_MODIFIER(VK_F22, ???); |
| 1985 | // MATCH_MODIFIER(VK_F23, ???); |
| 1986 | // MATCH_MODIFIER(VK_F24, ???); |
| 1987 | } |
| 1988 | } |
| 1989 | |
| 1990 | #undef MATCH |
| 1991 | #undef MATCH_MODIFIER |
| 1992 | #undef MATCH_KEYPAD |
| 1993 | #undef MATCH_MODIFIER_KEYPAD |
| 1994 | #undef ESC |
| 1995 | #undef CSI |
| 1996 | #undef SS3 |
| 1997 | |
| 1998 | const char* out; |
| 1999 | size_t outlen; |
| 2000 | |
| 2001 | // Check for output in any of: |
| 2002 | // * seqstr is set (and strlen can be used to determine the length). |
| 2003 | // * seqbuf and seqbuflen are set |
| 2004 | // Fallback to ch from Windows. |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 2005 | if (seqstr != nullptr) { |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2006 | out = seqstr; |
| 2007 | outlen = strlen(seqstr); |
| 2008 | } else if (seqbuflen > 0) { |
| 2009 | out = seqbuf; |
| 2010 | outlen = seqbuflen; |
| 2011 | } else if (ch != '\0') { |
| 2012 | // Use whatever Windows told us it is. |
| 2013 | seqbuf[0] = ch; |
| 2014 | seqbuflen = 1; |
| 2015 | out = seqbuf; |
| 2016 | outlen = seqbuflen; |
| 2017 | } else { |
| 2018 | // No special handling for the virtual key code and Windows isn't |
| 2019 | // telling us a character code, then we don't know how to translate |
| 2020 | // the key press. |
| 2021 | // |
| 2022 | // Consume the input and 'continue' to cause us to get a new key |
| 2023 | // event. |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2024 | D("_console_read: unknown virtual key code: %d, enhanced: %s", |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2025 | vk, _is_enhanced_key(control_key_state) ? "true" : "false"); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2026 | continue; |
| 2027 | } |
| 2028 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2029 | // put output wRepeatCount times into g_console_input_buffer |
| 2030 | while (key_event->wRepeatCount-- > 0) { |
| 2031 | g_console_input_buffer.insert(g_console_input_buffer.end(), out, out + outlen); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2032 | } |
| 2033 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2034 | // Loop around and try to flush g_console_input_buffer |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2035 | } |
| 2036 | } |
| 2037 | |
| 2038 | static DWORD _old_console_mode; // previous GetConsoleMode() result |
| 2039 | static HANDLE _console_handle; // when set, console mode should be restored |
| 2040 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 2041 | void stdin_raw_init() { |
| 2042 | const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode); |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2043 | if (in == nullptr) { |
| 2044 | return; |
| 2045 | } |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2046 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 2047 | // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of |
| 2048 | // calling the process Ctrl-C routine (configured by |
| 2049 | // SetConsoleCtrlHandler()). |
| 2050 | // Disable ENABLE_LINE_INPUT so that input is immediately sent. |
| 2051 | // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this |
| 2052 | // flag also seems necessary to have proper line-ending processing. |
Spencer Low | 5544140 | 2015-11-07 17:34:39 -0800 | [diff] [blame] | 2053 | DWORD new_console_mode = _old_console_mode & ~(ENABLE_PROCESSED_INPUT | |
| 2054 | ENABLE_LINE_INPUT | |
| 2055 | ENABLE_ECHO_INPUT); |
| 2056 | // Enable ENABLE_WINDOW_INPUT to get window resizes. |
| 2057 | new_console_mode |= ENABLE_WINDOW_INPUT; |
| 2058 | |
| 2059 | if (!SetConsoleMode(in, new_console_mode)) { |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 2060 | // This really should not fail. |
| 2061 | D("stdin_raw_init: SetConsoleMode() failed: %s", |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 2062 | android::base::SystemErrorCodeToString(GetLastError()).c_str()); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2063 | } |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 2064 | |
| 2065 | // Once this is set, it means that stdin has been configured for |
| 2066 | // reading from and that the old console mode should be restored later. |
| 2067 | _console_handle = in; |
| 2068 | |
| 2069 | // Note that we don't need to configure C Runtime line-ending |
| 2070 | // translation because _console_read() does not call the C Runtime to |
| 2071 | // read from the console. |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2072 | } |
| 2073 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 2074 | void stdin_raw_restore() { |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 2075 | if (_console_handle != nullptr) { |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 2076 | const HANDLE in = _console_handle; |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 2077 | _console_handle = nullptr; // clear state |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2078 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 2079 | if (!SetConsoleMode(in, _old_console_mode)) { |
| 2080 | // This really should not fail. |
| 2081 | D("stdin_raw_restore: SetConsoleMode() failed: %s", |
David Pursell | c573d52 | 2016-01-27 08:52:53 -0800 | [diff] [blame] | 2082 | android::base::SystemErrorCodeToString(GetLastError()).c_str()); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2083 | } |
| 2084 | } |
| 2085 | } |
| 2086 | |
Spencer Low | 5544140 | 2015-11-07 17:34:39 -0800 | [diff] [blame] | 2087 | // Called by 'adb shell' and 'adb exec-in' (via unix_read()) to read from stdin. |
| 2088 | int unix_read_interruptible(int fd, void* buf, size_t len) { |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 2089 | if ((fd == STDIN_FILENO) && (_console_handle != nullptr)) { |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2090 | // If it is a request to read from stdin, and stdin_raw_init() has been |
| 2091 | // called, and it successfully configured the console, then read from |
| 2092 | // the console using Win32 console APIs and partially emulate a unix |
| 2093 | // terminal. |
| 2094 | return _console_read(_console_handle, buf, len); |
| 2095 | } else { |
David Pursell | 3fe11f6 | 2015-10-06 15:30:03 -0700 | [diff] [blame] | 2096 | // On older versions of Windows (definitely 7, definitely not 10), |
| 2097 | // ReadConsole() with a size >= 31367 fails, so if |fd| is a console |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 2098 | // we need to limit the read size. |
| 2099 | if (len > 4096 && unix_isatty(fd)) { |
David Pursell | 3fe11f6 | 2015-10-06 15:30:03 -0700 | [diff] [blame] | 2100 | len = 4096; |
| 2101 | } |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2102 | // Just call into C Runtime which can read from pipes/files and which |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 2103 | // can do LF/CR translation (which is overridable with _setmode()). |
| 2104 | // Undefine the macro that is set in sysdeps.h which bans calls to |
| 2105 | // plain read() in favor of unix_read() or adb_read(). |
| 2106 | #pragma push_macro("read") |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2107 | #undef read |
| 2108 | return read(fd, buf, len); |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 2109 | #pragma pop_macro("read") |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2110 | } |
| 2111 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2112 | |
| 2113 | /**************************************************************************/ |
| 2114 | /**************************************************************************/ |
| 2115 | /***** *****/ |
| 2116 | /***** Unicode support *****/ |
| 2117 | /***** *****/ |
| 2118 | /**************************************************************************/ |
| 2119 | /**************************************************************************/ |
| 2120 | |
| 2121 | // This implements support for using files with Unicode filenames and for |
| 2122 | // outputting Unicode text to a Win32 console window. This is inspired from |
| 2123 | // http://utf8everywhere.org/. |
| 2124 | // |
| 2125 | // Background |
| 2126 | // ---------- |
| 2127 | // |
| 2128 | // On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8 |
| 2129 | // filenames to APIs such as open(). This works because filenames are largely |
| 2130 | // opaque 'cookies' (perhaps excluding path separators). |
| 2131 | // |
| 2132 | // On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t |
| 2133 | // UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char |
| 2134 | // strings, but the strings are in the ANSI codepage and not UTF-8. (The |
| 2135 | // CreateFile() API is really just a macro that adds the W/A based on whether |
| 2136 | // the UNICODE preprocessor symbol is defined). |
| 2137 | // |
| 2138 | // Options |
| 2139 | // ------- |
| 2140 | // |
| 2141 | // Thus, to write a portable program, there are a few options: |
| 2142 | // |
| 2143 | // 1. Write the program with wchar_t filenames (wchar_t path[256];). |
| 2144 | // For Windows, just call CreateFileW(). For POSIX, write a wrapper openW() |
| 2145 | // that takes a wchar_t string, converts it to UTF-8 and then calls the real |
| 2146 | // open() API. |
| 2147 | // |
| 2148 | // 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and |
| 2149 | // 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those, |
| 2150 | // potentially touching a lot of code. |
| 2151 | // |
| 2152 | // 3. Write the program with a 1-byte char filenames (char path[256];) that are |
| 2153 | // UTF-8. For POSIX, just call open(). For Windows, write a wrapper that |
| 2154 | // takes a UTF-8 string, converts it to UTF-16 and then calls the real OS |
| 2155 | // or C Runtime API. |
| 2156 | // |
| 2157 | // The Choice |
| 2158 | // ---------- |
| 2159 | // |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2160 | // The code below chooses option 3, the UTF-8 everywhere strategy. It uses |
| 2161 | // android::base::WideToUTF8() which converts UTF-16 to UTF-8. This is used by the |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2162 | // NarrowArgs helper class that is used to convert wmain() args into UTF-8 |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2163 | // args that are passed to main() at the beginning of program startup. We also use |
| 2164 | // android::base::UTF8ToWide() which converts from UTF-8 to UTF-16. This is used to |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2165 | // implement wrappers below that call UTF-16 OS and C Runtime APIs. |
| 2166 | // |
| 2167 | // Unicode console output |
| 2168 | // ---------------------- |
| 2169 | // |
| 2170 | // The way to output Unicode to a Win32 console window is to call |
| 2171 | // WriteConsoleW() with UTF-16 text. (The user must also choose a proper font |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 2172 | // such as Lucida Console or Consolas, and in the case of East Asian languages |
| 2173 | // (such as Chinese, Japanese, Korean), the user must go to the Control Panel |
| 2174 | // and change the "system locale" to Chinese, etc., which allows a Chinese, etc. |
| 2175 | // font to be used in console windows.) |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2176 | // |
| 2177 | // The problem is getting the C Runtime to make fprintf and related APIs call |
| 2178 | // WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds |
| 2179 | // promising, but the various modes have issues: |
| 2180 | // |
| 2181 | // 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and |
| 2182 | // UTF-16 do not display properly. |
| 2183 | // 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out |
| 2184 | // totally wrong. |
| 2185 | // 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter |
| 2186 | // handler to be called (upon a later I/O call), aborting the process. |
| 2187 | // 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf |
| 2188 | // to output nothing. |
| 2189 | // |
| 2190 | // So the only solution is to write our own adb_fprintf() that converts UTF-8 |
| 2191 | // to UTF-16 and then calls WriteConsoleW(). |
| 2192 | |
| 2193 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2194 | // Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to |
| 2195 | // be passed to main(). |
| 2196 | NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) { |
| 2197 | narrow_args = new char*[argc + 1]; |
| 2198 | |
| 2199 | for (int i = 0; i < argc; ++i) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2200 | std::string arg_narrow; |
| 2201 | if (!android::base::WideToUTF8(argv[i], &arg_narrow)) { |
| 2202 | fatal_errno("cannot convert argument from UTF-16 to UTF-8"); |
| 2203 | } |
| 2204 | narrow_args[i] = strdup(arg_narrow.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2205 | } |
| 2206 | narrow_args[argc] = nullptr; // terminate |
| 2207 | } |
| 2208 | |
| 2209 | NarrowArgs::~NarrowArgs() { |
| 2210 | if (narrow_args != nullptr) { |
| 2211 | for (char** argp = narrow_args; *argp != nullptr; ++argp) { |
| 2212 | free(*argp); |
| 2213 | } |
| 2214 | delete[] narrow_args; |
| 2215 | narrow_args = nullptr; |
| 2216 | } |
| 2217 | } |
| 2218 | |
| 2219 | int unix_open(const char* path, int options, ...) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2220 | std::wstring path_wide; |
| 2221 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 2222 | return -1; |
| 2223 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2224 | if ((options & O_CREAT) == 0) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2225 | return _wopen(path_wide.c_str(), options); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2226 | } else { |
| 2227 | int mode; |
| 2228 | va_list args; |
| 2229 | va_start(args, options); |
| 2230 | mode = va_arg(args, int); |
| 2231 | va_end(args); |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2232 | return _wopen(path_wide.c_str(), options, mode); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2233 | } |
| 2234 | } |
| 2235 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2236 | // Version of opendir() that takes a UTF-8 path. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2237 | DIR* adb_opendir(const char* path) { |
| 2238 | std::wstring path_wide; |
| 2239 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 2240 | return nullptr; |
| 2241 | } |
| 2242 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2243 | // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of |
| 2244 | // the fields, but right now all the callers treat the structure as |
| 2245 | // opaque. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2246 | return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str())); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2247 | } |
| 2248 | |
| 2249 | // Version of readdir() that returns UTF-8 paths. |
| 2250 | struct dirent* adb_readdir(DIR* dir) { |
| 2251 | _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir); |
| 2252 | struct _wdirent* const went = _wreaddir(wdir); |
| 2253 | if (went == nullptr) { |
| 2254 | return nullptr; |
| 2255 | } |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2256 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2257 | // Convert from UTF-16 to UTF-8. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2258 | std::string name_utf8; |
| 2259 | if (!android::base::WideToUTF8(went->d_name, &name_utf8)) { |
| 2260 | return nullptr; |
| 2261 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2262 | |
| 2263 | // Cast the _wdirent* to dirent* and overwrite the d_name field (which has |
| 2264 | // space for UTF-16 wchar_t's) with UTF-8 char's. |
| 2265 | struct dirent* ent = reinterpret_cast<struct dirent*>(went); |
| 2266 | |
| 2267 | if (name_utf8.length() + 1 > sizeof(went->d_name)) { |
| 2268 | // Name too big to fit in existing buffer. |
| 2269 | errno = ENOMEM; |
| 2270 | return nullptr; |
| 2271 | } |
| 2272 | |
| 2273 | // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name) |
| 2274 | // because _wdirent contains wchar_t instead of char. So even if name_utf8 |
| 2275 | // can fit in _wdirent::d_name, the resulting dirent::d_name field may be |
| 2276 | // bigger than the caller expects because they expect a dirent structure |
| 2277 | // which has a smaller d_name field. Ignore this since the caller should be |
| 2278 | // resilient. |
| 2279 | |
| 2280 | // Rewrite the UTF-16 d_name field to UTF-8. |
| 2281 | strcpy(ent->d_name, name_utf8.c_str()); |
| 2282 | |
| 2283 | return ent; |
| 2284 | } |
| 2285 | |
| 2286 | // Version of closedir() to go with our version of adb_opendir(). |
| 2287 | int adb_closedir(DIR* dir) { |
| 2288 | return _wclosedir(reinterpret_cast<_WDIR*>(dir)); |
| 2289 | } |
| 2290 | |
| 2291 | // Version of unlink() that takes a UTF-8 path. |
| 2292 | int adb_unlink(const char* path) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2293 | std::wstring wpath; |
| 2294 | if (!android::base::UTF8ToWide(path, &wpath)) { |
| 2295 | return -1; |
| 2296 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2297 | |
| 2298 | int rc = _wunlink(wpath.c_str()); |
| 2299 | |
| 2300 | if (rc == -1 && errno == EACCES) { |
| 2301 | /* unlink returns EACCES when the file is read-only, so we first */ |
| 2302 | /* try to make it writable, then unlink again... */ |
| 2303 | rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE); |
| 2304 | if (rc == 0) |
| 2305 | rc = _wunlink(wpath.c_str()); |
| 2306 | } |
| 2307 | return rc; |
| 2308 | } |
| 2309 | |
| 2310 | // Version of mkdir() that takes a UTF-8 path. |
| 2311 | int adb_mkdir(const std::string& path, int mode) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2312 | std::wstring path_wide; |
| 2313 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 2314 | return -1; |
| 2315 | } |
| 2316 | |
| 2317 | return _wmkdir(path_wide.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2318 | } |
| 2319 | |
| 2320 | // Version of utime() that takes a UTF-8 path. |
| 2321 | int adb_utime(const char* path, struct utimbuf* u) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2322 | std::wstring path_wide; |
| 2323 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 2324 | return -1; |
| 2325 | } |
| 2326 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2327 | static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf), |
| 2328 | "utimbuf and _utimbuf should be the same size because they both " |
| 2329 | "contain the same types, namely time_t"); |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2330 | return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u)); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2331 | } |
| 2332 | |
| 2333 | // Version of chmod() that takes a UTF-8 path. |
| 2334 | int adb_chmod(const char* path, int mode) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2335 | std::wstring path_wide; |
| 2336 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 2337 | return -1; |
| 2338 | } |
| 2339 | |
| 2340 | return _wchmod(path_wide.c_str(), mode); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2341 | } |
| 2342 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2343 | // From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte. |
| 2344 | static inline size_t utf8_codepoint_len(uint8_t ch) { |
| 2345 | return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1; |
| 2346 | } |
Elliott Hughes | 37be38a | 2015-11-11 18:02:29 +0000 | [diff] [blame] | 2347 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2348 | namespace internal { |
| 2349 | |
| 2350 | // Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes |
| 2351 | // (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to |
| 2352 | // remaining_bytes. |
| 2353 | size_t ParseCompleteUTF8(const char* const first, const char* const last, |
| 2354 | std::vector<char>* const remaining_bytes) { |
| 2355 | // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence. |
| 2356 | // Current_after points one byte past the current byte to be examined. |
| 2357 | for (const char* current_after = last; current_after != first; --current_after) { |
| 2358 | const char* const current = current_after - 1; |
| 2359 | const char ch = *current; |
| 2360 | const char kHighBit = 0x80u; |
| 2361 | const char kTwoHighestBits = 0xC0u; |
| 2362 | if ((ch & kHighBit) == 0) { // high bit not set |
| 2363 | // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing |
| 2364 | // bytes with no leading byte, so return the entire buffer. |
| 2365 | break; |
| 2366 | } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set |
| 2367 | // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence. |
| 2368 | const size_t bytes_available = last - current; |
| 2369 | if (bytes_available < utf8_codepoint_len(ch)) { |
| 2370 | // We don't have all the bytes in the UTF-8 sequence, so return all the bytes |
| 2371 | // preceding the current incomplete UTF-8 sequence and append the remaining bytes |
| 2372 | // to remaining_bytes. |
| 2373 | remaining_bytes->insert(remaining_bytes->end(), current, last); |
| 2374 | return current - first; |
| 2375 | } else { |
| 2376 | // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid |
| 2377 | // trailing bytes with no lead byte, so return the entire buffer. |
| 2378 | break; |
| 2379 | } |
| 2380 | } else { |
| 2381 | // Trailing byte, so keep going backwards looking for the lead byte. |
| 2382 | } |
| 2383 | } |
| 2384 | |
| 2385 | // Return the size of the entire buffer. It is possible that we walked backward past invalid |
| 2386 | // trailing bytes with no lead byte, in which case we want to return all those invalid bytes |
| 2387 | // so that they can be processed. |
| 2388 | return last - first; |
| 2389 | } |
| 2390 | |
| 2391 | } |
| 2392 | |
| 2393 | // Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences. |
| 2394 | // Note that we use only one buffer even though stderr and stdout are logically separate streams. |
| 2395 | // This matches the behavior of Linux. |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2396 | |
| 2397 | // Internal helper function to write UTF-8 bytes to a console. Returns -1 on error. |
| 2398 | static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream, |
| 2399 | HANDLE console) { |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 2400 | static std::mutex& console_output_buffer_lock = *new std::mutex(); |
| 2401 | static auto& console_output_buffer = *new std::vector<char>(); |
| 2402 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2403 | const int saved_errno = errno; |
| 2404 | std::vector<char> combined_buffer; |
| 2405 | |
| 2406 | // Complete UTF-8 sequences that should be immediately written to the console. |
| 2407 | const char* utf8; |
| 2408 | size_t utf8_size; |
| 2409 | |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 2410 | { |
| 2411 | std::lock_guard<std::mutex> lock(console_output_buffer_lock); |
| 2412 | if (console_output_buffer.empty()) { |
| 2413 | // If console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the |
| 2414 | // common case with plain ASCII), parse buf directly. |
| 2415 | utf8 = buf; |
| 2416 | utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &console_output_buffer); |
| 2417 | } else { |
| 2418 | // If console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to |
| 2419 | // combined_buffer (and effectively clear console_output_buffer) and append buf to |
| 2420 | // combined_buffer, then parse it all together. |
| 2421 | combined_buffer.swap(console_output_buffer); |
| 2422 | combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size); |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2423 | |
Josh Gao | e7daf57 | 2016-09-21 12:37:10 -0700 | [diff] [blame] | 2424 | utf8 = combined_buffer.data(); |
| 2425 | utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(), |
| 2426 | &console_output_buffer); |
| 2427 | } |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2428 | } |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2429 | |
| 2430 | std::wstring utf16; |
| 2431 | |
| 2432 | // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux |
| 2433 | // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's |
| 2434 | // random data, runs dmesg (which might have non-UTF-8), etc. |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2435 | // This could throw std::bad_alloc. |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2436 | (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2437 | |
| 2438 | // Note that this does not do \n => \r\n translation because that |
| 2439 | // doesn't seem necessary for the Windows console. For the Windows |
| 2440 | // console \r moves to the beginning of the line and \n moves to a new |
| 2441 | // line. |
| 2442 | |
| 2443 | // Flush any stream buffering so that our output is afterwards which |
| 2444 | // makes sense because our call is afterwards. |
| 2445 | (void)fflush(stream); |
| 2446 | |
| 2447 | // Write UTF-16 to the console. |
| 2448 | DWORD written = 0; |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 2449 | if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, nullptr)) { |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2450 | errno = EIO; |
| 2451 | return -1; |
| 2452 | } |
| 2453 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2454 | // Return the size of the original buffer passed in, signifying that we consumed it all, even |
| 2455 | // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This |
| 2456 | // matches the Linux behavior. |
| 2457 | errno = saved_errno; |
| 2458 | return buf_size; |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2459 | } |
| 2460 | |
| 2461 | // Function prototype because attributes cannot be placed on func definitions. |
Elliott Hughes | 874c941 | 2018-06-26 13:06:15 -0700 | [diff] [blame] | 2462 | static int _console_vfprintf(const HANDLE console, FILE* stream, const char* format, va_list ap) |
| 2463 | __attribute__((__format__(__printf__, 3, 0))); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2464 | |
| 2465 | // Internal function to format a UTF-8 string and write it to a Win32 console. |
| 2466 | // Returns -1 on error. |
| 2467 | static int _console_vfprintf(const HANDLE console, FILE* stream, |
| 2468 | const char *format, va_list ap) { |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2469 | const int saved_errno = errno; |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2470 | std::string output_utf8; |
| 2471 | |
| 2472 | // Format the string. |
| 2473 | // This could throw std::bad_alloc. |
| 2474 | android::base::StringAppendV(&output_utf8, format, ap); |
| 2475 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2476 | const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream, |
| 2477 | console); |
| 2478 | if (result != -1) { |
| 2479 | errno = saved_errno; |
| 2480 | } else { |
| 2481 | // If -1 was returned, errno has been set. |
| 2482 | } |
| 2483 | return result; |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2484 | } |
| 2485 | |
| 2486 | // Version of vfprintf() that takes UTF-8 and can write Unicode to a |
| 2487 | // Windows console. |
| 2488 | int adb_vfprintf(FILE *stream, const char *format, va_list ap) { |
| 2489 | const HANDLE console = _get_console_handle(stream); |
| 2490 | |
| 2491 | // If there is an associated Win32 console, write to it specially, |
| 2492 | // otherwise defer to the regular C Runtime, passing it UTF-8. |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 2493 | if (console != nullptr) { |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2494 | return _console_vfprintf(console, stream, format, ap); |
| 2495 | } else { |
| 2496 | // If vfprintf is a macro, undefine it, so we can call the real |
| 2497 | // C Runtime API. |
| 2498 | #pragma push_macro("vfprintf") |
| 2499 | #undef vfprintf |
| 2500 | return vfprintf(stream, format, ap); |
| 2501 | #pragma pop_macro("vfprintf") |
| 2502 | } |
| 2503 | } |
| 2504 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2505 | // Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console. |
| 2506 | int adb_vprintf(const char *format, va_list ap) { |
| 2507 | return adb_vfprintf(stdout, format, ap); |
| 2508 | } |
| 2509 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2510 | // Version of fprintf() that takes UTF-8 and can write Unicode to a |
| 2511 | // Windows console. |
| 2512 | int adb_fprintf(FILE *stream, const char *format, ...) { |
| 2513 | va_list ap; |
| 2514 | va_start(ap, format); |
| 2515 | const int result = adb_vfprintf(stream, format, ap); |
| 2516 | va_end(ap); |
| 2517 | |
| 2518 | return result; |
| 2519 | } |
| 2520 | |
| 2521 | // Version of printf() that takes UTF-8 and can write Unicode to a |
| 2522 | // Windows console. |
| 2523 | int adb_printf(const char *format, ...) { |
| 2524 | va_list ap; |
| 2525 | va_start(ap, format); |
| 2526 | const int result = adb_vfprintf(stdout, format, ap); |
| 2527 | va_end(ap); |
| 2528 | |
| 2529 | return result; |
| 2530 | } |
| 2531 | |
| 2532 | // Version of fputs() that takes UTF-8 and can write Unicode to a |
| 2533 | // Windows console. |
| 2534 | int adb_fputs(const char* buf, FILE* stream) { |
| 2535 | // adb_fprintf returns -1 on error, which is conveniently the same as EOF |
| 2536 | // which fputs (and hence adb_fputs) should return on error. |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2537 | static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed"); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2538 | return adb_fprintf(stream, "%s", buf); |
| 2539 | } |
| 2540 | |
| 2541 | // Version of fputc() that takes UTF-8 and can write Unicode to a |
| 2542 | // Windows console. |
| 2543 | int adb_fputc(int ch, FILE* stream) { |
| 2544 | const int result = adb_fprintf(stream, "%c", ch); |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2545 | if (result == -1) { |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2546 | return EOF; |
| 2547 | } |
| 2548 | // For success, fputc returns the char, cast to unsigned char, then to int. |
| 2549 | return static_cast<unsigned char>(ch); |
| 2550 | } |
| 2551 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2552 | // Version of putchar() that takes UTF-8 and can write Unicode to a Windows console. |
| 2553 | int adb_putchar(int ch) { |
| 2554 | return adb_fputc(ch, stdout); |
| 2555 | } |
| 2556 | |
| 2557 | // Version of puts() that takes UTF-8 and can write Unicode to a Windows console. |
| 2558 | int adb_puts(const char* buf) { |
| 2559 | // adb_printf returns -1 on error, which is conveniently the same as EOF |
| 2560 | // which puts (and hence adb_puts) should return on error. |
| 2561 | static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed"); |
| 2562 | return adb_printf("%s\n", buf); |
| 2563 | } |
| 2564 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2565 | // Internal function to write UTF-8 to a Win32 console. Returns the number of |
| 2566 | // items (of length size) written. On error, returns a short item count or 0. |
| 2567 | static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb, |
| 2568 | FILE* stream, HANDLE console) { |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame] | 2569 | const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream, |
| 2570 | console); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2571 | if (result == -1) { |
| 2572 | return 0; |
| 2573 | } |
| 2574 | return result / size; |
| 2575 | } |
| 2576 | |
| 2577 | // Version of fwrite() that takes UTF-8 and can write Unicode to a |
| 2578 | // Windows console. |
| 2579 | size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) { |
| 2580 | const HANDLE console = _get_console_handle(stream); |
| 2581 | |
| 2582 | // If there is an associated Win32 console, write to it specially, |
| 2583 | // otherwise defer to the regular C Runtime, passing it UTF-8. |
Yi Kong | 86e6718 | 2018-07-13 18:15:16 -0700 | [diff] [blame] | 2584 | if (console != nullptr) { |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2585 | return _console_fwrite(ptr, size, nmemb, stream, console); |
| 2586 | } else { |
| 2587 | // If fwrite is a macro, undefine it, so we can call the real |
| 2588 | // C Runtime API. |
| 2589 | #pragma push_macro("fwrite") |
| 2590 | #undef fwrite |
| 2591 | return fwrite(ptr, size, nmemb, stream); |
| 2592 | #pragma pop_macro("fwrite") |
| 2593 | } |
| 2594 | } |
| 2595 | |
| 2596 | // Version of fopen() that takes a UTF-8 filename and can access a file with |
| 2597 | // a Unicode filename. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2598 | FILE* adb_fopen(const char* path, const char* mode) { |
| 2599 | std::wstring path_wide; |
| 2600 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 2601 | return nullptr; |
| 2602 | } |
| 2603 | |
| 2604 | std::wstring mode_wide; |
| 2605 | if (!android::base::UTF8ToWide(mode, &mode_wide)) { |
| 2606 | return nullptr; |
| 2607 | } |
| 2608 | |
| 2609 | return _wfopen(path_wide.c_str(), mode_wide.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2610 | } |
| 2611 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 2612 | // Return a lowercase version of the argument. Uses C Runtime tolower() on |
| 2613 | // each byte which is not UTF-8 aware, and theoretically uses the current C |
| 2614 | // Runtime locale (which in practice is not changed, so this becomes a ASCII |
| 2615 | // conversion). |
| 2616 | static std::string ToLower(const std::string& anycase) { |
| 2617 | // copy string |
| 2618 | std::string str(anycase); |
| 2619 | // transform the copy |
| 2620 | std::transform(str.begin(), str.end(), str.begin(), tolower); |
| 2621 | return str; |
| 2622 | } |
| 2623 | |
| 2624 | extern "C" int main(int argc, char** argv); |
| 2625 | |
| 2626 | // Link with -municode to cause this wmain() to be used as the program |
| 2627 | // entrypoint. It will convert the args from UTF-16 to UTF-8 and call the |
| 2628 | // regular main() with UTF-8 args. |
| 2629 | extern "C" int wmain(int argc, wchar_t **argv) { |
| 2630 | // Convert args from UTF-16 to UTF-8 and pass that to main(). |
| 2631 | NarrowArgs narrow_args(argc, argv); |
| 2632 | return main(argc, narrow_args.data()); |
| 2633 | } |
| 2634 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2635 | // Shadow UTF-8 environment variable name/value pairs that are created from |
| 2636 | // _wenviron the first time that adb_getenv() is called. Note that this is not |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 2637 | // currently updated if putenv, setenv, unsetenv are called. Note that no |
| 2638 | // thread synchronization is done, but we're called early enough in |
| 2639 | // single-threaded startup that things work ok. |
Josh Gao | e3a87d0 | 2015-11-11 17:56:12 -0800 | [diff] [blame] | 2640 | static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>(); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2641 | |
| 2642 | // Make sure that shadow UTF-8 environment variables are setup. |
| 2643 | static void _ensure_env_setup() { |
| 2644 | // If some name/value pairs exist, then we've already done the setup below. |
| 2645 | if (g_environ_utf8.size() != 0) { |
| 2646 | return; |
| 2647 | } |
| 2648 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 2649 | if (_wenviron == nullptr) { |
| 2650 | // If _wenviron is null, then -municode probably wasn't used. That |
| 2651 | // linker flag will cause the entry point to setup _wenviron. It will |
| 2652 | // also require an implementation of wmain() (which we provide above). |
| 2653 | fatal("_wenviron is not set, did you link with -municode?"); |
| 2654 | } |
| 2655 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2656 | // Read name/value pairs from UTF-16 _wenviron and write new name/value |
| 2657 | // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense |
| 2658 | // to use the D() macro here because that tracing only works if the |
| 2659 | // ADB_TRACE environment variable is setup, but that env var can't be read |
| 2660 | // until this code completes. |
| 2661 | for (wchar_t** env = _wenviron; *env != nullptr; ++env) { |
| 2662 | wchar_t* const equal = wcschr(*env, L'='); |
| 2663 | if (equal == nullptr) { |
| 2664 | // Malformed environment variable with no equal sign. Shouldn't |
| 2665 | // really happen, but we should be resilient to this. |
| 2666 | continue; |
| 2667 | } |
| 2668 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2669 | // If we encounter an error converting UTF-16, don't error-out on account of a single env |
| 2670 | // var because the program might never even read this particular variable. |
| 2671 | std::string name_utf8; |
| 2672 | if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) { |
| 2673 | continue; |
| 2674 | } |
| 2675 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 2676 | // Store lowercase name so that we can do case-insensitive searches. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2677 | name_utf8 = ToLower(name_utf8); |
| 2678 | |
| 2679 | std::string value_utf8; |
| 2680 | if (!android::base::WideToUTF8(equal + 1, &value_utf8)) { |
| 2681 | continue; |
| 2682 | } |
| 2683 | |
| 2684 | char* const value_dup = strdup(value_utf8.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2685 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 2686 | // Don't overwrite a previus env var with the same name. In reality, |
| 2687 | // the system probably won't let two env vars with the same name exist |
| 2688 | // in _wenviron. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2689 | g_environ_utf8.insert({name_utf8, value_dup}); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2690 | } |
| 2691 | } |
| 2692 | |
| 2693 | // Version of getenv() that takes a UTF-8 environment variable name and |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 2694 | // retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows. |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2695 | char* adb_getenv(const char* name) { |
| 2696 | _ensure_env_setup(); |
| 2697 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 2698 | // Case-insensitive search by searching for lowercase name in a map of |
| 2699 | // lowercase names. |
| 2700 | const auto it = g_environ_utf8.find(ToLower(std::string(name))); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2701 | if (it == g_environ_utf8.end()) { |
| 2702 | return nullptr; |
| 2703 | } |
| 2704 | |
| 2705 | return it->second; |
| 2706 | } |
| 2707 | |
| 2708 | // Version of getcwd() that returns the current working directory in UTF-8. |
| 2709 | char* adb_getcwd(char* buf, int size) { |
| 2710 | wchar_t* wbuf = _wgetcwd(nullptr, 0); |
| 2711 | if (wbuf == nullptr) { |
| 2712 | return nullptr; |
| 2713 | } |
| 2714 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2715 | std::string buf_utf8; |
| 2716 | const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2717 | free(wbuf); |
| 2718 | wbuf = nullptr; |
| 2719 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 2720 | if (!narrow_result) { |
| 2721 | return nullptr; |
| 2722 | } |
| 2723 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 2724 | // If size was specified, make sure all the chars will fit. |
| 2725 | if (size != 0) { |
| 2726 | if (size < static_cast<int>(buf_utf8.length() + 1)) { |
| 2727 | errno = ERANGE; |
| 2728 | return nullptr; |
| 2729 | } |
| 2730 | } |
| 2731 | |
| 2732 | // If buf was not specified, allocate storage. |
| 2733 | if (buf == nullptr) { |
| 2734 | if (size == 0) { |
| 2735 | size = buf_utf8.length() + 1; |
| 2736 | } |
| 2737 | buf = reinterpret_cast<char*>(malloc(size)); |
| 2738 | if (buf == nullptr) { |
| 2739 | return nullptr; |
| 2740 | } |
| 2741 | } |
| 2742 | |
| 2743 | // Destination buffer was allocated with enough space, or we've already |
| 2744 | // checked an existing buffer size for enough space. |
| 2745 | strcpy(buf, buf_utf8.c_str()); |
| 2746 | |
| 2747 | return buf; |
| 2748 | } |
Spencer Low | ae37a31 | 2018-09-03 16:03:22 -0700 | [diff] [blame] | 2749 | |
| 2750 | // The SetThreadDescription API was brought in version 1607 of Windows 10. |
| 2751 | typedef HRESULT(WINAPI* SetThreadDescription)(HANDLE hThread, PCWSTR lpThreadDescription); |
| 2752 | |
| 2753 | // Based on PlatformThread::SetName() from |
| 2754 | // https://cs.chromium.org/chromium/src/base/threading/platform_thread_win.cc |
| 2755 | int adb_thread_setname(const std::string& name) { |
| 2756 | // The SetThreadDescription API works even if no debugger is attached. |
| 2757 | auto set_thread_description_func = reinterpret_cast<SetThreadDescription>( |
| 2758 | ::GetProcAddress(::GetModuleHandleW(L"Kernel32.dll"), "SetThreadDescription")); |
| 2759 | if (set_thread_description_func) { |
| 2760 | std::wstring name_wide; |
| 2761 | if (!android::base::UTF8ToWide(name.c_str(), &name_wide)) { |
| 2762 | return errno; |
| 2763 | } |
| 2764 | set_thread_description_func(::GetCurrentThread(), name_wide.c_str()); |
| 2765 | } |
| 2766 | |
| 2767 | // Don't use the thread naming SEH exception because we're compiled with -fno-exceptions. |
| 2768 | // https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code?view=vs-2017 |
| 2769 | |
| 2770 | return 0; |
| 2771 | } |