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