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