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