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