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