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