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