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> |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 32 | |
Elliott Hughes | fe44751 | 2015-07-24 11:35:40 -0700 | [diff] [blame] | 33 | #include <cutils/sockets.h> |
| 34 | |
Elliott Hughes | f55ead9 | 2015-12-04 22:00:26 -0800 | [diff] [blame] | 35 | #include <android-base/logging.h> |
| 36 | #include <android-base/stringprintf.h> |
| 37 | #include <android-base/strings.h> |
| 38 | #include <android-base/utf8.h> |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 39 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 40 | #include "adb.h" |
| 41 | |
| 42 | extern void fatal(const char *fmt, ...); |
| 43 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 44 | /* forward declarations */ |
| 45 | |
| 46 | typedef const struct FHClassRec_* FHClass; |
| 47 | typedef struct FHRec_* FH; |
| 48 | typedef struct EventHookRec_* EventHook; |
| 49 | |
| 50 | typedef struct FHClassRec_ { |
| 51 | void (*_fh_init)(FH); |
| 52 | int (*_fh_close)(FH); |
| 53 | int (*_fh_lseek)(FH, int, int); |
| 54 | int (*_fh_read)(FH, void*, int); |
| 55 | int (*_fh_write)(FH, const void*, int); |
| 56 | void (*_fh_hook)(FH, int, EventHook); |
| 57 | } FHClassRec; |
| 58 | |
| 59 | static void _fh_file_init(FH); |
| 60 | static int _fh_file_close(FH); |
| 61 | static int _fh_file_lseek(FH, int, int); |
| 62 | static int _fh_file_read(FH, void*, int); |
| 63 | static int _fh_file_write(FH, const void*, int); |
| 64 | static void _fh_file_hook(FH, int, EventHook); |
| 65 | |
| 66 | static const FHClassRec _fh_file_class = { |
| 67 | _fh_file_init, |
| 68 | _fh_file_close, |
| 69 | _fh_file_lseek, |
| 70 | _fh_file_read, |
| 71 | _fh_file_write, |
| 72 | _fh_file_hook |
| 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); |
| 80 | static void _fh_socket_hook(FH, int, EventHook); |
| 81 | |
| 82 | static const FHClassRec _fh_socket_class = { |
| 83 | _fh_socket_init, |
| 84 | _fh_socket_close, |
| 85 | _fh_socket_lseek, |
| 86 | _fh_socket_read, |
| 87 | _fh_socket_write, |
| 88 | _fh_socket_hook |
| 89 | }; |
| 90 | |
Josh Gao | 2930cdc | 2016-01-15 15:17:37 -0800 | [diff] [blame] | 91 | #define assert(cond) \ |
| 92 | do { \ |
| 93 | if (!(cond)) fatal("assertion failed '%s' on %s:%d\n", #cond, __FILE__, __LINE__); \ |
| 94 | } while (0) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 95 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 96 | std::string SystemErrorCodeToString(const DWORD error_code) { |
| 97 | const int kErrorMessageBufferSize = 256; |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 98 | WCHAR msgbuf[kErrorMessageBufferSize]; |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 99 | DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 100 | DWORD len = FormatMessageW(flags, nullptr, error_code, 0, msgbuf, |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 101 | arraysize(msgbuf), nullptr); |
| 102 | if (len == 0) { |
| 103 | return android::base::StringPrintf( |
| 104 | "Error (%lu) while retrieving error. (%lu)", GetLastError(), |
| 105 | error_code); |
| 106 | } |
| 107 | |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 108 | // Convert UTF-16 to UTF-8. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 109 | std::string msg; |
| 110 | if (!android::base::WideToUTF8(msgbuf, &msg)) { |
| 111 | return android::base::StringPrintf( |
| 112 | "Error (%d) converting from UTF-16 to UTF-8 while retrieving error. (%lu)", errno, |
| 113 | error_code); |
| 114 | } |
| 115 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 116 | // Messages returned by the system end with line breaks. |
| 117 | msg = android::base::Trim(msg); |
| 118 | // There are many Windows error messages compared to POSIX, so include the |
| 119 | // numeric error code for easier, quicker, accurate identification. Use |
| 120 | // decimal instead of hex because there are decimal ranges like 10000-11999 |
| 121 | // for Winsock. |
| 122 | android::base::StringAppendF(&msg, " (%lu)", error_code); |
| 123 | return msg; |
| 124 | } |
| 125 | |
Spencer Low | 2bbb3a9 | 2015-08-26 18:46:09 -0700 | [diff] [blame] | 126 | void handle_deleter::operator()(HANDLE h) { |
| 127 | // CreateFile() is documented to return INVALID_HANDLE_FILE on error, |
| 128 | // implying that NULL is a valid handle, but this is probably impossible. |
| 129 | // Other APIs like CreateEvent() are documented to return NULL on error, |
| 130 | // implying that INVALID_HANDLE_VALUE is a valid handle, but this is also |
| 131 | // probably impossible. Thus, consider both NULL and INVALID_HANDLE_VALUE |
| 132 | // as invalid handles. std::unique_ptr won't call a deleter with NULL, so we |
| 133 | // only need to check for INVALID_HANDLE_VALUE. |
| 134 | if (h != INVALID_HANDLE_VALUE) { |
| 135 | if (!CloseHandle(h)) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 136 | D("CloseHandle(%p) failed: %s", h, |
Spencer Low | 2bbb3a9 | 2015-08-26 18:46:09 -0700 | [diff] [blame] | 137 | SystemErrorCodeToString(GetLastError()).c_str()); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 142 | /**************************************************************************/ |
| 143 | /**************************************************************************/ |
| 144 | /***** *****/ |
| 145 | /***** replaces libs/cutils/load_file.c *****/ |
| 146 | /***** *****/ |
| 147 | /**************************************************************************/ |
| 148 | /**************************************************************************/ |
| 149 | |
| 150 | void *load_file(const char *fn, unsigned *_sz) |
| 151 | { |
| 152 | HANDLE file; |
| 153 | char *data; |
| 154 | DWORD file_size; |
| 155 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 156 | std::wstring fn_wide; |
| 157 | if (!android::base::UTF8ToWide(fn, &fn_wide)) |
| 158 | return NULL; |
| 159 | |
| 160 | file = CreateFileW( fn_wide.c_str(), |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 161 | GENERIC_READ, |
| 162 | FILE_SHARE_READ, |
| 163 | NULL, |
| 164 | OPEN_EXISTING, |
| 165 | 0, |
| 166 | NULL ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 167 | |
| 168 | if (file == INVALID_HANDLE_VALUE) |
| 169 | return NULL; |
| 170 | |
| 171 | file_size = GetFileSize( file, NULL ); |
| 172 | data = NULL; |
| 173 | |
| 174 | if (file_size > 0) { |
| 175 | data = (char*) malloc( file_size + 1 ); |
| 176 | if (data == NULL) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 177 | 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] | 178 | file_size = 0; |
| 179 | } else { |
| 180 | DWORD out_bytes; |
| 181 | |
| 182 | if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) || |
| 183 | out_bytes != file_size ) |
| 184 | { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 185 | 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] | 186 | free(data); |
| 187 | data = NULL; |
| 188 | file_size = 0; |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | CloseHandle( file ); |
| 193 | |
| 194 | *_sz = (unsigned) file_size; |
| 195 | return data; |
| 196 | } |
| 197 | |
| 198 | /**************************************************************************/ |
| 199 | /**************************************************************************/ |
| 200 | /***** *****/ |
| 201 | /***** common file descriptor handling *****/ |
| 202 | /***** *****/ |
| 203 | /**************************************************************************/ |
| 204 | /**************************************************************************/ |
| 205 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 206 | /* used to emulate unix-domain socket pairs */ |
| 207 | typedef struct SocketPairRec_* SocketPair; |
| 208 | |
| 209 | typedef struct FHRec_ |
| 210 | { |
| 211 | FHClass clazz; |
| 212 | int used; |
| 213 | int eof; |
| 214 | union { |
| 215 | HANDLE handle; |
| 216 | SOCKET socket; |
| 217 | SocketPair pair; |
| 218 | } u; |
| 219 | |
| 220 | HANDLE event; |
| 221 | int mask; |
| 222 | |
| 223 | char name[32]; |
| 224 | |
| 225 | } FHRec; |
| 226 | |
| 227 | #define fh_handle u.handle |
| 228 | #define fh_socket u.socket |
| 229 | #define fh_pair u.pair |
| 230 | |
| 231 | #define WIN32_FH_BASE 100 |
| 232 | |
| 233 | #define WIN32_MAX_FHS 128 |
| 234 | |
| 235 | static adb_mutex_t _win32_lock; |
| 236 | static FHRec _win32_fhs[ WIN32_MAX_FHS ]; |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 237 | 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] | 238 | |
| 239 | static FH |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 240 | _fh_from_int( int fd, const char* func ) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 241 | { |
| 242 | FH f; |
| 243 | |
| 244 | fd -= WIN32_FH_BASE; |
| 245 | |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 246 | if (fd < 0 || fd >= WIN32_MAX_FHS) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 247 | 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] | 248 | func ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 249 | errno = EBADF; |
| 250 | return NULL; |
| 251 | } |
| 252 | |
| 253 | f = &_win32_fhs[fd]; |
| 254 | |
| 255 | if (f->used == 0) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 256 | 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] | 257 | func ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 258 | errno = EBADF; |
| 259 | return NULL; |
| 260 | } |
| 261 | |
| 262 | return f; |
| 263 | } |
| 264 | |
| 265 | |
| 266 | static int |
| 267 | _fh_to_int( FH f ) |
| 268 | { |
| 269 | if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS) |
| 270 | return (int)(f - _win32_fhs) + WIN32_FH_BASE; |
| 271 | |
| 272 | return -1; |
| 273 | } |
| 274 | |
| 275 | static FH |
| 276 | _fh_alloc( FHClass clazz ) |
| 277 | { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 278 | FH f = NULL; |
| 279 | |
| 280 | adb_mutex_lock( &_win32_lock ); |
| 281 | |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 282 | // Search entire array, starting from _win32_fh_next. |
| 283 | for (int nn = 0; nn < WIN32_MAX_FHS; nn++) { |
| 284 | // Keep incrementing _win32_fh_next to avoid giving out an index that |
| 285 | // was recently closed, to try to avoid use-after-free. |
| 286 | const int index = _win32_fh_next++; |
| 287 | // Handle wrap-around of _win32_fh_next. |
| 288 | if (_win32_fh_next == WIN32_MAX_FHS) { |
| 289 | _win32_fh_next = 0; |
| 290 | } |
| 291 | if (_win32_fhs[index].clazz == NULL) { |
| 292 | f = &_win32_fhs[index]; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 293 | goto Exit; |
| 294 | } |
| 295 | } |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 296 | D( "_fh_alloc: no more free file descriptors" ); |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 297 | errno = EMFILE; // Too many open files |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 298 | Exit: |
| 299 | if (f) { |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 300 | f->clazz = clazz; |
| 301 | f->used = 1; |
| 302 | f->eof = 0; |
| 303 | f->name[0] = '\0'; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 304 | clazz->_fh_init(f); |
| 305 | } |
| 306 | adb_mutex_unlock( &_win32_lock ); |
| 307 | return f; |
| 308 | } |
| 309 | |
| 310 | |
| 311 | static int |
| 312 | _fh_close( FH f ) |
| 313 | { |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 314 | // Use lock so that closing only happens once and so that _fh_alloc can't |
| 315 | // allocate a FH that we're in the middle of closing. |
| 316 | adb_mutex_lock(&_win32_lock); |
| 317 | if (f->used) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 318 | f->clazz->_fh_close( f ); |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 319 | f->name[0] = '\0'; |
| 320 | f->eof = 0; |
| 321 | f->used = 0; |
| 322 | f->clazz = NULL; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 323 | } |
Spencer Low | b732a37 | 2015-07-24 15:38:19 -0700 | [diff] [blame] | 324 | adb_mutex_unlock(&_win32_lock); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 325 | return 0; |
| 326 | } |
| 327 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 328 | // Deleter for unique_fh. |
| 329 | class fh_deleter { |
| 330 | public: |
| 331 | void operator()(struct FHRec_* fh) { |
| 332 | // We're called from a destructor and destructors should not overwrite |
| 333 | // errno because callers may do: |
| 334 | // errno = EBLAH; |
| 335 | // return -1; // calls destructor, which should not overwrite errno |
| 336 | const int saved_errno = errno; |
| 337 | _fh_close(fh); |
| 338 | errno = saved_errno; |
| 339 | } |
| 340 | }; |
| 341 | |
| 342 | // Like std::unique_ptr, but calls _fh_close() instead of operator delete(). |
| 343 | typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh; |
| 344 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 345 | /**************************************************************************/ |
| 346 | /**************************************************************************/ |
| 347 | /***** *****/ |
| 348 | /***** file-based descriptor handling *****/ |
| 349 | /***** *****/ |
| 350 | /**************************************************************************/ |
| 351 | /**************************************************************************/ |
| 352 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 353 | static void _fh_file_init( FH f ) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 354 | f->fh_handle = INVALID_HANDLE_VALUE; |
| 355 | } |
| 356 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 357 | static int _fh_file_close( FH f ) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 358 | CloseHandle( f->fh_handle ); |
| 359 | f->fh_handle = INVALID_HANDLE_VALUE; |
| 360 | return 0; |
| 361 | } |
| 362 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 363 | 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] | 364 | DWORD read_bytes; |
| 365 | |
| 366 | if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 367 | 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] | 368 | errno = EIO; |
| 369 | return -1; |
| 370 | } else if (read_bytes < (DWORD)len) { |
| 371 | f->eof = 1; |
| 372 | } |
| 373 | return (int)read_bytes; |
| 374 | } |
| 375 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 376 | 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] | 377 | DWORD wrote_bytes; |
| 378 | |
| 379 | if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 380 | 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] | 381 | errno = EIO; |
| 382 | return -1; |
| 383 | } else if (wrote_bytes < (DWORD)len) { |
| 384 | f->eof = 1; |
| 385 | } |
| 386 | return (int)wrote_bytes; |
| 387 | } |
| 388 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 389 | 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] | 390 | DWORD method; |
| 391 | DWORD result; |
| 392 | |
| 393 | switch (origin) |
| 394 | { |
| 395 | case SEEK_SET: method = FILE_BEGIN; break; |
| 396 | case SEEK_CUR: method = FILE_CURRENT; break; |
| 397 | case SEEK_END: method = FILE_END; break; |
| 398 | default: |
| 399 | errno = EINVAL; |
| 400 | return -1; |
| 401 | } |
| 402 | |
| 403 | result = SetFilePointer( f->fh_handle, pos, NULL, method ); |
| 404 | if (result == INVALID_SET_FILE_POINTER) { |
| 405 | errno = EIO; |
| 406 | return -1; |
| 407 | } else { |
| 408 | f->eof = 0; |
| 409 | } |
| 410 | return (int)result; |
| 411 | } |
| 412 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 413 | |
| 414 | /**************************************************************************/ |
| 415 | /**************************************************************************/ |
| 416 | /***** *****/ |
| 417 | /***** file-based descriptor handling *****/ |
| 418 | /***** *****/ |
| 419 | /**************************************************************************/ |
| 420 | /**************************************************************************/ |
| 421 | |
| 422 | int adb_open(const char* path, int options) |
| 423 | { |
| 424 | FH f; |
| 425 | |
| 426 | DWORD desiredAccess = 0; |
| 427 | DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; |
| 428 | |
| 429 | switch (options) { |
| 430 | case O_RDONLY: |
| 431 | desiredAccess = GENERIC_READ; |
| 432 | break; |
| 433 | case O_WRONLY: |
| 434 | desiredAccess = GENERIC_WRITE; |
| 435 | break; |
| 436 | case O_RDWR: |
| 437 | desiredAccess = GENERIC_READ | GENERIC_WRITE; |
| 438 | break; |
| 439 | default: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 440 | D("adb_open: invalid options (0x%0x)", options); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 441 | errno = EINVAL; |
| 442 | return -1; |
| 443 | } |
| 444 | |
| 445 | f = _fh_alloc( &_fh_file_class ); |
| 446 | if ( !f ) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 447 | return -1; |
| 448 | } |
| 449 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 450 | std::wstring path_wide; |
| 451 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 452 | return -1; |
| 453 | } |
| 454 | f->fh_handle = CreateFileW( path_wide.c_str(), desiredAccess, shareMode, |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 455 | NULL, OPEN_EXISTING, 0, NULL ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 456 | |
| 457 | if ( f->fh_handle == INVALID_HANDLE_VALUE ) { |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 458 | const DWORD err = GetLastError(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 459 | _fh_close(f); |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 460 | D( "adb_open: could not open '%s': ", path ); |
| 461 | switch (err) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 462 | case ERROR_FILE_NOT_FOUND: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 463 | D( "file not found" ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 464 | errno = ENOENT; |
| 465 | return -1; |
| 466 | |
| 467 | case ERROR_PATH_NOT_FOUND: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 468 | D( "path not found" ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 469 | errno = ENOTDIR; |
| 470 | return -1; |
| 471 | |
| 472 | default: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 473 | D( "unknown error: %s", |
Spencer Low | 1711e01 | 2015-08-02 18:50:17 -0700 | [diff] [blame] | 474 | SystemErrorCodeToString( err ).c_str() ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 475 | errno = ENOENT; |
| 476 | return -1; |
| 477 | } |
| 478 | } |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 479 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 480 | 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] | 481 | 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] | 482 | return _fh_to_int(f); |
| 483 | } |
| 484 | |
| 485 | /* ignore mode on Win32 */ |
| 486 | int adb_creat(const char* path, int mode) |
| 487 | { |
| 488 | FH f; |
| 489 | |
| 490 | f = _fh_alloc( &_fh_file_class ); |
| 491 | if ( !f ) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 492 | return -1; |
| 493 | } |
| 494 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 495 | std::wstring path_wide; |
| 496 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 497 | return -1; |
| 498 | } |
| 499 | f->fh_handle = CreateFileW( path_wide.c_str(), GENERIC_WRITE, |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 500 | FILE_SHARE_READ | FILE_SHARE_WRITE, |
| 501 | NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, |
| 502 | NULL ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 503 | |
| 504 | if ( f->fh_handle == INVALID_HANDLE_VALUE ) { |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 505 | const DWORD err = GetLastError(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 506 | _fh_close(f); |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 507 | D( "adb_creat: could not open '%s': ", path ); |
| 508 | switch (err) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 509 | case ERROR_FILE_NOT_FOUND: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 510 | D( "file not found" ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 511 | errno = ENOENT; |
| 512 | return -1; |
| 513 | |
| 514 | case ERROR_PATH_NOT_FOUND: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 515 | D( "path not found" ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 516 | errno = ENOTDIR; |
| 517 | return -1; |
| 518 | |
| 519 | default: |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 520 | D( "unknown error: %s", |
Spencer Low | 1711e01 | 2015-08-02 18:50:17 -0700 | [diff] [blame] | 521 | SystemErrorCodeToString( err ).c_str() ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 522 | errno = ENOENT; |
| 523 | return -1; |
| 524 | } |
| 525 | } |
| 526 | 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] | 527 | 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] | 528 | return _fh_to_int(f); |
| 529 | } |
| 530 | |
| 531 | |
| 532 | int adb_read(int fd, void* buf, int len) |
| 533 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 534 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 535 | |
| 536 | if (f == NULL) { |
| 537 | return -1; |
| 538 | } |
| 539 | |
| 540 | return f->clazz->_fh_read( f, buf, len ); |
| 541 | } |
| 542 | |
| 543 | |
| 544 | int adb_write(int fd, const void* buf, int len) |
| 545 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 546 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 547 | |
| 548 | if (f == NULL) { |
| 549 | return -1; |
| 550 | } |
| 551 | |
| 552 | return f->clazz->_fh_write(f, buf, len); |
| 553 | } |
| 554 | |
| 555 | |
| 556 | int adb_lseek(int fd, int pos, int where) |
| 557 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 558 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 559 | |
| 560 | if (!f) { |
| 561 | return -1; |
| 562 | } |
| 563 | |
| 564 | return f->clazz->_fh_lseek(f, pos, where); |
| 565 | } |
| 566 | |
| 567 | |
| 568 | int adb_close(int fd) |
| 569 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 570 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 571 | |
| 572 | if (!f) { |
| 573 | return -1; |
| 574 | } |
| 575 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 576 | D( "adb_close: %s", f->name); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 577 | _fh_close(f); |
| 578 | return 0; |
| 579 | } |
| 580 | |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 581 | // Overrides strerror() to handle error codes not supported by the Windows C |
| 582 | // Runtime (MSVCRT.DLL). |
| 583 | char* adb_strerror(int err) { |
| 584 | // sysdeps.h defines strerror to adb_strerror, but in this function, we |
| 585 | // want to call the real C Runtime strerror(). |
| 586 | #pragma push_macro("strerror") |
| 587 | #undef strerror |
| 588 | const int saved_err = errno; // Save because we overwrite it later. |
| 589 | |
| 590 | // Lookup the string for an unknown error. |
| 591 | char* errmsg = strerror(-1); |
Elliott Hughes | 6c73bfc | 2015-10-27 13:40:35 -0700 | [diff] [blame] | 592 | const std::string unknown_error = (errmsg == nullptr) ? "" : errmsg; |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 593 | |
| 594 | // Lookup the string for this error to see if the C Runtime has it. |
| 595 | errmsg = strerror(err); |
Elliott Hughes | 6c73bfc | 2015-10-27 13:40:35 -0700 | [diff] [blame] | 596 | if (errmsg != nullptr && unknown_error != errmsg) { |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 597 | // The CRT returned an error message and it is different than the error |
| 598 | // message for an unknown error, so it is probably valid, so use it. |
| 599 | } else { |
| 600 | // Check if we have a string for this error code. |
| 601 | const char* custom_msg = nullptr; |
| 602 | switch (err) { |
| 603 | #pragma push_macro("ERR") |
| 604 | #undef ERR |
| 605 | #define ERR(errnum, desc) case errnum: custom_msg = desc; break |
| 606 | // These error strings are from AOSP bionic/libc/include/sys/_errdefs.h. |
| 607 | // Note that these cannot be longer than 94 characters because we |
| 608 | // pass this to _strerror() which has that requirement. |
| 609 | ERR(ECONNRESET, "Connection reset by peer"); |
| 610 | ERR(EHOSTUNREACH, "No route to host"); |
| 611 | ERR(ENETDOWN, "Network is down"); |
| 612 | ERR(ENETRESET, "Network dropped connection because of reset"); |
| 613 | ERR(ENOBUFS, "No buffer space available"); |
| 614 | ERR(ENOPROTOOPT, "Protocol not available"); |
| 615 | ERR(ENOTCONN, "Transport endpoint is not connected"); |
| 616 | ERR(ENOTSOCK, "Socket operation on non-socket"); |
| 617 | ERR(EOPNOTSUPP, "Operation not supported on transport endpoint"); |
| 618 | #pragma pop_macro("ERR") |
| 619 | } |
| 620 | |
| 621 | if (custom_msg != nullptr) { |
| 622 | // Use _strerror() to write our string into the writable per-thread |
| 623 | // buffer used by strerror()/_strerror(). _strerror() appends the |
| 624 | // msg for the current value of errno, so set errno to a consistent |
| 625 | // value for every call so that our code-path is always the same. |
| 626 | errno = 0; |
| 627 | errmsg = _strerror(custom_msg); |
| 628 | const size_t custom_msg_len = strlen(custom_msg); |
| 629 | // Just in case _strerror() returned a read-only string, check if |
| 630 | // the returned string starts with our custom message because that |
| 631 | // implies that the string is not read-only. |
| 632 | if ((errmsg != nullptr) && |
| 633 | !strncmp(custom_msg, errmsg, custom_msg_len)) { |
| 634 | // _strerror() puts other text after our custom message, so |
| 635 | // remove that by terminating after our message. |
| 636 | errmsg[custom_msg_len] = '\0'; |
| 637 | } else { |
| 638 | // For some reason nullptr was returned or a pointer to a |
| 639 | // read-only string was returned, so fallback to whatever |
| 640 | // strerror() can muster (probably "Unknown error" or some |
| 641 | // generic CRT error string). |
| 642 | errmsg = strerror(err); |
| 643 | } |
| 644 | } else { |
| 645 | // We don't have a custom message, so use whatever strerror(err) |
| 646 | // returned earlier. |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | errno = saved_err; // restore |
| 651 | |
| 652 | return errmsg; |
| 653 | #pragma pop_macro("strerror") |
| 654 | } |
| 655 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 656 | /**************************************************************************/ |
| 657 | /**************************************************************************/ |
| 658 | /***** *****/ |
| 659 | /***** socket-based file descriptors *****/ |
| 660 | /***** *****/ |
| 661 | /**************************************************************************/ |
| 662 | /**************************************************************************/ |
| 663 | |
Spencer Low | 31aafa6 | 2015-01-25 14:40:16 -0800 | [diff] [blame] | 664 | #undef setsockopt |
| 665 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 666 | static void _socket_set_errno( const DWORD err ) { |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 667 | // Because the Windows C Runtime (MSVCRT.DLL) strerror() does not support a |
| 668 | // lot of POSIX and socket error codes, some of the resulting error codes |
| 669 | // are mapped to strings by adb_strerror() above. |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 670 | switch ( err ) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 671 | case 0: errno = 0; break; |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 672 | // Don't map WSAEINTR since that is only for Winsock 1.1 which we don't use. |
| 673 | // case WSAEINTR: errno = EINTR; break; |
| 674 | case WSAEFAULT: errno = EFAULT; break; |
| 675 | case WSAEINVAL: errno = EINVAL; break; |
| 676 | case WSAEMFILE: errno = EMFILE; break; |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 677 | // Mapping WSAEWOULDBLOCK to EAGAIN is absolutely critical because |
| 678 | // non-blocking sockets can cause an error code of WSAEWOULDBLOCK and |
| 679 | // callers check specifically for EAGAIN. |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 680 | case WSAEWOULDBLOCK: errno = EAGAIN; break; |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 681 | case WSAENOTSOCK: errno = ENOTSOCK; break; |
| 682 | case WSAENOPROTOOPT: errno = ENOPROTOOPT; break; |
| 683 | case WSAEOPNOTSUPP: errno = EOPNOTSUPP; break; |
| 684 | case WSAENETDOWN: errno = ENETDOWN; break; |
| 685 | case WSAENETRESET: errno = ENETRESET; break; |
| 686 | // Map WSAECONNABORTED to EPIPE instead of ECONNABORTED because POSIX seems |
| 687 | // to use EPIPE for these situations and there are some callers that look |
| 688 | // for EPIPE. |
| 689 | case WSAECONNABORTED: errno = EPIPE; break; |
| 690 | case WSAECONNRESET: errno = ECONNRESET; break; |
| 691 | case WSAENOBUFS: errno = ENOBUFS; break; |
| 692 | case WSAENOTCONN: errno = ENOTCONN; break; |
| 693 | // Don't map WSAETIMEDOUT because we don't currently use SO_RCVTIMEO or |
| 694 | // SO_SNDTIMEO which would cause WSAETIMEDOUT to be returned. Future |
| 695 | // considerations: Reportedly send() can return zero on timeout, and POSIX |
| 696 | // code may expect EAGAIN instead of ETIMEDOUT on timeout. |
| 697 | // case WSAETIMEDOUT: errno = ETIMEDOUT; break; |
| 698 | case WSAEHOSTUNREACH: errno = EHOSTUNREACH; break; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 699 | default: |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 700 | errno = EINVAL; |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 701 | D( "_socket_set_errno: mapping Windows error code %lu to errno %d", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 702 | err, errno ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 703 | } |
| 704 | } |
| 705 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 706 | static void _fh_socket_init( FH f ) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 707 | f->fh_socket = INVALID_SOCKET; |
| 708 | f->event = WSACreateEvent(); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 709 | if (f->event == WSA_INVALID_EVENT) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 710 | D("WSACreateEvent failed: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 711 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
| 712 | |
| 713 | // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE |
| 714 | // on failure, instead of NULL which is what Windows really returns on |
| 715 | // error. It might be better to change all the other code to look for |
| 716 | // NULL, but that is a much riskier change. |
| 717 | f->event = INVALID_HANDLE_VALUE; |
| 718 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 719 | f->mask = 0; |
| 720 | } |
| 721 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 722 | static int _fh_socket_close( FH f ) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 723 | if (f->fh_socket != INVALID_SOCKET) { |
| 724 | /* gently tell any peer that we're closing the socket */ |
| 725 | if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) { |
| 726 | // If the socket is not connected, this returns an error. We want to |
| 727 | // minimize logging spam, so don't log these errors for now. |
| 728 | #if 0 |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 729 | D("socket shutdown failed: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 730 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
| 731 | #endif |
| 732 | } |
| 733 | if (closesocket(f->fh_socket) == SOCKET_ERROR) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 734 | D("closesocket failed: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 735 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
| 736 | } |
| 737 | f->fh_socket = INVALID_SOCKET; |
| 738 | } |
| 739 | if (f->event != NULL) { |
| 740 | if (!CloseHandle(f->event)) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 741 | D("CloseHandle failed: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 742 | SystemErrorCodeToString(GetLastError()).c_str()); |
| 743 | } |
| 744 | f->event = NULL; |
| 745 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 746 | f->mask = 0; |
| 747 | return 0; |
| 748 | } |
| 749 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 750 | 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] | 751 | errno = EPIPE; |
| 752 | return -1; |
| 753 | } |
| 754 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 755 | static int _fh_socket_read(FH f, void* buf, int len) { |
| 756 | 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] | 757 | if (result == SOCKET_ERROR) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 758 | const DWORD err = WSAGetLastError(); |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 759 | // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace |
| 760 | // that to reduce spam and confusion. |
| 761 | if (err != WSAEWOULDBLOCK) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 762 | D("recv fd %d failed: %s", _fh_to_int(f), |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 763 | SystemErrorCodeToString(err).c_str()); |
| 764 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 765 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 766 | result = -1; |
| 767 | } |
| 768 | return result; |
| 769 | } |
| 770 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 771 | static int _fh_socket_write(FH f, const void* buf, int len) { |
| 772 | 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] | 773 | if (result == SOCKET_ERROR) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 774 | const DWORD err = WSAGetLastError(); |
Spencer Low | 028e159 | 2015-10-18 16:45:09 -0700 | [diff] [blame] | 775 | // WSAEWOULDBLOCK is normal with a non-blocking socket, so don't trace |
| 776 | // that to reduce spam and confusion. |
| 777 | if (err != WSAEWOULDBLOCK) { |
| 778 | D("send fd %d failed: %s", _fh_to_int(f), |
| 779 | SystemErrorCodeToString(err).c_str()); |
| 780 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 781 | _socket_set_errno(err); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 782 | result = -1; |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 783 | } else { |
| 784 | // According to https://code.google.com/p/chromium/issues/detail?id=27870 |
| 785 | // Winsock Layered Service Providers may cause this. |
| 786 | CHECK_LE(result, len) << "Tried to write " << len << " bytes to " |
| 787 | << f->name << ", but " << result |
| 788 | << " bytes reportedly written"; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 789 | } |
| 790 | return result; |
| 791 | } |
| 792 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 793 | /**************************************************************************/ |
| 794 | /**************************************************************************/ |
| 795 | /***** *****/ |
| 796 | /***** replacement for libs/cutils/socket_xxxx.c *****/ |
| 797 | /***** *****/ |
| 798 | /**************************************************************************/ |
| 799 | /**************************************************************************/ |
| 800 | |
| 801 | #include <winsock2.h> |
| 802 | |
| 803 | static int _winsock_init; |
| 804 | |
| 805 | static void |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 806 | _init_winsock( void ) |
| 807 | { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 808 | // TODO: Multiple threads calling this may potentially cause multiple calls |
Spencer Low | c7c1ca6 | 2015-08-12 18:19:16 -0700 | [diff] [blame] | 809 | // to WSAStartup() which offers no real benefit. |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 810 | if (!_winsock_init) { |
| 811 | WSADATA wsaData; |
| 812 | int rc = WSAStartup( MAKEWORD(2,2), &wsaData); |
| 813 | if (rc != 0) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 814 | fatal( "adb: could not initialize Winsock: %s", |
| 815 | SystemErrorCodeToString( rc ).c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 816 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 817 | _winsock_init = 1; |
Spencer Low | c7c1ca6 | 2015-08-12 18:19:16 -0700 | [diff] [blame] | 818 | |
| 819 | // Note that we do not call atexit() to register WSACleanup to be called |
| 820 | // at normal process termination because: |
| 821 | // 1) When exit() is called, there are still threads actively using |
| 822 | // Winsock because we don't cleanly shutdown all threads, so it |
| 823 | // doesn't make sense to call WSACleanup() and may cause problems |
| 824 | // with those threads. |
| 825 | // 2) A deadlock can occur when exit() holds a C Runtime lock, then it |
| 826 | // calls WSACleanup() which tries to unload a DLL, which tries to |
| 827 | // grab the LoaderLock. This conflicts with the device_poll_thread |
| 828 | // which holds the LoaderLock because AdbWinApi.dll calls |
| 829 | // setupapi.dll which tries to load wintrust.dll which tries to load |
| 830 | // crypt32.dll which calls atexit() which tries to acquire the C |
| 831 | // Runtime lock that the other thread holds. |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 832 | } |
| 833 | } |
| 834 | |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 835 | // Map a socket type to an explicit socket protocol instead of using the socket |
| 836 | // protocol of 0. Explicit socket protocols are used by most apps and we should |
| 837 | // do the same to reduce the chance of exercising uncommon code-paths that might |
| 838 | // have problems or that might load different Winsock service providers that |
| 839 | // have problems. |
| 840 | static int GetSocketProtocolFromSocketType(int type) { |
| 841 | switch (type) { |
| 842 | case SOCK_STREAM: |
| 843 | return IPPROTO_TCP; |
| 844 | case SOCK_DGRAM: |
| 845 | return IPPROTO_UDP; |
| 846 | default: |
| 847 | LOG(FATAL) << "Unknown socket type: " << type; |
| 848 | return 0; |
| 849 | } |
| 850 | } |
| 851 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 852 | 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] | 853 | struct sockaddr_in addr; |
| 854 | SOCKET s; |
| 855 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 856 | unique_fh f(_fh_alloc(&_fh_socket_class)); |
| 857 | if (!f) { |
| 858 | *error = strerror(errno); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 859 | return -1; |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 860 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 861 | |
| 862 | if (!_winsock_init) |
| 863 | _init_winsock(); |
| 864 | |
| 865 | memset(&addr, 0, sizeof(addr)); |
| 866 | addr.sin_family = AF_INET; |
| 867 | addr.sin_port = htons(port); |
| 868 | addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); |
| 869 | |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 870 | s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type)); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 871 | if(s == INVALID_SOCKET) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 872 | *error = android::base::StringPrintf("cannot create socket: %s", |
| 873 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 874 | D("%s", error->c_str()); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 875 | return -1; |
| 876 | } |
| 877 | f->fh_socket = s; |
| 878 | |
| 879 | if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 880 | // Save err just in case inet_ntoa() or ntohs() changes the last error. |
| 881 | const DWORD err = WSAGetLastError(); |
| 882 | *error = android::base::StringPrintf("cannot connect to %s:%u: %s", |
| 883 | inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), |
| 884 | SystemErrorCodeToString(err).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 885 | D("could not connect to %s:%d: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 886 | type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 887 | return -1; |
| 888 | } |
| 889 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 890 | const int fd = _fh_to_int(f.get()); |
| 891 | snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd, |
| 892 | type != SOCK_STREAM ? "udp:" : "", port ); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 893 | 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] | 894 | fd ); |
| 895 | f.release(); |
| 896 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 897 | } |
| 898 | |
| 899 | #define LISTEN_BACKLOG 4 |
| 900 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 901 | // interface_address is INADDR_LOOPBACK or INADDR_ANY. |
| 902 | static int _network_server(int port, int type, u_long interface_address, |
| 903 | std::string* error) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 904 | struct sockaddr_in addr; |
| 905 | SOCKET s; |
| 906 | int n; |
| 907 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 908 | unique_fh f(_fh_alloc(&_fh_socket_class)); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 909 | if (!f) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 910 | *error = strerror(errno); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 911 | return -1; |
| 912 | } |
| 913 | |
| 914 | if (!_winsock_init) |
| 915 | _init_winsock(); |
| 916 | |
| 917 | memset(&addr, 0, sizeof(addr)); |
| 918 | addr.sin_family = AF_INET; |
| 919 | addr.sin_port = htons(port); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 920 | addr.sin_addr.s_addr = htonl(interface_address); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 921 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 922 | // TODO: Consider using dual-stack socket that can simultaneously listen on |
| 923 | // IPv4 and IPv6. |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 924 | s = socket(AF_INET, type, GetSocketProtocolFromSocketType(type)); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 925 | if (s == INVALID_SOCKET) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 926 | *error = android::base::StringPrintf("cannot create socket: %s", |
| 927 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 928 | D("%s", error->c_str()); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 929 | return -1; |
| 930 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 931 | |
| 932 | f->fh_socket = s; |
| 933 | |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 934 | // Note: SO_REUSEADDR on Windows allows multiple processes to bind to the |
| 935 | // same port, so instead use SO_EXCLUSIVEADDRUSE. |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 936 | n = 1; |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 937 | if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n, |
| 938 | sizeof(n)) == SOCKET_ERROR) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 939 | *error = android::base::StringPrintf( |
| 940 | "cannot set socket option SO_EXCLUSIVEADDRUSE: %s", |
| 941 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 942 | D("%s", error->c_str()); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 943 | return -1; |
| 944 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 945 | |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 946 | if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) { |
| 947 | // Save err just in case inet_ntoa() or ntohs() changes the last error. |
| 948 | const DWORD err = WSAGetLastError(); |
| 949 | *error = android::base::StringPrintf("cannot bind to %s:%u: %s", |
| 950 | inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), |
| 951 | SystemErrorCodeToString(err).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 952 | D("could not bind to %s:%d: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 953 | type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 954 | return -1; |
| 955 | } |
| 956 | if (type == SOCK_STREAM) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 957 | if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 958 | *error = android::base::StringPrintf("cannot listen on socket: %s", |
| 959 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 960 | D("could not listen on %s:%d: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 961 | type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 962 | return -1; |
| 963 | } |
| 964 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 965 | const int fd = _fh_to_int(f.get()); |
| 966 | snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd, |
| 967 | interface_address == INADDR_LOOPBACK ? "lo" : "any", |
| 968 | type != SOCK_STREAM ? "udp:" : "", port ); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 969 | 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] | 970 | fd ); |
| 971 | f.release(); |
| 972 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 973 | } |
| 974 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 975 | int network_loopback_server(int port, int type, std::string* error) { |
| 976 | return _network_server(port, type, INADDR_LOOPBACK, error); |
| 977 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 978 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 979 | int network_inaddr_any_server(int port, int type, std::string* error) { |
| 980 | return _network_server(port, type, INADDR_ANY, error); |
| 981 | } |
| 982 | |
| 983 | int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) { |
| 984 | unique_fh f(_fh_alloc(&_fh_socket_class)); |
| 985 | if (!f) { |
| 986 | *error = strerror(errno); |
| 987 | return -1; |
| 988 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 989 | |
Elliott Hughes | 43df109 | 2015-07-23 17:12:58 -0700 | [diff] [blame] | 990 | if (!_winsock_init) _init_winsock(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 991 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 992 | struct addrinfo hints; |
| 993 | memset(&hints, 0, sizeof(hints)); |
| 994 | hints.ai_family = AF_UNSPEC; |
| 995 | hints.ai_socktype = type; |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 996 | hints.ai_protocol = GetSocketProtocolFromSocketType(type); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 997 | |
| 998 | char port_str[16]; |
| 999 | snprintf(port_str, sizeof(port_str), "%d", port); |
| 1000 | |
| 1001 | struct addrinfo* addrinfo_ptr = nullptr; |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 1002 | |
| 1003 | #if (NTDDI_VERSION >= NTDDI_WINXPSP2) || (_WIN32_WINNT >= _WIN32_WINNT_WS03) |
| 1004 | // TODO: When the Android SDK tools increases the Windows system |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 1005 | // requirements >= WinXP SP2, switch to android::base::UTF8ToWide() + GetAddrInfoW(). |
Spencer Low | cc467f1 | 2015-08-02 18:13:54 -0700 | [diff] [blame] | 1006 | #else |
| 1007 | // Otherwise, keep using getaddrinfo(), or do runtime API detection |
| 1008 | // with GetProcAddress("GetAddrInfoW"). |
| 1009 | #endif |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1010 | if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 1011 | *error = android::base::StringPrintf( |
| 1012 | "cannot resolve host '%s' and port %s: %s", host.c_str(), |
| 1013 | port_str, SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1014 | D("%s", error->c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1015 | return -1; |
| 1016 | } |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1017 | std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*> |
| 1018 | addrinfo(addrinfo_ptr, freeaddrinfo); |
| 1019 | addrinfo_ptr = nullptr; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1020 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1021 | // TODO: Try all the addresses if there's more than one? This just uses |
| 1022 | // the first. Or, could call WSAConnectByName() (Windows Vista and newer) |
| 1023 | // which tries all addresses, takes a timeout and more. |
| 1024 | SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype, |
| 1025 | addrinfo->ai_protocol); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1026 | if(s == INVALID_SOCKET) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 1027 | *error = android::base::StringPrintf("cannot create socket: %s", |
| 1028 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1029 | D("%s", error->c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1030 | return -1; |
| 1031 | } |
| 1032 | f->fh_socket = s; |
| 1033 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1034 | // TODO: Implement timeouts for Windows. Seems like the default in theory |
| 1035 | // (according to http://serverfault.com/a/671453) and in practice is 21 sec. |
| 1036 | if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) { |
Spencer Low | 3262585 | 2015-08-11 16:45:32 -0700 | [diff] [blame] | 1037 | // TODO: Use WSAAddressToString or inet_ntop on address. |
| 1038 | *error = android::base::StringPrintf("cannot connect to %s:%s: %s", |
| 1039 | host.c_str(), port_str, |
| 1040 | SystemErrorCodeToString(WSAGetLastError()).c_str()); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1041 | D("could not connect to %s:%s:%s: %s", |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1042 | type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str, |
| 1043 | error->c_str()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1044 | return -1; |
| 1045 | } |
| 1046 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1047 | const int fd = _fh_to_int(f.get()); |
| 1048 | snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd, |
| 1049 | type != SOCK_STREAM ? "udp:" : "", port ); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1050 | 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] | 1051 | type != SOCK_STREAM ? "udp" : "tcp", fd ); |
| 1052 | f.release(); |
| 1053 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1054 | } |
| 1055 | |
| 1056 | #undef accept |
| 1057 | int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen) |
| 1058 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 1059 | FH serverfh = _fh_from_int(serverfd, __func__); |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 1060 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1061 | if ( !serverfh || serverfh->clazz != &_fh_socket_class ) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1062 | D("adb_socket_accept: invalid fd %d", serverfd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1063 | errno = EBADF; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1064 | return -1; |
| 1065 | } |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 1066 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1067 | unique_fh fh(_fh_alloc( &_fh_socket_class )); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1068 | if (!fh) { |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1069 | PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket " |
| 1070 | "descriptor"; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1071 | return -1; |
| 1072 | } |
| 1073 | |
| 1074 | fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen ); |
| 1075 | if (fh->fh_socket == INVALID_SOCKET) { |
Spencer Low | 5c761bd | 2015-07-21 02:06:26 -0700 | [diff] [blame] | 1076 | const DWORD err = WSAGetLastError(); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1077 | LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd << |
| 1078 | " failed: " + SystemErrorCodeToString(err); |
| 1079 | _socket_set_errno( err ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1080 | return -1; |
| 1081 | } |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 1082 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1083 | const int fd = _fh_to_int(fh.get()); |
| 1084 | snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name ); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1085 | D( "adb_socket_accept on fd %d returns fd %d", serverfd, fd ); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1086 | fh.release(); |
| 1087 | return fd; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1088 | } |
| 1089 | |
| 1090 | |
Spencer Low | 31aafa6 | 2015-01-25 14:40:16 -0800 | [diff] [blame] | 1091 | 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] | 1092 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 1093 | FH fh = _fh_from_int(fd, __func__); |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 1094 | |
Spencer Low | 31aafa6 | 2015-01-25 14:40:16 -0800 | [diff] [blame] | 1095 | if ( !fh || fh->clazz != &_fh_socket_class ) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1096 | D("adb_setsockopt: invalid fd %d", fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1097 | errno = EBADF; |
| 1098 | return -1; |
| 1099 | } |
Spencer Low | c7c4561 | 2015-09-29 15:05:29 -0700 | [diff] [blame] | 1100 | |
| 1101 | // TODO: Once we can assume Windows Vista or later, if the caller is trying |
| 1102 | // to set SOL_SOCKET, SO_SNDBUF/SO_RCVBUF, ignore it since the OS has |
| 1103 | // auto-tuning. |
| 1104 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1105 | int result = setsockopt( fh->fh_socket, level, optname, |
| 1106 | reinterpret_cast<const char*>(optval), optlen ); |
| 1107 | if ( result == SOCKET_ERROR ) { |
| 1108 | const DWORD err = WSAGetLastError(); |
| 1109 | D( "adb_setsockopt: setsockopt on fd %d level %d optname %d " |
| 1110 | "failed: %s\n", fd, level, optname, |
| 1111 | SystemErrorCodeToString(err).c_str() ); |
| 1112 | _socket_set_errno( err ); |
| 1113 | result = -1; |
| 1114 | } |
| 1115 | return result; |
| 1116 | } |
| 1117 | |
| 1118 | |
| 1119 | int adb_shutdown(int fd) |
| 1120 | { |
| 1121 | FH f = _fh_from_int(fd, __func__); |
| 1122 | |
| 1123 | if (!f || f->clazz != &_fh_socket_class) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1124 | D("adb_shutdown: invalid fd %d", fd); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1125 | errno = EBADF; |
Spencer Low | 31aafa6 | 2015-01-25 14:40:16 -0800 | [diff] [blame] | 1126 | return -1; |
| 1127 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1128 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1129 | D( "adb_shutdown: %s", f->name); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1130 | if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) { |
| 1131 | const DWORD err = WSAGetLastError(); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1132 | D("socket shutdown fd %d failed: %s", fd, |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1133 | SystemErrorCodeToString(err).c_str()); |
| 1134 | _socket_set_errno(err); |
| 1135 | return -1; |
| 1136 | } |
| 1137 | return 0; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1138 | } |
| 1139 | |
| 1140 | /**************************************************************************/ |
| 1141 | /**************************************************************************/ |
| 1142 | /***** *****/ |
| 1143 | /***** emulated socketpairs *****/ |
| 1144 | /***** *****/ |
| 1145 | /**************************************************************************/ |
| 1146 | /**************************************************************************/ |
| 1147 | |
| 1148 | /* we implement socketpairs directly in use space for the following reasons: |
| 1149 | * - it avoids copying data from/to the Nt kernel |
| 1150 | * - it allows us to implement fdevent hooks easily and cheaply, something |
| 1151 | * that is not possible with standard Win32 pipes !! |
| 1152 | * |
| 1153 | * basically, we use two circular buffers, each one corresponding to a given |
| 1154 | * direction. |
| 1155 | * |
| 1156 | * each buffer is implemented as two regions: |
| 1157 | * |
| 1158 | * region A which is (a_start,a_end) |
| 1159 | * region B which is (0, b_end) with b_end <= a_start |
| 1160 | * |
| 1161 | * an empty buffer has: a_start = a_end = b_end = 0 |
| 1162 | * |
| 1163 | * a_start is the pointer where we start reading data |
| 1164 | * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE, |
| 1165 | * then you start writing at b_end |
| 1166 | * |
| 1167 | * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE |
| 1168 | * |
| 1169 | * there is room when b_end < a_start || a_end < BUFER_SIZE |
| 1170 | * |
| 1171 | * when reading, a_start is incremented, it a_start meets a_end, then |
| 1172 | * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on.. |
| 1173 | */ |
| 1174 | |
| 1175 | #define BIP_BUFFER_SIZE 4096 |
| 1176 | |
| 1177 | #if 0 |
| 1178 | #include <stdio.h> |
| 1179 | # define BIPD(x) D x |
| 1180 | # define BIPDUMP bip_dump_hex |
| 1181 | |
| 1182 | static void bip_dump_hex( const unsigned char* ptr, size_t len ) |
| 1183 | { |
| 1184 | int nn, len2 = len; |
| 1185 | |
| 1186 | if (len2 > 8) len2 = 8; |
| 1187 | |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 1188 | for (nn = 0; nn < len2; nn++) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1189 | printf("%02x", ptr[nn]); |
| 1190 | printf(" "); |
| 1191 | |
| 1192 | for (nn = 0; nn < len2; nn++) { |
| 1193 | int c = ptr[nn]; |
| 1194 | if (c < 32 || c > 127) |
| 1195 | c = '.'; |
| 1196 | printf("%c", c); |
| 1197 | } |
| 1198 | printf("\n"); |
| 1199 | fflush(stdout); |
| 1200 | } |
| 1201 | |
| 1202 | #else |
| 1203 | # define BIPD(x) do {} while (0) |
| 1204 | # define BIPDUMP(p,l) BIPD(p) |
| 1205 | #endif |
| 1206 | |
| 1207 | typedef struct BipBufferRec_ |
| 1208 | { |
| 1209 | int a_start; |
| 1210 | int a_end; |
| 1211 | int b_end; |
| 1212 | int fdin; |
| 1213 | int fdout; |
| 1214 | int closed; |
| 1215 | int can_write; /* boolean */ |
| 1216 | HANDLE evt_write; /* event signaled when one can write to a buffer */ |
| 1217 | int can_read; /* boolean */ |
| 1218 | HANDLE evt_read; /* event signaled when one can read from a buffer */ |
| 1219 | CRITICAL_SECTION lock; |
| 1220 | unsigned char buff[ BIP_BUFFER_SIZE ]; |
| 1221 | |
| 1222 | } BipBufferRec, *BipBuffer; |
| 1223 | |
| 1224 | static void |
| 1225 | bip_buffer_init( BipBuffer buffer ) |
| 1226 | { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1227 | D( "bit_buffer_init %p", buffer ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1228 | buffer->a_start = 0; |
| 1229 | buffer->a_end = 0; |
| 1230 | buffer->b_end = 0; |
| 1231 | buffer->can_write = 1; |
| 1232 | buffer->can_read = 0; |
| 1233 | buffer->fdin = 0; |
| 1234 | buffer->fdout = 0; |
| 1235 | buffer->closed = 0; |
| 1236 | buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL ); |
| 1237 | buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL ); |
| 1238 | InitializeCriticalSection( &buffer->lock ); |
| 1239 | } |
| 1240 | |
| 1241 | static void |
| 1242 | bip_buffer_close( BipBuffer bip ) |
| 1243 | { |
| 1244 | bip->closed = 1; |
| 1245 | |
| 1246 | if (!bip->can_read) { |
| 1247 | SetEvent( bip->evt_read ); |
| 1248 | } |
| 1249 | if (!bip->can_write) { |
| 1250 | SetEvent( bip->evt_write ); |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | static void |
| 1255 | bip_buffer_done( BipBuffer bip ) |
| 1256 | { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1257 | BIPD(( "bip_buffer_done: %d->%d", bip->fdin, bip->fdout )); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1258 | CloseHandle( bip->evt_read ); |
| 1259 | CloseHandle( bip->evt_write ); |
| 1260 | DeleteCriticalSection( &bip->lock ); |
| 1261 | } |
| 1262 | |
| 1263 | static int |
| 1264 | bip_buffer_write( BipBuffer bip, const void* src, int len ) |
| 1265 | { |
| 1266 | int avail, count = 0; |
| 1267 | |
| 1268 | if (len <= 0) |
| 1269 | return 0; |
| 1270 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1271 | BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len )); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1272 | BIPDUMP( src, len ); |
| 1273 | |
David Pursell | 7616ae1 | 2015-09-11 16:06:59 -0700 | [diff] [blame] | 1274 | if (bip->closed) { |
| 1275 | errno = EPIPE; |
| 1276 | return -1; |
| 1277 | } |
| 1278 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1279 | EnterCriticalSection( &bip->lock ); |
| 1280 | |
| 1281 | while (!bip->can_write) { |
| 1282 | int ret; |
| 1283 | LeaveCriticalSection( &bip->lock ); |
| 1284 | |
| 1285 | if (bip->closed) { |
| 1286 | errno = EPIPE; |
| 1287 | return -1; |
| 1288 | } |
| 1289 | /* spinlocking here is probably unfair, but let's live with it */ |
| 1290 | ret = WaitForSingleObject( bip->evt_write, INFINITE ); |
| 1291 | if (ret != WAIT_OBJECT_0) { /* buffer probably closed */ |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1292 | D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError() ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1293 | return 0; |
| 1294 | } |
| 1295 | if (bip->closed) { |
| 1296 | errno = EPIPE; |
| 1297 | return -1; |
| 1298 | } |
| 1299 | EnterCriticalSection( &bip->lock ); |
| 1300 | } |
| 1301 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1302 | BIPD(( "bip_buffer_write: exec %d->%d len %d", bip->fdin, bip->fdout, len )); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1303 | |
| 1304 | avail = BIP_BUFFER_SIZE - bip->a_end; |
| 1305 | if (avail > 0) |
| 1306 | { |
| 1307 | /* we can append to region A */ |
| 1308 | if (avail > len) |
| 1309 | avail = len; |
| 1310 | |
| 1311 | memcpy( bip->buff + bip->a_end, src, avail ); |
Mark Salyzyn | 63e39f2 | 2014-04-30 09:10:31 -0700 | [diff] [blame] | 1312 | src = (const char *)src + avail; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1313 | count += avail; |
| 1314 | len -= avail; |
| 1315 | |
| 1316 | bip->a_end += avail; |
| 1317 | if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) { |
| 1318 | bip->can_write = 0; |
| 1319 | ResetEvent( bip->evt_write ); |
| 1320 | goto Exit; |
| 1321 | } |
| 1322 | } |
| 1323 | |
| 1324 | if (len == 0) |
| 1325 | goto Exit; |
| 1326 | |
| 1327 | avail = bip->a_start - bip->b_end; |
| 1328 | assert( avail > 0 ); /* since can_write is TRUE */ |
| 1329 | |
| 1330 | if (avail > len) |
| 1331 | avail = len; |
| 1332 | |
| 1333 | memcpy( bip->buff + bip->b_end, src, avail ); |
| 1334 | count += avail; |
| 1335 | bip->b_end += avail; |
| 1336 | |
| 1337 | if (bip->b_end == bip->a_start) { |
| 1338 | bip->can_write = 0; |
| 1339 | ResetEvent( bip->evt_write ); |
| 1340 | } |
| 1341 | |
| 1342 | Exit: |
| 1343 | assert( count > 0 ); |
| 1344 | |
| 1345 | if ( !bip->can_read ) { |
| 1346 | bip->can_read = 1; |
| 1347 | SetEvent( bip->evt_read ); |
| 1348 | } |
| 1349 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1350 | BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d", |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1351 | bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read )); |
| 1352 | LeaveCriticalSection( &bip->lock ); |
| 1353 | |
| 1354 | return count; |
| 1355 | } |
| 1356 | |
| 1357 | static int |
| 1358 | bip_buffer_read( BipBuffer bip, void* dst, int len ) |
| 1359 | { |
| 1360 | int avail, count = 0; |
| 1361 | |
| 1362 | if (len <= 0) |
| 1363 | return 0; |
| 1364 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1365 | BIPD(( "bip_buffer_read: enter %d->%d len %d", bip->fdin, bip->fdout, len )); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1366 | |
| 1367 | EnterCriticalSection( &bip->lock ); |
| 1368 | while ( !bip->can_read ) |
| 1369 | { |
| 1370 | #if 0 |
| 1371 | LeaveCriticalSection( &bip->lock ); |
| 1372 | errno = EAGAIN; |
| 1373 | return -1; |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 1374 | #else |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1375 | int ret; |
| 1376 | LeaveCriticalSection( &bip->lock ); |
| 1377 | |
| 1378 | if (bip->closed) { |
| 1379 | errno = EPIPE; |
| 1380 | return -1; |
| 1381 | } |
| 1382 | |
| 1383 | ret = WaitForSingleObject( bip->evt_read, INFINITE ); |
| 1384 | if (ret != WAIT_OBJECT_0) { /* probably closed buffer */ |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1385 | D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld", bip->fdin, bip->fdout, ret, GetLastError()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1386 | return 0; |
| 1387 | } |
| 1388 | if (bip->closed) { |
| 1389 | errno = EPIPE; |
| 1390 | return -1; |
| 1391 | } |
| 1392 | EnterCriticalSection( &bip->lock ); |
| 1393 | #endif |
| 1394 | } |
| 1395 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1396 | BIPD(( "bip_buffer_read: exec %d->%d len %d", bip->fdin, bip->fdout, len )); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1397 | |
| 1398 | avail = bip->a_end - bip->a_start; |
| 1399 | assert( avail > 0 ); /* since can_read is TRUE */ |
| 1400 | |
| 1401 | if (avail > len) |
| 1402 | avail = len; |
| 1403 | |
| 1404 | memcpy( dst, bip->buff + bip->a_start, avail ); |
Mark Salyzyn | 63e39f2 | 2014-04-30 09:10:31 -0700 | [diff] [blame] | 1405 | dst = (char *)dst + avail; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1406 | count += avail; |
| 1407 | len -= avail; |
| 1408 | |
| 1409 | bip->a_start += avail; |
| 1410 | if (bip->a_start < bip->a_end) |
| 1411 | goto Exit; |
| 1412 | |
| 1413 | bip->a_start = 0; |
| 1414 | bip->a_end = bip->b_end; |
| 1415 | bip->b_end = 0; |
| 1416 | |
| 1417 | avail = bip->a_end; |
| 1418 | if (avail > 0) { |
| 1419 | if (avail > len) |
| 1420 | avail = len; |
| 1421 | memcpy( dst, bip->buff, avail ); |
| 1422 | count += avail; |
| 1423 | bip->a_start += avail; |
| 1424 | |
| 1425 | if ( bip->a_start < bip->a_end ) |
| 1426 | goto Exit; |
| 1427 | |
| 1428 | bip->a_start = bip->a_end = 0; |
| 1429 | } |
| 1430 | |
| 1431 | bip->can_read = 0; |
| 1432 | ResetEvent( bip->evt_read ); |
| 1433 | |
| 1434 | Exit: |
| 1435 | assert( count > 0 ); |
| 1436 | |
| 1437 | if (!bip->can_write ) { |
| 1438 | bip->can_write = 1; |
| 1439 | SetEvent( bip->evt_write ); |
| 1440 | } |
| 1441 | |
| 1442 | BIPDUMP( (const unsigned char*)dst - count, count ); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1443 | BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d", |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1444 | bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read )); |
| 1445 | LeaveCriticalSection( &bip->lock ); |
| 1446 | |
| 1447 | return count; |
| 1448 | } |
| 1449 | |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 1450 | typedef struct SocketPairRec_ |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1451 | { |
| 1452 | BipBufferRec a2b_bip; |
| 1453 | BipBufferRec b2a_bip; |
| 1454 | FH a_fd; |
| 1455 | int used; |
| 1456 | |
| 1457 | } SocketPairRec; |
| 1458 | |
| 1459 | void _fh_socketpair_init( FH f ) |
| 1460 | { |
| 1461 | f->fh_pair = NULL; |
| 1462 | } |
| 1463 | |
| 1464 | static int |
| 1465 | _fh_socketpair_close( FH f ) |
| 1466 | { |
| 1467 | if ( f->fh_pair ) { |
| 1468 | SocketPair pair = f->fh_pair; |
| 1469 | |
| 1470 | if ( f == pair->a_fd ) { |
| 1471 | pair->a_fd = NULL; |
| 1472 | } |
| 1473 | |
| 1474 | bip_buffer_close( &pair->b2a_bip ); |
| 1475 | bip_buffer_close( &pair->a2b_bip ); |
| 1476 | |
| 1477 | if ( --pair->used == 0 ) { |
| 1478 | bip_buffer_done( &pair->b2a_bip ); |
| 1479 | bip_buffer_done( &pair->a2b_bip ); |
| 1480 | free( pair ); |
| 1481 | } |
| 1482 | f->fh_pair = NULL; |
| 1483 | } |
| 1484 | return 0; |
| 1485 | } |
| 1486 | |
| 1487 | static int |
| 1488 | _fh_socketpair_lseek( FH f, int pos, int origin ) |
| 1489 | { |
| 1490 | errno = ESPIPE; |
| 1491 | return -1; |
| 1492 | } |
| 1493 | |
| 1494 | static int |
| 1495 | _fh_socketpair_read( FH f, void* buf, int len ) |
| 1496 | { |
| 1497 | SocketPair pair = f->fh_pair; |
| 1498 | BipBuffer bip; |
| 1499 | |
| 1500 | if (!pair) |
| 1501 | return -1; |
| 1502 | |
| 1503 | if ( f == pair->a_fd ) |
| 1504 | bip = &pair->b2a_bip; |
| 1505 | else |
| 1506 | bip = &pair->a2b_bip; |
| 1507 | |
| 1508 | return bip_buffer_read( bip, buf, len ); |
| 1509 | } |
| 1510 | |
| 1511 | static int |
| 1512 | _fh_socketpair_write( FH f, const void* buf, int len ) |
| 1513 | { |
| 1514 | SocketPair pair = f->fh_pair; |
| 1515 | BipBuffer bip; |
| 1516 | |
| 1517 | if (!pair) |
| 1518 | return -1; |
| 1519 | |
| 1520 | if ( f == pair->a_fd ) |
| 1521 | bip = &pair->a2b_bip; |
| 1522 | else |
| 1523 | bip = &pair->b2a_bip; |
| 1524 | |
| 1525 | return bip_buffer_write( bip, buf, len ); |
| 1526 | } |
| 1527 | |
| 1528 | |
| 1529 | static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */ |
| 1530 | |
| 1531 | static const FHClassRec _fh_socketpair_class = |
| 1532 | { |
| 1533 | _fh_socketpair_init, |
| 1534 | _fh_socketpair_close, |
| 1535 | _fh_socketpair_lseek, |
| 1536 | _fh_socketpair_read, |
| 1537 | _fh_socketpair_write, |
| 1538 | _fh_socketpair_hook |
| 1539 | }; |
| 1540 | |
| 1541 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 1542 | int adb_socketpair(int sv[2]) { |
| 1543 | SocketPair pair; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1544 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1545 | unique_fh fa(_fh_alloc(&_fh_socketpair_class)); |
| 1546 | if (!fa) { |
| 1547 | return -1; |
| 1548 | } |
| 1549 | unique_fh fb(_fh_alloc(&_fh_socketpair_class)); |
| 1550 | if (!fb) { |
| 1551 | return -1; |
| 1552 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1553 | |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 1554 | pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair))); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1555 | if (pair == NULL) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1556 | D("adb_socketpair: not enough memory to allocate pipes" ); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1557 | return -1; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1558 | } |
| 1559 | |
| 1560 | bip_buffer_init( &pair->a2b_bip ); |
| 1561 | bip_buffer_init( &pair->b2a_bip ); |
| 1562 | |
| 1563 | fa->fh_pair = pair; |
| 1564 | fb->fh_pair = pair; |
| 1565 | pair->used = 2; |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1566 | pair->a_fd = fa.get(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1567 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1568 | sv[0] = _fh_to_int(fa.get()); |
| 1569 | sv[1] = _fh_to_int(fb.get()); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1570 | |
| 1571 | pair->a2b_bip.fdin = sv[0]; |
| 1572 | pair->a2b_bip.fdout = sv[1]; |
| 1573 | pair->b2a_bip.fdin = sv[1]; |
| 1574 | pair->b2a_bip.fdout = sv[0]; |
| 1575 | |
| 1576 | snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] ); |
| 1577 | snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] ); |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1578 | D( "adb_socketpair: returns (%d, %d)", sv[0], sv[1] ); |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 1579 | fa.release(); |
| 1580 | fb.release(); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1581 | return 0; |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1582 | } |
| 1583 | |
| 1584 | /**************************************************************************/ |
| 1585 | /**************************************************************************/ |
| 1586 | /***** *****/ |
| 1587 | /***** fdevents emulation *****/ |
| 1588 | /***** *****/ |
| 1589 | /***** this is a very simple implementation, we rely on the fact *****/ |
| 1590 | /***** that ADB doesn't use FDE_ERROR. *****/ |
| 1591 | /***** *****/ |
| 1592 | /**************************************************************************/ |
| 1593 | /**************************************************************************/ |
| 1594 | |
Josh Gao | 2930cdc | 2016-01-15 15:17:37 -0800 | [diff] [blame] | 1595 | #define FATAL(fmt, ...) fatal("%s: " fmt, __FUNCTION__, ##__VA_ARGS__) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1596 | |
| 1597 | #if DEBUG |
| 1598 | static void dump_fde(fdevent *fde, const char *info) |
| 1599 | { |
| 1600 | fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd, |
| 1601 | fde->state & FDE_READ ? 'R' : ' ', |
| 1602 | fde->state & FDE_WRITE ? 'W' : ' ', |
| 1603 | fde->state & FDE_ERROR ? 'E' : ' ', |
| 1604 | info); |
| 1605 | } |
| 1606 | #else |
| 1607 | #define dump_fde(fde, info) do { } while(0) |
| 1608 | #endif |
| 1609 | |
| 1610 | #define FDE_EVENTMASK 0x00ff |
| 1611 | #define FDE_STATEMASK 0xff00 |
| 1612 | |
| 1613 | #define FDE_ACTIVE 0x0100 |
| 1614 | #define FDE_PENDING 0x0200 |
| 1615 | #define FDE_CREATED 0x0400 |
| 1616 | |
| 1617 | static void fdevent_plist_enqueue(fdevent *node); |
| 1618 | static void fdevent_plist_remove(fdevent *node); |
| 1619 | static fdevent *fdevent_plist_dequeue(void); |
| 1620 | |
| 1621 | static fdevent list_pending = { |
| 1622 | .next = &list_pending, |
| 1623 | .prev = &list_pending, |
| 1624 | }; |
| 1625 | |
| 1626 | static fdevent **fd_table = 0; |
| 1627 | static int fd_table_max = 0; |
| 1628 | |
| 1629 | typedef struct EventLooperRec_* EventLooper; |
| 1630 | |
| 1631 | typedef struct EventHookRec_ |
| 1632 | { |
| 1633 | EventHook next; |
| 1634 | FH fh; |
| 1635 | HANDLE h; |
| 1636 | int wanted; /* wanted event flags */ |
| 1637 | int ready; /* ready event flags */ |
| 1638 | void* aux; |
| 1639 | void (*prepare)( EventHook hook ); |
| 1640 | int (*start) ( EventHook hook ); |
| 1641 | void (*stop) ( EventHook hook ); |
| 1642 | int (*check) ( EventHook hook ); |
| 1643 | int (*peek) ( EventHook hook ); |
| 1644 | } EventHookRec; |
| 1645 | |
| 1646 | static EventHook _free_hooks; |
| 1647 | |
| 1648 | static EventHook |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 1649 | event_hook_alloc(FH fh) { |
| 1650 | EventHook hook = _free_hooks; |
| 1651 | if (hook != NULL) { |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1652 | _free_hooks = hook->next; |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 1653 | } else { |
| 1654 | hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook))); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1655 | if (hook == NULL) |
| 1656 | fatal( "could not allocate event hook\n" ); |
| 1657 | } |
| 1658 | hook->next = NULL; |
| 1659 | hook->fh = fh; |
| 1660 | hook->wanted = 0; |
| 1661 | hook->ready = 0; |
| 1662 | hook->h = INVALID_HANDLE_VALUE; |
| 1663 | hook->aux = NULL; |
| 1664 | |
| 1665 | hook->prepare = NULL; |
| 1666 | hook->start = NULL; |
| 1667 | hook->stop = NULL; |
| 1668 | hook->check = NULL; |
| 1669 | hook->peek = NULL; |
| 1670 | |
| 1671 | return hook; |
| 1672 | } |
| 1673 | |
| 1674 | static void |
| 1675 | event_hook_free( EventHook hook ) |
| 1676 | { |
| 1677 | hook->fh = NULL; |
| 1678 | hook->wanted = 0; |
| 1679 | hook->ready = 0; |
| 1680 | hook->next = _free_hooks; |
| 1681 | _free_hooks = hook; |
| 1682 | } |
| 1683 | |
| 1684 | |
| 1685 | static void |
| 1686 | event_hook_signal( EventHook hook ) |
| 1687 | { |
| 1688 | FH f = hook->fh; |
| 1689 | int fd = _fh_to_int(f); |
| 1690 | fdevent* fde = fd_table[ fd - WIN32_FH_BASE ]; |
| 1691 | |
| 1692 | if (fde != NULL && fde->fd == fd) { |
| 1693 | if ((fde->state & FDE_PENDING) == 0) { |
| 1694 | fde->state |= FDE_PENDING; |
| 1695 | fdevent_plist_enqueue( fde ); |
| 1696 | } |
| 1697 | fde->events |= hook->wanted; |
| 1698 | } |
| 1699 | } |
| 1700 | |
| 1701 | |
| 1702 | #define MAX_LOOPER_HANDLES WIN32_MAX_FHS |
| 1703 | |
| 1704 | typedef struct EventLooperRec_ |
| 1705 | { |
| 1706 | EventHook hooks; |
| 1707 | HANDLE htab[ MAX_LOOPER_HANDLES ]; |
| 1708 | int htab_count; |
| 1709 | |
| 1710 | } EventLooperRec; |
| 1711 | |
| 1712 | static EventHook* |
| 1713 | event_looper_find_p( EventLooper looper, FH fh ) |
| 1714 | { |
| 1715 | EventHook *pnode = &looper->hooks; |
| 1716 | EventHook node = *pnode; |
| 1717 | for (;;) { |
| 1718 | if ( node == NULL || node->fh == fh ) |
| 1719 | break; |
| 1720 | pnode = &node->next; |
| 1721 | node = *pnode; |
| 1722 | } |
| 1723 | return pnode; |
| 1724 | } |
| 1725 | |
| 1726 | static void |
| 1727 | event_looper_hook( EventLooper looper, int fd, int events ) |
| 1728 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 1729 | FH f = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1730 | EventHook *pnode; |
| 1731 | EventHook node; |
| 1732 | |
| 1733 | if (f == NULL) /* invalid arg */ { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1734 | D("event_looper_hook: invalid fd=%d", fd); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1735 | return; |
| 1736 | } |
| 1737 | |
| 1738 | pnode = event_looper_find_p( looper, f ); |
| 1739 | node = *pnode; |
| 1740 | if ( node == NULL ) { |
| 1741 | node = event_hook_alloc( f ); |
| 1742 | node->next = *pnode; |
| 1743 | *pnode = node; |
| 1744 | } |
| 1745 | |
| 1746 | if ( (node->wanted & events) != events ) { |
| 1747 | /* this should update start/stop/check/peek */ |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1748 | D("event_looper_hook: call hook for %d (new=%x, old=%x)", |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1749 | fd, node->wanted, events); |
| 1750 | f->clazz->_fh_hook( f, events & ~node->wanted, node ); |
| 1751 | node->wanted |= events; |
| 1752 | } else { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1753 | D("event_looper_hook: ignoring events %x for %d wanted=%x)", |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1754 | events, fd, node->wanted); |
| 1755 | } |
| 1756 | } |
| 1757 | |
| 1758 | static void |
| 1759 | event_looper_unhook( EventLooper looper, int fd, int events ) |
| 1760 | { |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 1761 | FH fh = _fh_from_int(fd, __func__); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1762 | EventHook *pnode = event_looper_find_p( looper, fh ); |
| 1763 | EventHook node = *pnode; |
| 1764 | |
| 1765 | if (node != NULL) { |
| 1766 | int events2 = events & node->wanted; |
| 1767 | if ( events2 == 0 ) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1768 | D( "event_looper_unhook: events %x not registered for fd %d", events, fd ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1769 | return; |
| 1770 | } |
| 1771 | node->wanted &= ~events2; |
| 1772 | if (!node->wanted) { |
| 1773 | *pnode = node->next; |
| 1774 | event_hook_free( node ); |
| 1775 | } |
| 1776 | } |
| 1777 | } |
| 1778 | |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 1779 | /* |
| 1780 | * A fixer for WaitForMultipleObjects on condition that there are more than 64 |
| 1781 | * handles to wait on. |
| 1782 | * |
| 1783 | * In cetain cases DDMS may establish more than 64 connections with ADB. For |
| 1784 | * instance, this may happen if there are more than 64 processes running on a |
| 1785 | * device, or there are multiple devices connected (including the emulator) with |
| 1786 | * the combined number of running processes greater than 64. In this case using |
| 1787 | * WaitForMultipleObjects to wait on connection events simply wouldn't cut, |
| 1788 | * because of the API limitations (64 handles max). So, we need to provide a way |
| 1789 | * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The |
| 1790 | * easiest (and "Microsoft recommended") way to do that would be dividing the |
| 1791 | * handle array into chunks with the chunk size less than 64, and fire up as many |
| 1792 | * waiting threads as there are chunks. Then each thread would wait on a chunk of |
| 1793 | * handles, and will report back to the caller which handle has been set. |
| 1794 | * Here is the implementation of that algorithm. |
| 1795 | */ |
| 1796 | |
| 1797 | /* Number of handles to wait on in each wating thread. */ |
| 1798 | #define WAIT_ALL_CHUNK_SIZE 63 |
| 1799 | |
| 1800 | /* Descriptor for a wating thread */ |
| 1801 | typedef struct WaitForAllParam { |
| 1802 | /* A handle to an event to signal when waiting is over. This handle is shared |
| 1803 | * accross all the waiting threads, so each waiting thread knows when any |
| 1804 | * other thread has exited, so it can exit too. */ |
| 1805 | HANDLE main_event; |
| 1806 | /* Upon exit from a waiting thread contains the index of the handle that has |
| 1807 | * been signaled. The index is an absolute index of the signaled handle in |
| 1808 | * the original array. This pointer is shared accross all the waiting threads |
| 1809 | * and it's not guaranteed (due to a race condition) that when all the |
| 1810 | * waiting threads exit, the value contained here would indicate the first |
| 1811 | * handle that was signaled. This is fine, because the caller cares only |
| 1812 | * about any handle being signaled. It doesn't care about the order, nor |
| 1813 | * about the whole list of handles that were signaled. */ |
| 1814 | LONG volatile *signaled_index; |
| 1815 | /* Array of handles to wait on in a waiting thread. */ |
| 1816 | HANDLE* handles; |
| 1817 | /* Number of handles in 'handles' array to wait on. */ |
| 1818 | int handles_count; |
| 1819 | /* Index inside the main array of the first handle in the 'handles' array. */ |
| 1820 | int first_handle_index; |
| 1821 | /* Waiting thread handle. */ |
| 1822 | HANDLE thread; |
| 1823 | } WaitForAllParam; |
| 1824 | |
| 1825 | /* Waiting thread routine. */ |
| 1826 | static unsigned __stdcall |
| 1827 | _in_waiter_thread(void* arg) |
| 1828 | { |
| 1829 | HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1]; |
| 1830 | int res; |
| 1831 | WaitForAllParam* const param = (WaitForAllParam*)arg; |
| 1832 | |
| 1833 | /* We have to wait on the main_event in order to be notified when any of the |
| 1834 | * sibling threads is exiting. */ |
| 1835 | wait_on[0] = param->main_event; |
| 1836 | /* The rest of the handles go behind the main event handle. */ |
| 1837 | memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE)); |
| 1838 | |
| 1839 | res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE); |
| 1840 | if (res > 0 && res < (param->handles_count + 1)) { |
| 1841 | /* One of the original handles got signaled. Save its absolute index into |
| 1842 | * the output variable. */ |
| 1843 | InterlockedCompareExchange(param->signaled_index, |
| 1844 | res - 1L + param->first_handle_index, -1L); |
| 1845 | } |
| 1846 | |
| 1847 | /* Notify the caller (and the siblings) that the wait is over. */ |
| 1848 | SetEvent(param->main_event); |
| 1849 | |
| 1850 | _endthreadex(0); |
| 1851 | return 0; |
| 1852 | } |
| 1853 | |
| 1854 | /* WaitForMultipeObjects fixer routine. |
| 1855 | * Param: |
| 1856 | * handles Array of handles to wait on. |
| 1857 | * handles_count Number of handles in the array. |
| 1858 | * Return: |
| 1859 | * (>= 0 && < handles_count) - Index of the signaled handle in the array, or |
| 1860 | * WAIT_FAILED on an error. |
| 1861 | */ |
| 1862 | static int |
| 1863 | _wait_for_all(HANDLE* handles, int handles_count) |
| 1864 | { |
| 1865 | WaitForAllParam* threads; |
| 1866 | HANDLE main_event; |
| 1867 | int chunks, chunk, remains; |
| 1868 | |
| 1869 | /* This variable is going to be accessed by several threads at the same time, |
| 1870 | * this is bound to fail randomly when the core is run on multi-core machines. |
| 1871 | * To solve this, we need to do the following (1 _and_ 2): |
| 1872 | * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize |
| 1873 | * out the reads/writes in this function unexpectedly. |
| 1874 | * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap |
| 1875 | * all accesses inside a critical section. But we can also use |
| 1876 | * InterlockedCompareExchange() which always provide a full memory barrier |
| 1877 | * on Win32. |
| 1878 | */ |
| 1879 | volatile LONG sig_index = -1; |
| 1880 | |
| 1881 | /* Calculate number of chunks, and allocate thread param array. */ |
| 1882 | chunks = handles_count / WAIT_ALL_CHUNK_SIZE; |
| 1883 | remains = handles_count % WAIT_ALL_CHUNK_SIZE; |
| 1884 | threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) * |
| 1885 | sizeof(WaitForAllParam)); |
| 1886 | if (threads == NULL) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1887 | D("Unable to allocate thread array for %d handles.", handles_count); |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 1888 | return (int)WAIT_FAILED; |
| 1889 | } |
| 1890 | |
| 1891 | /* Create main event to wait on for all waiting threads. This is a "manualy |
| 1892 | * reset" event that will remain set once it was set. */ |
| 1893 | main_event = CreateEvent(NULL, TRUE, FALSE, NULL); |
| 1894 | if (main_event == NULL) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1895 | D("Unable to create main event. Error: %ld", GetLastError()); |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 1896 | free(threads); |
| 1897 | return (int)WAIT_FAILED; |
| 1898 | } |
| 1899 | |
| 1900 | /* |
| 1901 | * Initialize waiting thread parameters. |
| 1902 | */ |
| 1903 | |
| 1904 | for (chunk = 0; chunk < chunks; chunk++) { |
| 1905 | threads[chunk].main_event = main_event; |
| 1906 | threads[chunk].signaled_index = &sig_index; |
| 1907 | threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk; |
| 1908 | threads[chunk].handles = handles + threads[chunk].first_handle_index; |
| 1909 | threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE; |
| 1910 | } |
| 1911 | if (remains) { |
| 1912 | threads[chunk].main_event = main_event; |
| 1913 | threads[chunk].signaled_index = &sig_index; |
| 1914 | threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk; |
| 1915 | threads[chunk].handles = handles + threads[chunk].first_handle_index; |
| 1916 | threads[chunk].handles_count = remains; |
| 1917 | chunks++; |
| 1918 | } |
| 1919 | |
| 1920 | /* Start the waiting threads. */ |
| 1921 | for (chunk = 0; chunk < chunks; chunk++) { |
| 1922 | /* Note that using adb_thread_create is not appropriate here, since we |
| 1923 | * need a handle to wait on for thread termination. */ |
| 1924 | threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread, |
| 1925 | &threads[chunk], 0, NULL); |
| 1926 | if (threads[chunk].thread == NULL) { |
| 1927 | /* Unable to create a waiter thread. Collapse. */ |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1928 | D("Unable to create a waiting thread %d of %d. errno=%d", |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 1929 | chunk, chunks, errno); |
| 1930 | chunks = chunk; |
| 1931 | SetEvent(main_event); |
| 1932 | break; |
| 1933 | } |
| 1934 | } |
| 1935 | |
| 1936 | /* Wait on any of the threads to get signaled. */ |
| 1937 | WaitForSingleObject(main_event, INFINITE); |
| 1938 | |
| 1939 | /* Wait on all the waiting threads to exit. */ |
| 1940 | for (chunk = 0; chunk < chunks; chunk++) { |
| 1941 | WaitForSingleObject(threads[chunk].thread, INFINITE); |
| 1942 | CloseHandle(threads[chunk].thread); |
| 1943 | } |
| 1944 | |
| 1945 | CloseHandle(main_event); |
| 1946 | free(threads); |
| 1947 | |
| 1948 | |
| 1949 | const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1); |
| 1950 | return (ret >= 0) ? ret : (int)WAIT_FAILED; |
| 1951 | } |
| 1952 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1953 | static EventLooperRec win32_looper; |
| 1954 | |
| 1955 | static void fdevent_init(void) |
| 1956 | { |
| 1957 | win32_looper.htab_count = 0; |
| 1958 | win32_looper.hooks = NULL; |
| 1959 | } |
| 1960 | |
| 1961 | static void fdevent_connect(fdevent *fde) |
| 1962 | { |
| 1963 | EventLooper looper = &win32_looper; |
| 1964 | int events = fde->state & FDE_EVENTMASK; |
| 1965 | |
| 1966 | if (events != 0) |
| 1967 | event_looper_hook( looper, fde->fd, events ); |
| 1968 | } |
| 1969 | |
| 1970 | static void fdevent_disconnect(fdevent *fde) |
| 1971 | { |
| 1972 | EventLooper looper = &win32_looper; |
| 1973 | int events = fde->state & FDE_EVENTMASK; |
| 1974 | |
| 1975 | if (events != 0) |
| 1976 | event_looper_unhook( looper, fde->fd, events ); |
| 1977 | } |
| 1978 | |
| 1979 | static void fdevent_update(fdevent *fde, unsigned events) |
| 1980 | { |
| 1981 | EventLooper looper = &win32_looper; |
| 1982 | unsigned events0 = fde->state & FDE_EVENTMASK; |
| 1983 | |
| 1984 | if (events != events0) { |
| 1985 | int removes = events0 & ~events; |
| 1986 | int adds = events & ~events0; |
| 1987 | if (removes) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1988 | D("fdevent_update: remove %x from %d", removes, fde->fd); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1989 | event_looper_unhook( looper, fde->fd, removes ); |
| 1990 | } |
| 1991 | if (adds) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 1992 | D("fdevent_update: add %x to %d", adds, fde->fd); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 1993 | event_looper_hook ( looper, fde->fd, adds ); |
| 1994 | } |
| 1995 | } |
| 1996 | } |
| 1997 | |
| 1998 | static void fdevent_process() |
| 1999 | { |
| 2000 | EventLooper looper = &win32_looper; |
| 2001 | EventHook hook; |
| 2002 | int gotone = 0; |
| 2003 | |
| 2004 | /* if we have at least one ready hook, execute it/them */ |
| 2005 | for (hook = looper->hooks; hook; hook = hook->next) { |
| 2006 | hook->ready = 0; |
| 2007 | if (hook->prepare) { |
| 2008 | hook->prepare(hook); |
| 2009 | if (hook->ready != 0) { |
| 2010 | event_hook_signal( hook ); |
| 2011 | gotone = 1; |
| 2012 | } |
| 2013 | } |
| 2014 | } |
| 2015 | |
| 2016 | /* nothing's ready yet, so wait for something to happen */ |
| 2017 | if (!gotone) |
| 2018 | { |
| 2019 | looper->htab_count = 0; |
| 2020 | |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 2021 | for (hook = looper->hooks; hook; hook = hook->next) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2022 | { |
| 2023 | if (hook->start && !hook->start(hook)) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2024 | D( "fdevent_process: error when starting a hook" ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2025 | return; |
| 2026 | } |
| 2027 | if (hook->h != INVALID_HANDLE_VALUE) { |
| 2028 | int nn; |
| 2029 | |
| 2030 | for (nn = 0; nn < looper->htab_count; nn++) |
| 2031 | { |
| 2032 | if ( looper->htab[nn] == hook->h ) |
| 2033 | goto DontAdd; |
| 2034 | } |
| 2035 | looper->htab[ looper->htab_count++ ] = hook->h; |
| 2036 | DontAdd: |
| 2037 | ; |
| 2038 | } |
| 2039 | } |
| 2040 | |
| 2041 | if (looper->htab_count == 0) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2042 | D( "fdevent_process: nothing to wait for !!" ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2043 | return; |
| 2044 | } |
| 2045 | |
| 2046 | do |
| 2047 | { |
| 2048 | int wait_ret; |
| 2049 | |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2050 | D( "adb_win32: waiting for %d events", looper->htab_count ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2051 | if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2052 | D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.", looper->htab_count); |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 2053 | wait_ret = _wait_for_all(looper->htab, looper->htab_count); |
| 2054 | } else { |
| 2055 | wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2056 | } |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2057 | if (wait_ret == (int)WAIT_FAILED) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2058 | D( "adb_win32: wait failed, error %ld", GetLastError() ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2059 | } else { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2060 | D( "adb_win32: got one (index %d)", wait_ret ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2061 | |
| 2062 | /* according to Cygwin, some objects like consoles wake up on "inappropriate" events |
| 2063 | * like mouse movements. we need to filter these with the "check" function |
| 2064 | */ |
| 2065 | if ((unsigned)wait_ret < (unsigned)looper->htab_count) |
| 2066 | { |
| 2067 | for (hook = looper->hooks; hook; hook = hook->next) |
| 2068 | { |
| 2069 | if ( looper->htab[wait_ret] == hook->h && |
| 2070 | (!hook->check || hook->check(hook)) ) |
| 2071 | { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2072 | D( "adb_win32: signaling %s for %x", hook->fh->name, hook->ready ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2073 | event_hook_signal( hook ); |
| 2074 | gotone = 1; |
| 2075 | break; |
| 2076 | } |
| 2077 | } |
| 2078 | } |
| 2079 | } |
| 2080 | } |
| 2081 | while (!gotone); |
| 2082 | |
| 2083 | for (hook = looper->hooks; hook; hook = hook->next) { |
| 2084 | if (hook->stop) |
| 2085 | hook->stop( hook ); |
| 2086 | } |
| 2087 | } |
| 2088 | |
| 2089 | for (hook = looper->hooks; hook; hook = hook->next) { |
| 2090 | if (hook->peek && hook->peek(hook)) |
| 2091 | event_hook_signal( hook ); |
| 2092 | } |
| 2093 | } |
| 2094 | |
| 2095 | |
| 2096 | static void fdevent_register(fdevent *fde) |
| 2097 | { |
| 2098 | int fd = fde->fd - WIN32_FH_BASE; |
| 2099 | |
| 2100 | if(fd < 0) { |
| 2101 | FATAL("bogus negative fd (%d)\n", fde->fd); |
| 2102 | } |
| 2103 | |
| 2104 | if(fd >= fd_table_max) { |
| 2105 | int oldmax = fd_table_max; |
| 2106 | if(fde->fd > 32000) { |
| 2107 | FATAL("bogus huuuuge fd (%d)\n", fde->fd); |
| 2108 | } |
| 2109 | if(fd_table_max == 0) { |
| 2110 | fdevent_init(); |
| 2111 | fd_table_max = 256; |
| 2112 | } |
| 2113 | while(fd_table_max <= fd) { |
| 2114 | fd_table_max *= 2; |
| 2115 | } |
Elliott Hughes | 6a09693 | 2015-04-16 16:47:02 -0700 | [diff] [blame] | 2116 | fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max)); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2117 | if(fd_table == 0) { |
| 2118 | FATAL("could not expand fd_table to %d entries\n", fd_table_max); |
| 2119 | } |
| 2120 | memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax)); |
| 2121 | } |
| 2122 | |
| 2123 | fd_table[fd] = fde; |
| 2124 | } |
| 2125 | |
| 2126 | static void fdevent_unregister(fdevent *fde) |
| 2127 | { |
| 2128 | int fd = fde->fd - WIN32_FH_BASE; |
| 2129 | |
| 2130 | if((fd < 0) || (fd >= fd_table_max)) { |
| 2131 | FATAL("fd out of range (%d)\n", fde->fd); |
| 2132 | } |
| 2133 | |
| 2134 | if(fd_table[fd] != fde) { |
| 2135 | FATAL("fd_table out of sync"); |
| 2136 | } |
| 2137 | |
| 2138 | fd_table[fd] = 0; |
| 2139 | |
| 2140 | if(!(fde->state & FDE_DONT_CLOSE)) { |
| 2141 | dump_fde(fde, "close"); |
| 2142 | adb_close(fde->fd); |
| 2143 | } |
| 2144 | } |
| 2145 | |
| 2146 | static void fdevent_plist_enqueue(fdevent *node) |
| 2147 | { |
| 2148 | fdevent *list = &list_pending; |
| 2149 | |
| 2150 | node->next = list; |
| 2151 | node->prev = list->prev; |
| 2152 | node->prev->next = node; |
| 2153 | list->prev = node; |
| 2154 | } |
| 2155 | |
| 2156 | static void fdevent_plist_remove(fdevent *node) |
| 2157 | { |
| 2158 | node->prev->next = node->next; |
| 2159 | node->next->prev = node->prev; |
| 2160 | node->next = 0; |
| 2161 | node->prev = 0; |
| 2162 | } |
| 2163 | |
| 2164 | static fdevent *fdevent_plist_dequeue(void) |
| 2165 | { |
| 2166 | fdevent *list = &list_pending; |
| 2167 | fdevent *node = list->next; |
| 2168 | |
| 2169 | if(node == list) return 0; |
| 2170 | |
| 2171 | list->next = node->next; |
| 2172 | list->next->prev = list; |
| 2173 | node->next = 0; |
| 2174 | node->prev = 0; |
| 2175 | |
| 2176 | return node; |
| 2177 | } |
| 2178 | |
| 2179 | fdevent *fdevent_create(int fd, fd_func func, void *arg) |
| 2180 | { |
| 2181 | fdevent *fde = (fdevent*) malloc(sizeof(fdevent)); |
| 2182 | if(fde == 0) return 0; |
| 2183 | fdevent_install(fde, fd, func, arg); |
| 2184 | fde->state |= FDE_CREATED; |
| 2185 | return fde; |
| 2186 | } |
| 2187 | |
| 2188 | void fdevent_destroy(fdevent *fde) |
| 2189 | { |
| 2190 | if(fde == 0) return; |
| 2191 | if(!(fde->state & FDE_CREATED)) { |
| 2192 | FATAL("fde %p not created by fdevent_create()\n", fde); |
| 2193 | } |
| 2194 | fdevent_remove(fde); |
| 2195 | } |
| 2196 | |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 2197 | void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2198 | { |
| 2199 | memset(fde, 0, sizeof(fdevent)); |
| 2200 | fde->state = FDE_ACTIVE; |
| 2201 | fde->fd = fd; |
| 2202 | fde->func = func; |
| 2203 | fde->arg = arg; |
| 2204 | |
| 2205 | fdevent_register(fde); |
| 2206 | dump_fde(fde, "connect"); |
| 2207 | fdevent_connect(fde); |
| 2208 | fde->state |= FDE_ACTIVE; |
| 2209 | } |
| 2210 | |
| 2211 | void fdevent_remove(fdevent *fde) |
| 2212 | { |
| 2213 | if(fde->state & FDE_PENDING) { |
| 2214 | fdevent_plist_remove(fde); |
| 2215 | } |
| 2216 | |
| 2217 | if(fde->state & FDE_ACTIVE) { |
| 2218 | fdevent_disconnect(fde); |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 2219 | dump_fde(fde, "disconnect"); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2220 | fdevent_unregister(fde); |
| 2221 | } |
| 2222 | |
| 2223 | fde->state = 0; |
| 2224 | fde->events = 0; |
| 2225 | } |
| 2226 | |
| 2227 | |
| 2228 | void fdevent_set(fdevent *fde, unsigned events) |
| 2229 | { |
| 2230 | events &= FDE_EVENTMASK; |
| 2231 | |
| 2232 | if((fde->state & FDE_EVENTMASK) == (int)events) return; |
| 2233 | |
| 2234 | if(fde->state & FDE_ACTIVE) { |
| 2235 | fdevent_update(fde, events); |
| 2236 | dump_fde(fde, "update"); |
| 2237 | } |
| 2238 | |
| 2239 | fde->state = (fde->state & FDE_STATEMASK) | events; |
| 2240 | |
| 2241 | if(fde->state & FDE_PENDING) { |
| 2242 | /* if we're pending, make sure |
| 2243 | ** we don't signal an event that |
| 2244 | ** is no longer wanted. |
| 2245 | */ |
| 2246 | fde->events &= (~events); |
| 2247 | if(fde->events == 0) { |
| 2248 | fdevent_plist_remove(fde); |
| 2249 | fde->state &= (~FDE_PENDING); |
| 2250 | } |
| 2251 | } |
| 2252 | } |
| 2253 | |
| 2254 | void fdevent_add(fdevent *fde, unsigned events) |
| 2255 | { |
| 2256 | fdevent_set( |
| 2257 | fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK)); |
| 2258 | } |
| 2259 | |
| 2260 | void fdevent_del(fdevent *fde, unsigned events) |
| 2261 | { |
| 2262 | fdevent_set( |
| 2263 | fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK))); |
| 2264 | } |
| 2265 | |
| 2266 | void fdevent_loop() |
| 2267 | { |
| 2268 | fdevent *fde; |
| 2269 | |
| 2270 | for(;;) { |
| 2271 | #if DEBUG |
| 2272 | fprintf(stderr,"--- ---- waiting for events\n"); |
| 2273 | #endif |
| 2274 | fdevent_process(); |
| 2275 | |
| 2276 | while((fde = fdevent_plist_dequeue())) { |
| 2277 | unsigned events = fde->events; |
| 2278 | fde->events = 0; |
| 2279 | fde->state &= (~FDE_PENDING); |
| 2280 | dump_fde(fde, "callback"); |
| 2281 | fde->func(fde->fd, events, fde->arg); |
| 2282 | } |
| 2283 | } |
| 2284 | } |
| 2285 | |
| 2286 | /** FILE EVENT HOOKS |
| 2287 | **/ |
David 'Digit' Turner | 1f1efb5 | 2009-05-18 17:36:28 +0200 | [diff] [blame] | 2288 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2289 | static void _event_file_prepare( EventHook hook ) |
| 2290 | { |
| 2291 | if (hook->wanted & (FDE_READ|FDE_WRITE)) { |
| 2292 | /* we can always read/write */ |
| 2293 | hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE); |
| 2294 | } |
| 2295 | } |
| 2296 | |
| 2297 | static int _event_file_peek( EventHook hook ) |
| 2298 | { |
| 2299 | return (hook->wanted & (FDE_READ|FDE_WRITE)); |
| 2300 | } |
| 2301 | |
| 2302 | static void _fh_file_hook( FH f, int events, EventHook hook ) |
| 2303 | { |
| 2304 | hook->h = f->fh_handle; |
| 2305 | hook->prepare = _event_file_prepare; |
| 2306 | hook->peek = _event_file_peek; |
| 2307 | } |
| 2308 | |
| 2309 | /** SOCKET EVENT HOOKS |
| 2310 | **/ |
| 2311 | |
| 2312 | static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts ) |
| 2313 | { |
| 2314 | if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) { |
| 2315 | if (hook->wanted & FDE_READ) |
| 2316 | hook->ready |= FDE_READ; |
| 2317 | if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR) |
| 2318 | hook->ready |= FDE_ERROR; |
| 2319 | } |
| 2320 | if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) { |
| 2321 | if (hook->wanted & FDE_WRITE) |
| 2322 | hook->ready |= FDE_WRITE; |
| 2323 | if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR) |
| 2324 | hook->ready |= FDE_ERROR; |
| 2325 | } |
| 2326 | if ( evts->lNetworkEvents & FD_OOB ) { |
| 2327 | if (hook->wanted & FDE_ERROR) |
| 2328 | hook->ready |= FDE_ERROR; |
| 2329 | } |
| 2330 | } |
| 2331 | |
| 2332 | static void _event_socket_prepare( EventHook hook ) |
| 2333 | { |
| 2334 | WSANETWORKEVENTS evts; |
| 2335 | |
| 2336 | /* look if some of the events we want already happened ? */ |
| 2337 | if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts )) |
| 2338 | _event_socket_verify( hook, &evts ); |
| 2339 | } |
| 2340 | |
| 2341 | static int _socket_wanted_to_flags( int wanted ) |
| 2342 | { |
| 2343 | int flags = 0; |
| 2344 | if (wanted & FDE_READ) |
| 2345 | flags |= FD_READ | FD_ACCEPT | FD_CLOSE; |
| 2346 | |
| 2347 | if (wanted & FDE_WRITE) |
| 2348 | flags |= FD_WRITE | FD_CONNECT | FD_CLOSE; |
| 2349 | |
| 2350 | if (wanted & FDE_ERROR) |
| 2351 | flags |= FD_OOB; |
| 2352 | |
| 2353 | return flags; |
| 2354 | } |
| 2355 | |
| 2356 | static int _event_socket_start( EventHook hook ) |
| 2357 | { |
| 2358 | /* create an event which we're going to wait for */ |
| 2359 | FH fh = hook->fh; |
| 2360 | long flags = _socket_wanted_to_flags( hook->wanted ); |
| 2361 | |
| 2362 | hook->h = fh->event; |
| 2363 | if (hook->h == INVALID_HANDLE_VALUE) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2364 | D( "_event_socket_start: no event for %s", fh->name ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2365 | return 0; |
| 2366 | } |
| 2367 | |
| 2368 | if ( flags != fh->mask ) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2369 | D( "_event_socket_start: hooking %s for %x (flags %ld)", hook->fh->name, hook->wanted, flags ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2370 | if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2371 | D( "_event_socket_start: WSAEventSelect() for %s failed, error %d", hook->fh->name, WSAGetLastError() ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2372 | CloseHandle( hook->h ); |
| 2373 | hook->h = INVALID_HANDLE_VALUE; |
| 2374 | exit(1); |
| 2375 | return 0; |
| 2376 | } |
| 2377 | fh->mask = flags; |
| 2378 | } |
| 2379 | return 1; |
| 2380 | } |
| 2381 | |
| 2382 | static void _event_socket_stop( EventHook hook ) |
| 2383 | { |
| 2384 | hook->h = INVALID_HANDLE_VALUE; |
| 2385 | } |
| 2386 | |
| 2387 | static int _event_socket_check( EventHook hook ) |
| 2388 | { |
| 2389 | int result = 0; |
| 2390 | FH fh = hook->fh; |
| 2391 | WSANETWORKEVENTS evts; |
| 2392 | |
| 2393 | if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) { |
| 2394 | _event_socket_verify( hook, &evts ); |
| 2395 | result = (hook->ready != 0); |
| 2396 | if (result) { |
| 2397 | ResetEvent( hook->h ); |
| 2398 | } |
| 2399 | } |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2400 | D( "_event_socket_check %s returns %d", fh->name, result ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2401 | return result; |
| 2402 | } |
| 2403 | |
| 2404 | static int _event_socket_peek( EventHook hook ) |
| 2405 | { |
| 2406 | WSANETWORKEVENTS evts; |
| 2407 | FH fh = hook->fh; |
| 2408 | |
| 2409 | /* look if some of the events we want already happened ? */ |
| 2410 | if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) { |
| 2411 | _event_socket_verify( hook, &evts ); |
| 2412 | if (hook->ready) |
| 2413 | ResetEvent( hook->h ); |
| 2414 | } |
| 2415 | |
| 2416 | return hook->ready != 0; |
| 2417 | } |
| 2418 | |
| 2419 | |
| 2420 | |
| 2421 | static void _fh_socket_hook( FH f, int events, EventHook hook ) |
| 2422 | { |
| 2423 | hook->prepare = _event_socket_prepare; |
| 2424 | hook->start = _event_socket_start; |
| 2425 | hook->stop = _event_socket_stop; |
| 2426 | hook->check = _event_socket_check; |
| 2427 | hook->peek = _event_socket_peek; |
| 2428 | |
Spencer Low | 753d485 | 2015-07-30 23:07:55 -0700 | [diff] [blame] | 2429 | // TODO: check return value? |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2430 | _event_socket_start( hook ); |
| 2431 | } |
| 2432 | |
| 2433 | /** SOCKETPAIR EVENT HOOKS |
| 2434 | **/ |
| 2435 | |
| 2436 | static void _event_socketpair_prepare( EventHook hook ) |
| 2437 | { |
| 2438 | FH fh = hook->fh; |
| 2439 | SocketPair pair = fh->fh_pair; |
| 2440 | BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip; |
| 2441 | BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip; |
| 2442 | |
| 2443 | if (hook->wanted & FDE_READ && rbip->can_read) |
| 2444 | hook->ready |= FDE_READ; |
| 2445 | |
Vladimir Chtchetkine | b87b828 | 2011-11-30 10:20:27 -0800 | [diff] [blame] | 2446 | if (hook->wanted & FDE_WRITE && wbip->can_write) |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2447 | hook->ready |= FDE_WRITE; |
| 2448 | } |
| 2449 | |
| 2450 | static int _event_socketpair_start( EventHook hook ) |
| 2451 | { |
| 2452 | FH fh = hook->fh; |
| 2453 | SocketPair pair = fh->fh_pair; |
| 2454 | BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip; |
| 2455 | BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip; |
| 2456 | |
| 2457 | if (hook->wanted == FDE_READ) |
| 2458 | hook->h = rbip->evt_read; |
| 2459 | |
| 2460 | else if (hook->wanted == FDE_WRITE) |
| 2461 | hook->h = wbip->evt_write; |
| 2462 | |
| 2463 | else { |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2464 | D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE" ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2465 | return 0; |
| 2466 | } |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 2467 | D( "_event_socketpair_start: hook %s for %x wanted=%x", |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2468 | hook->fh->name, _fh_to_int(fh), hook->wanted); |
| 2469 | return 1; |
| 2470 | } |
| 2471 | |
| 2472 | static int _event_socketpair_peek( EventHook hook ) |
| 2473 | { |
| 2474 | _event_socketpair_prepare( hook ); |
| 2475 | return hook->ready != 0; |
| 2476 | } |
| 2477 | |
| 2478 | static void _fh_socketpair_hook( FH fh, int events, EventHook hook ) |
| 2479 | { |
| 2480 | hook->prepare = _event_socketpair_prepare; |
| 2481 | hook->start = _event_socketpair_start; |
| 2482 | hook->peek = _event_socketpair_peek; |
| 2483 | } |
| 2484 | |
| 2485 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 2486 | static adb_mutex_t g_console_output_buffer_lock; |
| 2487 | |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2488 | void |
| 2489 | adb_sysdeps_init( void ) |
| 2490 | { |
| 2491 | #define ADB_MUTEX(x) InitializeCriticalSection( & x ); |
| 2492 | #include "mutex_list.h" |
| 2493 | InitializeCriticalSection( &_win32_lock ); |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 2494 | InitializeCriticalSection( &g_console_output_buffer_lock ); |
The Android Open Source Project | 9ca14dc | 2009-03-03 19:32:55 -0800 | [diff] [blame] | 2495 | } |
| 2496 | |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2497 | /**************************************************************************/ |
| 2498 | /**************************************************************************/ |
| 2499 | /***** *****/ |
| 2500 | /***** Console Window Terminal Emulation *****/ |
| 2501 | /***** *****/ |
| 2502 | /**************************************************************************/ |
| 2503 | /**************************************************************************/ |
| 2504 | |
| 2505 | // This reads input from a Win32 console window and translates it into Unix |
| 2506 | // terminal-style sequences. This emulates mostly Gnome Terminal (in Normal |
| 2507 | // mode, not Application mode), which itself emulates xterm. Gnome Terminal |
| 2508 | // is emulated instead of xterm because it is probably more popular than xterm: |
| 2509 | // Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal |
| 2510 | // supports modern fonts, etc. It seems best to emulate the terminal that most |
| 2511 | // Android developers use because they'll fix apps (the shell, etc.) to keep |
| 2512 | // working with that terminal's emulation. |
| 2513 | // |
| 2514 | // The point of this emulation is not to be perfect or to solve all issues with |
| 2515 | // console windows on Windows, but to be better than the original code which |
| 2516 | // just called read() (which called ReadFile(), which called ReadConsoleA()) |
| 2517 | // which did not support Ctrl-C, tab completion, shell input line editing |
| 2518 | // keys, server echo, and more. |
| 2519 | // |
| 2520 | // This implementation reconfigures the console with SetConsoleMode(), then |
| 2521 | // calls ReadConsoleInput() to get raw input which it remaps to Unix |
| 2522 | // terminal-style sequences which is returned via unix_read() which is used |
| 2523 | // by the 'adb shell' command. |
| 2524 | // |
| 2525 | // Code organization: |
| 2526 | // |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 2527 | // * _get_console_handle() and unix_isatty() provide console information. |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2528 | // * stdin_raw_init() and stdin_raw_restore() reconfigure the console. |
| 2529 | // * unix_read() detects console windows (as opposed to pipes, files, etc.). |
| 2530 | // * _console_read() is the main code of the emulation. |
| 2531 | |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 2532 | // Returns a console HANDLE if |fd| is a console, otherwise returns nullptr. |
| 2533 | // If a valid HANDLE is returned and |mode| is not null, |mode| is also filled |
| 2534 | // with the console mode. Requires GENERIC_READ access to the underlying HANDLE. |
| 2535 | static HANDLE _get_console_handle(int fd, DWORD* mode=nullptr) { |
| 2536 | // First check isatty(); this is very fast and eliminates most non-console |
| 2537 | // FDs, but returns 1 for both consoles and character devices like NUL. |
| 2538 | #pragma push_macro("isatty") |
| 2539 | #undef isatty |
| 2540 | if (!isatty(fd)) { |
| 2541 | return nullptr; |
| 2542 | } |
| 2543 | #pragma pop_macro("isatty") |
| 2544 | |
| 2545 | // To differentiate between character devices and consoles we need to get |
| 2546 | // the underlying HANDLE and use GetConsoleMode(), which is what requires |
| 2547 | // GENERIC_READ permissions. |
| 2548 | const intptr_t intptr_handle = _get_osfhandle(fd); |
| 2549 | if (intptr_handle == -1) { |
| 2550 | return nullptr; |
| 2551 | } |
| 2552 | const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle); |
| 2553 | DWORD temp_mode = 0; |
| 2554 | if (!GetConsoleMode(handle, mode ? mode : &temp_mode)) { |
| 2555 | return nullptr; |
| 2556 | } |
| 2557 | |
| 2558 | return handle; |
| 2559 | } |
| 2560 | |
| 2561 | // Returns a console handle if |stream| is a console, otherwise returns nullptr. |
| 2562 | static HANDLE _get_console_handle(FILE* const stream) { |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 2563 | // Save and restore errno to make it easier for callers to prevent from overwriting errno. |
| 2564 | android::base::ErrnoRestorer er; |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 2565 | const int fd = fileno(stream); |
| 2566 | if (fd < 0) { |
| 2567 | return nullptr; |
| 2568 | } |
| 2569 | return _get_console_handle(fd); |
| 2570 | } |
| 2571 | |
| 2572 | int unix_isatty(int fd) { |
| 2573 | return _get_console_handle(fd) ? 1 : 0; |
| 2574 | } |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2575 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2576 | // Get the next KEY_EVENT_RECORD that should be processed. |
| 2577 | 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] | 2578 | for (;;) { |
| 2579 | DWORD read_count = 0; |
| 2580 | memset(input_record, 0, sizeof(*input_record)); |
| 2581 | if (!ReadConsoleInputA(console, input_record, 1, &read_count)) { |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2582 | D("_get_key_event_record: ReadConsoleInputA() failed: %s\n", |
| 2583 | SystemErrorCodeToString(GetLastError()).c_str()); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2584 | errno = EIO; |
| 2585 | return false; |
| 2586 | } |
| 2587 | |
| 2588 | if (read_count == 0) { // should be impossible |
| 2589 | fatal("ReadConsoleInputA returned 0"); |
| 2590 | } |
| 2591 | |
| 2592 | if (read_count != 1) { // should be impossible |
| 2593 | fatal("ReadConsoleInputA did not return one input record"); |
| 2594 | } |
| 2595 | |
| 2596 | if ((input_record->EventType == KEY_EVENT) && |
| 2597 | (input_record->Event.KeyEvent.bKeyDown)) { |
| 2598 | if (input_record->Event.KeyEvent.wRepeatCount == 0) { |
| 2599 | fatal("ReadConsoleInputA returned a key event with zero repeat" |
| 2600 | " count"); |
| 2601 | } |
| 2602 | |
| 2603 | // Got an interesting INPUT_RECORD, so return |
| 2604 | return true; |
| 2605 | } |
| 2606 | } |
| 2607 | } |
| 2608 | |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2609 | static __inline__ bool _is_shift_pressed(const DWORD control_key_state) { |
| 2610 | return (control_key_state & SHIFT_PRESSED) != 0; |
| 2611 | } |
| 2612 | |
| 2613 | static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) { |
| 2614 | return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0; |
| 2615 | } |
| 2616 | |
| 2617 | static __inline__ bool _is_alt_pressed(const DWORD control_key_state) { |
| 2618 | return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0; |
| 2619 | } |
| 2620 | |
| 2621 | static __inline__ bool _is_numlock_on(const DWORD control_key_state) { |
| 2622 | return (control_key_state & NUMLOCK_ON) != 0; |
| 2623 | } |
| 2624 | |
| 2625 | static __inline__ bool _is_capslock_on(const DWORD control_key_state) { |
| 2626 | return (control_key_state & CAPSLOCK_ON) != 0; |
| 2627 | } |
| 2628 | |
| 2629 | static __inline__ bool _is_enhanced_key(const DWORD control_key_state) { |
| 2630 | return (control_key_state & ENHANCED_KEY) != 0; |
| 2631 | } |
| 2632 | |
| 2633 | // Constants from MSDN for ToAscii(). |
| 2634 | static const BYTE TOASCII_KEY_OFF = 0x00; |
| 2635 | static const BYTE TOASCII_KEY_DOWN = 0x80; |
| 2636 | static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock |
| 2637 | |
| 2638 | // Given a key event, ignore a modifier key and return the character that was |
| 2639 | // entered without the modifier. Writes to *ch and returns the number of bytes |
| 2640 | // written. |
| 2641 | static size_t _get_char_ignoring_modifier(char* const ch, |
| 2642 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state, |
| 2643 | const WORD modifier) { |
| 2644 | // If there is no character from Windows, try ignoring the specified |
| 2645 | // modifier and look for a character. Note that if AltGr is being used, |
| 2646 | // there will be a character from Windows. |
| 2647 | if (key_event->uChar.AsciiChar == '\0') { |
| 2648 | // Note that we read the control key state from the passed in argument |
| 2649 | // instead of from key_event since the argument has been normalized. |
| 2650 | if (((modifier == VK_SHIFT) && |
| 2651 | _is_shift_pressed(control_key_state)) || |
| 2652 | ((modifier == VK_CONTROL) && |
| 2653 | _is_ctrl_pressed(control_key_state)) || |
| 2654 | ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) { |
| 2655 | |
| 2656 | BYTE key_state[256] = {0}; |
| 2657 | key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ? |
| 2658 | TOASCII_KEY_DOWN : TOASCII_KEY_OFF; |
| 2659 | key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ? |
| 2660 | TOASCII_KEY_DOWN : TOASCII_KEY_OFF; |
| 2661 | key_state[VK_MENU] = _is_alt_pressed(control_key_state) ? |
| 2662 | TOASCII_KEY_DOWN : TOASCII_KEY_OFF; |
| 2663 | key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ? |
| 2664 | TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF; |
| 2665 | |
| 2666 | // cause this modifier to be ignored |
| 2667 | key_state[modifier] = TOASCII_KEY_OFF; |
| 2668 | |
| 2669 | WORD translated = 0; |
| 2670 | if (ToAscii(key_event->wVirtualKeyCode, |
| 2671 | key_event->wVirtualScanCode, key_state, &translated, 0) == 1) { |
| 2672 | // Ignoring the modifier, we found a character. |
| 2673 | *ch = (CHAR)translated; |
| 2674 | return 1; |
| 2675 | } |
| 2676 | } |
| 2677 | } |
| 2678 | |
| 2679 | // Just use whatever Windows told us originally. |
| 2680 | *ch = key_event->uChar.AsciiChar; |
| 2681 | |
| 2682 | // If the character from Windows is NULL, return a size of zero. |
| 2683 | return (*ch == '\0') ? 0 : 1; |
| 2684 | } |
| 2685 | |
| 2686 | // If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key, |
| 2687 | // but taking into account the shift key. This is because for a sequence like |
| 2688 | // Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0, |
| 2689 | // we want to find the character ')'. |
| 2690 | // |
| 2691 | // Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0 |
| 2692 | // because it is the default key-sequence to switch the input language. |
| 2693 | // This is configurable in the Region and Language control panel. |
| 2694 | static __inline__ size_t _get_non_control_char(char* const ch, |
| 2695 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) { |
| 2696 | return _get_char_ignoring_modifier(ch, key_event, control_key_state, |
| 2697 | VK_CONTROL); |
| 2698 | } |
| 2699 | |
| 2700 | // Get without Alt. |
| 2701 | static __inline__ size_t _get_non_alt_char(char* const ch, |
| 2702 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) { |
| 2703 | return _get_char_ignoring_modifier(ch, key_event, control_key_state, |
| 2704 | VK_MENU); |
| 2705 | } |
| 2706 | |
| 2707 | // Ignore the control key, find the character from Windows, and apply any |
| 2708 | // Control key mappings (for example, Ctrl-2 is a NULL character). Writes to |
| 2709 | // *pch and returns number of bytes written. |
| 2710 | static size_t _get_control_character(char* const pch, |
| 2711 | const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) { |
| 2712 | const size_t len = _get_non_control_char(pch, key_event, |
| 2713 | control_key_state); |
| 2714 | |
| 2715 | if ((len == 1) && _is_ctrl_pressed(control_key_state)) { |
| 2716 | char ch = *pch; |
| 2717 | switch (ch) { |
| 2718 | case '2': |
| 2719 | case '@': |
| 2720 | case '`': |
| 2721 | ch = '\0'; |
| 2722 | break; |
| 2723 | case '3': |
| 2724 | case '[': |
| 2725 | case '{': |
| 2726 | ch = '\x1b'; |
| 2727 | break; |
| 2728 | case '4': |
| 2729 | case '\\': |
| 2730 | case '|': |
| 2731 | ch = '\x1c'; |
| 2732 | break; |
| 2733 | case '5': |
| 2734 | case ']': |
| 2735 | case '}': |
| 2736 | ch = '\x1d'; |
| 2737 | break; |
| 2738 | case '6': |
| 2739 | case '^': |
| 2740 | case '~': |
| 2741 | ch = '\x1e'; |
| 2742 | break; |
| 2743 | case '7': |
| 2744 | case '-': |
| 2745 | case '_': |
| 2746 | ch = '\x1f'; |
| 2747 | break; |
| 2748 | case '8': |
| 2749 | ch = '\x7f'; |
| 2750 | break; |
| 2751 | case '/': |
| 2752 | if (!_is_alt_pressed(control_key_state)) { |
| 2753 | ch = '\x1f'; |
| 2754 | } |
| 2755 | break; |
| 2756 | case '?': |
| 2757 | if (!_is_alt_pressed(control_key_state)) { |
| 2758 | ch = '\x7f'; |
| 2759 | } |
| 2760 | break; |
| 2761 | } |
| 2762 | *pch = ch; |
| 2763 | } |
| 2764 | |
| 2765 | return len; |
| 2766 | } |
| 2767 | |
| 2768 | static DWORD _normalize_altgr_control_key_state( |
| 2769 | const KEY_EVENT_RECORD* const key_event) { |
| 2770 | DWORD control_key_state = key_event->dwControlKeyState; |
| 2771 | |
| 2772 | // If we're in an AltGr situation where the AltGr key is down (depending on |
| 2773 | // the keyboard layout, that might be the physical right alt key which |
| 2774 | // produces a control_key_state where Right-Alt and Left-Ctrl are down) or |
| 2775 | // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have |
| 2776 | // a character (which indicates that there was an AltGr mapping), then act |
| 2777 | // as if alt and control are not really down for the purposes of modifiers. |
| 2778 | // This makes it so that if the user with, say, a German keyboard layout |
| 2779 | // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just |
| 2780 | // output the key and we don't see the Alt and Ctrl keys. |
| 2781 | if (_is_ctrl_pressed(control_key_state) && |
| 2782 | _is_alt_pressed(control_key_state) |
| 2783 | && (key_event->uChar.AsciiChar != '\0')) { |
| 2784 | // Try to remove as few bits as possible to improve our chances of |
| 2785 | // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or |
| 2786 | // Left-Alt + Right-Ctrl + AltGr. |
| 2787 | if ((control_key_state & RIGHT_ALT_PRESSED) != 0) { |
| 2788 | // Remove Right-Alt. |
| 2789 | control_key_state &= ~RIGHT_ALT_PRESSED; |
| 2790 | // If uChar is set, a Ctrl key is pressed, and Right-Alt is |
| 2791 | // pressed, Left-Ctrl is almost always set, except if the user |
| 2792 | // presses Right-Ctrl, then AltGr (in that specific order) for |
| 2793 | // whatever reason. At any rate, make sure the bit is not set. |
| 2794 | control_key_state &= ~LEFT_CTRL_PRESSED; |
| 2795 | } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) { |
| 2796 | // Remove Left-Alt. |
| 2797 | control_key_state &= ~LEFT_ALT_PRESSED; |
| 2798 | // Whichever Ctrl key is down, remove it from the state. We only |
| 2799 | // remove one key, to improve our chances of detecting the |
| 2800 | // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl. |
| 2801 | if ((control_key_state & LEFT_CTRL_PRESSED) != 0) { |
| 2802 | // Remove Left-Ctrl. |
| 2803 | control_key_state &= ~LEFT_CTRL_PRESSED; |
| 2804 | } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) { |
| 2805 | // Remove Right-Ctrl. |
| 2806 | control_key_state &= ~RIGHT_CTRL_PRESSED; |
| 2807 | } |
| 2808 | } |
| 2809 | |
| 2810 | // Note that this logic isn't 100% perfect because Windows doesn't |
| 2811 | // allow us to detect all combinations because a physical AltGr key |
| 2812 | // press shows up as two bits, plus some combinations are ambiguous |
| 2813 | // about what is actually physically pressed. |
| 2814 | } |
| 2815 | |
| 2816 | return control_key_state; |
| 2817 | } |
| 2818 | |
| 2819 | // If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in |
| 2820 | // dwControlKeyState for the following keypad keys: period, 0-9. If we detect |
| 2821 | // this scenario, set the SHIFT_PRESSED bit so we can add modifiers |
| 2822 | // appropriately. |
| 2823 | static DWORD _normalize_keypad_control_key_state(const WORD vk, |
| 2824 | const DWORD control_key_state) { |
| 2825 | if (!_is_numlock_on(control_key_state)) { |
| 2826 | return control_key_state; |
| 2827 | } |
| 2828 | if (!_is_enhanced_key(control_key_state)) { |
| 2829 | switch (vk) { |
| 2830 | case VK_INSERT: // 0 |
| 2831 | case VK_DELETE: // . |
| 2832 | case VK_END: // 1 |
| 2833 | case VK_DOWN: // 2 |
| 2834 | case VK_NEXT: // 3 |
| 2835 | case VK_LEFT: // 4 |
| 2836 | case VK_CLEAR: // 5 |
| 2837 | case VK_RIGHT: // 6 |
| 2838 | case VK_HOME: // 7 |
| 2839 | case VK_UP: // 8 |
| 2840 | case VK_PRIOR: // 9 |
| 2841 | return control_key_state | SHIFT_PRESSED; |
| 2842 | } |
| 2843 | } |
| 2844 | |
| 2845 | return control_key_state; |
| 2846 | } |
| 2847 | |
| 2848 | static const char* _get_keypad_sequence(const DWORD control_key_state, |
| 2849 | const char* const normal, const char* const shifted) { |
| 2850 | if (_is_shift_pressed(control_key_state)) { |
| 2851 | // Shift is pressed and NumLock is off |
| 2852 | return shifted; |
| 2853 | } else { |
| 2854 | // Shift is not pressed and NumLock is off, or, |
| 2855 | // Shift is pressed and NumLock is on, in which case we want the |
| 2856 | // NumLock and Shift to neutralize each other, thus, we want the normal |
| 2857 | // sequence. |
| 2858 | return normal; |
| 2859 | } |
| 2860 | // If Shift is not pressed and NumLock is on, a different virtual key code |
| 2861 | // is returned by Windows, which can be taken care of by a different case |
| 2862 | // statement in _console_read(). |
| 2863 | } |
| 2864 | |
| 2865 | // Write sequence to buf and return the number of bytes written. |
| 2866 | static size_t _get_modifier_sequence(char* const buf, const WORD vk, |
| 2867 | DWORD control_key_state, const char* const normal) { |
| 2868 | // Copy the base sequence into buf. |
| 2869 | const size_t len = strlen(normal); |
| 2870 | memcpy(buf, normal, len); |
| 2871 | |
| 2872 | int code = 0; |
| 2873 | |
| 2874 | control_key_state = _normalize_keypad_control_key_state(vk, |
| 2875 | control_key_state); |
| 2876 | |
| 2877 | if (_is_shift_pressed(control_key_state)) { |
| 2878 | code |= 0x1; |
| 2879 | } |
| 2880 | if (_is_alt_pressed(control_key_state)) { // any alt key pressed |
| 2881 | code |= 0x2; |
| 2882 | } |
| 2883 | if (_is_ctrl_pressed(control_key_state)) { // any control key pressed |
| 2884 | code |= 0x4; |
| 2885 | } |
| 2886 | // If some modifier was held down, then we need to insert the modifier code |
| 2887 | if (code != 0) { |
| 2888 | if (len == 0) { |
| 2889 | // Should be impossible because caller should pass a string of |
| 2890 | // non-zero length. |
| 2891 | return 0; |
| 2892 | } |
| 2893 | size_t index = len - 1; |
| 2894 | const char lastChar = buf[index]; |
| 2895 | if (lastChar != '~') { |
| 2896 | buf[index++] = '1'; |
| 2897 | } |
| 2898 | buf[index++] = ';'; // modifier separator |
| 2899 | // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control, |
| 2900 | // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control |
| 2901 | buf[index++] = '1' + code; |
| 2902 | buf[index++] = lastChar; // move ~ (or other last char) to the end |
| 2903 | return index; |
| 2904 | } |
| 2905 | return len; |
| 2906 | } |
| 2907 | |
| 2908 | // Write sequence to buf and return the number of bytes written. |
| 2909 | static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk, |
| 2910 | const DWORD control_key_state, const char* const normal, |
| 2911 | const char shifted) { |
| 2912 | if (_is_shift_pressed(control_key_state)) { |
| 2913 | // Shift is pressed and NumLock is off |
| 2914 | if (shifted != '\0') { |
| 2915 | buf[0] = shifted; |
| 2916 | return sizeof(buf[0]); |
| 2917 | } else { |
| 2918 | return 0; |
| 2919 | } |
| 2920 | } else { |
| 2921 | // Shift is not pressed and NumLock is off, or, |
| 2922 | // Shift is pressed and NumLock is on, in which case we want the |
| 2923 | // NumLock and Shift to neutralize each other, thus, we want the normal |
| 2924 | // sequence. |
| 2925 | return _get_modifier_sequence(buf, vk, control_key_state, normal); |
| 2926 | } |
| 2927 | // If Shift is not pressed and NumLock is on, a different virtual key code |
| 2928 | // is returned by Windows, which can be taken care of by a different case |
| 2929 | // statement in _console_read(). |
| 2930 | } |
| 2931 | |
| 2932 | // The decimal key on the keypad produces a '.' for U.S. English and a ',' for |
| 2933 | // Standard German. Figure this out at runtime so we know what to output for |
| 2934 | // Shift-VK_DELETE. |
| 2935 | static char _get_decimal_char() { |
| 2936 | return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR); |
| 2937 | } |
| 2938 | |
| 2939 | // Prefix the len bytes in buf with the escape character, and then return the |
| 2940 | // new buffer length. |
| 2941 | size_t _escape_prefix(char* const buf, const size_t len) { |
| 2942 | // If nothing to prefix, don't do anything. We might be called with |
| 2943 | // len == 0, if alt was held down with a dead key which produced nothing. |
| 2944 | if (len == 0) { |
| 2945 | return 0; |
| 2946 | } |
| 2947 | |
| 2948 | memmove(&buf[1], buf, len); |
| 2949 | buf[0] = '\x1b'; |
| 2950 | return len + 1; |
| 2951 | } |
| 2952 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2953 | // Internal buffer to satisfy future _console_read() calls. |
Josh Gao | e3a87d0 | 2015-11-11 17:56:12 -0800 | [diff] [blame] | 2954 | static auto& g_console_input_buffer = *new std::vector<char>(); |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2955 | |
| 2956 | // Writes to buffer buf (of length len), returning number of bytes written or -1 on error. Never |
| 2957 | // 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] | 2958 | static int _console_read(const HANDLE console, void* buf, size_t len) { |
| 2959 | for (;;) { |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2960 | // Read of zero bytes should not block waiting for something from the console. |
| 2961 | if (len == 0) { |
| 2962 | return 0; |
| 2963 | } |
| 2964 | |
| 2965 | // Flush as much as possible from input buffer. |
| 2966 | if (!g_console_input_buffer.empty()) { |
| 2967 | const int bytes_read = std::min(len, g_console_input_buffer.size()); |
| 2968 | memcpy(buf, g_console_input_buffer.data(), bytes_read); |
| 2969 | const auto begin = g_console_input_buffer.begin(); |
| 2970 | g_console_input_buffer.erase(begin, begin + bytes_read); |
| 2971 | return bytes_read; |
| 2972 | } |
| 2973 | |
| 2974 | // Read from the actual console. This may block until input. |
| 2975 | INPUT_RECORD input_record; |
| 2976 | if (!_get_key_event_record(console, &input_record)) { |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2977 | return -1; |
| 2978 | } |
| 2979 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 2980 | KEY_EVENT_RECORD* const key_event = &input_record.Event.KeyEvent; |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 2981 | const WORD vk = key_event->wVirtualKeyCode; |
| 2982 | const CHAR ch = key_event->uChar.AsciiChar; |
| 2983 | const DWORD control_key_state = _normalize_altgr_control_key_state( |
| 2984 | key_event); |
| 2985 | |
| 2986 | // The following emulation code should write the output sequence to |
| 2987 | // either seqstr or to seqbuf and seqbuflen. |
| 2988 | const char* seqstr = NULL; // NULL terminated C-string |
| 2989 | // Enough space for max sequence string below, plus modifiers and/or |
| 2990 | // escape prefix. |
| 2991 | char seqbuf[16]; |
| 2992 | size_t seqbuflen = 0; // Space used in seqbuf. |
| 2993 | |
| 2994 | #define MATCH(vk, normal) \ |
| 2995 | case (vk): \ |
| 2996 | { \ |
| 2997 | seqstr = (normal); \ |
| 2998 | } \ |
| 2999 | break; |
| 3000 | |
| 3001 | // Modifier keys should affect the output sequence. |
| 3002 | #define MATCH_MODIFIER(vk, normal) \ |
| 3003 | case (vk): \ |
| 3004 | { \ |
| 3005 | seqbuflen = _get_modifier_sequence(seqbuf, (vk), \ |
| 3006 | control_key_state, (normal)); \ |
| 3007 | } \ |
| 3008 | break; |
| 3009 | |
| 3010 | // The shift key should affect the output sequence. |
| 3011 | #define MATCH_KEYPAD(vk, normal, shifted) \ |
| 3012 | case (vk): \ |
| 3013 | { \ |
| 3014 | seqstr = _get_keypad_sequence(control_key_state, (normal), \ |
| 3015 | (shifted)); \ |
| 3016 | } \ |
| 3017 | break; |
| 3018 | |
| 3019 | // The shift key and other modifier keys should affect the output |
| 3020 | // sequence. |
| 3021 | #define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \ |
| 3022 | case (vk): \ |
| 3023 | { \ |
| 3024 | seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \ |
| 3025 | control_key_state, (normal), (shifted)); \ |
| 3026 | } \ |
| 3027 | break; |
| 3028 | |
| 3029 | #define ESC "\x1b" |
| 3030 | #define CSI ESC "[" |
| 3031 | #define SS3 ESC "O" |
| 3032 | |
| 3033 | // Only support normal mode, not application mode. |
| 3034 | |
| 3035 | // Enhanced keys: |
| 3036 | // * 6-pack: insert, delete, home, end, page up, page down |
| 3037 | // * cursor keys: up, down, right, left |
| 3038 | // * keypad: divide, enter |
| 3039 | // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT, |
| 3040 | // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK |
| 3041 | if (_is_enhanced_key(control_key_state)) { |
| 3042 | switch (vk) { |
| 3043 | case VK_RETURN: // Enter key on keypad |
| 3044 | if (_is_ctrl_pressed(control_key_state)) { |
| 3045 | seqstr = "\n"; |
| 3046 | } else { |
| 3047 | seqstr = "\r"; |
| 3048 | } |
| 3049 | break; |
| 3050 | |
| 3051 | MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up |
| 3052 | MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down |
| 3053 | |
| 3054 | // gnome-terminal currently sends SS3 "F" and SS3 "H", but that |
| 3055 | // will be fixed soon to match xterm which sends CSI "F" and |
| 3056 | // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764 |
| 3057 | MATCH(VK_END, CSI "F"); |
| 3058 | MATCH(VK_HOME, CSI "H"); |
| 3059 | |
| 3060 | MATCH_MODIFIER(VK_LEFT, CSI "D"); |
| 3061 | MATCH_MODIFIER(VK_UP, CSI "A"); |
| 3062 | MATCH_MODIFIER(VK_RIGHT, CSI "C"); |
| 3063 | MATCH_MODIFIER(VK_DOWN, CSI "B"); |
| 3064 | |
| 3065 | MATCH_MODIFIER(VK_INSERT, CSI "2~"); |
| 3066 | MATCH_MODIFIER(VK_DELETE, CSI "3~"); |
| 3067 | |
| 3068 | MATCH(VK_DIVIDE, "/"); |
| 3069 | } |
| 3070 | } else { // Non-enhanced keys: |
| 3071 | switch (vk) { |
| 3072 | case VK_BACK: // backspace |
| 3073 | if (_is_alt_pressed(control_key_state)) { |
| 3074 | seqstr = ESC "\x7f"; |
| 3075 | } else { |
| 3076 | seqstr = "\x7f"; |
| 3077 | } |
| 3078 | break; |
| 3079 | |
| 3080 | case VK_TAB: |
| 3081 | if (_is_shift_pressed(control_key_state)) { |
| 3082 | seqstr = CSI "Z"; |
| 3083 | } else { |
| 3084 | seqstr = "\t"; |
| 3085 | } |
| 3086 | break; |
| 3087 | |
| 3088 | // Number 5 key in keypad when NumLock is off, or if NumLock is |
| 3089 | // on and Shift is down. |
| 3090 | MATCH_KEYPAD(VK_CLEAR, CSI "E", "5"); |
| 3091 | |
| 3092 | case VK_RETURN: // Enter key on main keyboard |
| 3093 | if (_is_alt_pressed(control_key_state)) { |
| 3094 | seqstr = ESC "\n"; |
| 3095 | } else if (_is_ctrl_pressed(control_key_state)) { |
| 3096 | seqstr = "\n"; |
| 3097 | } else { |
| 3098 | seqstr = "\r"; |
| 3099 | } |
| 3100 | break; |
| 3101 | |
| 3102 | // VK_ESCAPE: Don't do any special handling. The OS uses many |
| 3103 | // of the sequences with Escape and many of the remaining |
| 3104 | // sequences don't produce bKeyDown messages, only !bKeyDown |
| 3105 | // for whatever reason. |
| 3106 | |
| 3107 | case VK_SPACE: |
| 3108 | if (_is_alt_pressed(control_key_state)) { |
| 3109 | seqstr = ESC " "; |
| 3110 | } else if (_is_ctrl_pressed(control_key_state)) { |
| 3111 | seqbuf[0] = '\0'; // NULL char |
| 3112 | seqbuflen = 1; |
| 3113 | } else { |
| 3114 | seqstr = " "; |
| 3115 | } |
| 3116 | break; |
| 3117 | |
| 3118 | MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up |
| 3119 | MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down |
| 3120 | |
| 3121 | MATCH_KEYPAD(VK_END, CSI "4~", "1"); |
| 3122 | MATCH_KEYPAD(VK_HOME, CSI "1~", "7"); |
| 3123 | |
| 3124 | MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4'); |
| 3125 | MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8'); |
| 3126 | MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6'); |
| 3127 | MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2'); |
| 3128 | |
| 3129 | MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0'); |
| 3130 | MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~", |
| 3131 | _get_decimal_char()); |
| 3132 | |
| 3133 | case 0x30: // 0 |
| 3134 | case 0x31: // 1 |
| 3135 | case 0x39: // 9 |
| 3136 | case VK_OEM_1: // ;: |
| 3137 | case VK_OEM_PLUS: // =+ |
| 3138 | case VK_OEM_COMMA: // ,< |
| 3139 | case VK_OEM_PERIOD: // .> |
| 3140 | case VK_OEM_7: // '" |
| 3141 | case VK_OEM_102: // depends on keyboard, could be <> or \| |
| 3142 | case VK_OEM_2: // /? |
| 3143 | case VK_OEM_3: // `~ |
| 3144 | case VK_OEM_4: // [{ |
| 3145 | case VK_OEM_5: // \| |
| 3146 | case VK_OEM_6: // ]} |
| 3147 | { |
| 3148 | seqbuflen = _get_control_character(seqbuf, key_event, |
| 3149 | control_key_state); |
| 3150 | |
| 3151 | if (_is_alt_pressed(control_key_state)) { |
| 3152 | seqbuflen = _escape_prefix(seqbuf, seqbuflen); |
| 3153 | } |
| 3154 | } |
| 3155 | break; |
| 3156 | |
| 3157 | case 0x32: // 2 |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 3158 | case 0x33: // 3 |
| 3159 | case 0x34: // 4 |
| 3160 | case 0x35: // 5 |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3161 | case 0x36: // 6 |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 3162 | case 0x37: // 7 |
| 3163 | case 0x38: // 8 |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3164 | case VK_OEM_MINUS: // -_ |
| 3165 | { |
| 3166 | seqbuflen = _get_control_character(seqbuf, key_event, |
| 3167 | control_key_state); |
| 3168 | |
| 3169 | // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then |
| 3170 | // prefix with escape. |
| 3171 | if (_is_alt_pressed(control_key_state) && |
| 3172 | !(_is_ctrl_pressed(control_key_state) && |
| 3173 | !_is_shift_pressed(control_key_state))) { |
| 3174 | seqbuflen = _escape_prefix(seqbuf, seqbuflen); |
| 3175 | } |
| 3176 | } |
| 3177 | break; |
| 3178 | |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3179 | case 0x41: // a |
| 3180 | case 0x42: // b |
| 3181 | case 0x43: // c |
| 3182 | case 0x44: // d |
| 3183 | case 0x45: // e |
| 3184 | case 0x46: // f |
| 3185 | case 0x47: // g |
| 3186 | case 0x48: // h |
| 3187 | case 0x49: // i |
| 3188 | case 0x4a: // j |
| 3189 | case 0x4b: // k |
| 3190 | case 0x4c: // l |
| 3191 | case 0x4d: // m |
| 3192 | case 0x4e: // n |
| 3193 | case 0x4f: // o |
| 3194 | case 0x50: // p |
| 3195 | case 0x51: // q |
| 3196 | case 0x52: // r |
| 3197 | case 0x53: // s |
| 3198 | case 0x54: // t |
| 3199 | case 0x55: // u |
| 3200 | case 0x56: // v |
| 3201 | case 0x57: // w |
| 3202 | case 0x58: // x |
| 3203 | case 0x59: // y |
| 3204 | case 0x5a: // z |
| 3205 | { |
| 3206 | seqbuflen = _get_non_alt_char(seqbuf, key_event, |
| 3207 | control_key_state); |
| 3208 | |
| 3209 | // If Alt is pressed, then prefix with escape. |
| 3210 | if (_is_alt_pressed(control_key_state)) { |
| 3211 | seqbuflen = _escape_prefix(seqbuf, seqbuflen); |
| 3212 | } |
| 3213 | } |
| 3214 | break; |
| 3215 | |
| 3216 | // These virtual key codes are generated by the keys on the |
| 3217 | // keypad *when NumLock is on* and *Shift is up*. |
| 3218 | MATCH(VK_NUMPAD0, "0"); |
| 3219 | MATCH(VK_NUMPAD1, "1"); |
| 3220 | MATCH(VK_NUMPAD2, "2"); |
| 3221 | MATCH(VK_NUMPAD3, "3"); |
| 3222 | MATCH(VK_NUMPAD4, "4"); |
| 3223 | MATCH(VK_NUMPAD5, "5"); |
| 3224 | MATCH(VK_NUMPAD6, "6"); |
| 3225 | MATCH(VK_NUMPAD7, "7"); |
| 3226 | MATCH(VK_NUMPAD8, "8"); |
| 3227 | MATCH(VK_NUMPAD9, "9"); |
| 3228 | |
| 3229 | MATCH(VK_MULTIPLY, "*"); |
| 3230 | MATCH(VK_ADD, "+"); |
| 3231 | MATCH(VK_SUBTRACT, "-"); |
| 3232 | // VK_DECIMAL is generated by the . key on the keypad *when |
| 3233 | // NumLock is on* and *Shift is up* and the sequence is not |
| 3234 | // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the |
| 3235 | // Windows Security screen to come up). |
| 3236 | case VK_DECIMAL: |
| 3237 | // U.S. English uses '.', Germany German uses ','. |
| 3238 | seqbuflen = _get_non_control_char(seqbuf, key_event, |
| 3239 | control_key_state); |
| 3240 | break; |
| 3241 | |
| 3242 | MATCH_MODIFIER(VK_F1, SS3 "P"); |
| 3243 | MATCH_MODIFIER(VK_F2, SS3 "Q"); |
| 3244 | MATCH_MODIFIER(VK_F3, SS3 "R"); |
| 3245 | MATCH_MODIFIER(VK_F4, SS3 "S"); |
| 3246 | MATCH_MODIFIER(VK_F5, CSI "15~"); |
| 3247 | MATCH_MODIFIER(VK_F6, CSI "17~"); |
| 3248 | MATCH_MODIFIER(VK_F7, CSI "18~"); |
| 3249 | MATCH_MODIFIER(VK_F8, CSI "19~"); |
| 3250 | MATCH_MODIFIER(VK_F9, CSI "20~"); |
| 3251 | MATCH_MODIFIER(VK_F10, CSI "21~"); |
| 3252 | MATCH_MODIFIER(VK_F11, CSI "23~"); |
| 3253 | MATCH_MODIFIER(VK_F12, CSI "24~"); |
| 3254 | |
| 3255 | MATCH_MODIFIER(VK_F13, CSI "25~"); |
| 3256 | MATCH_MODIFIER(VK_F14, CSI "26~"); |
| 3257 | MATCH_MODIFIER(VK_F15, CSI "28~"); |
| 3258 | MATCH_MODIFIER(VK_F16, CSI "29~"); |
| 3259 | MATCH_MODIFIER(VK_F17, CSI "31~"); |
| 3260 | MATCH_MODIFIER(VK_F18, CSI "32~"); |
| 3261 | MATCH_MODIFIER(VK_F19, CSI "33~"); |
| 3262 | MATCH_MODIFIER(VK_F20, CSI "34~"); |
| 3263 | |
| 3264 | // MATCH_MODIFIER(VK_F21, ???); |
| 3265 | // MATCH_MODIFIER(VK_F22, ???); |
| 3266 | // MATCH_MODIFIER(VK_F23, ???); |
| 3267 | // MATCH_MODIFIER(VK_F24, ???); |
| 3268 | } |
| 3269 | } |
| 3270 | |
| 3271 | #undef MATCH |
| 3272 | #undef MATCH_MODIFIER |
| 3273 | #undef MATCH_KEYPAD |
| 3274 | #undef MATCH_MODIFIER_KEYPAD |
| 3275 | #undef ESC |
| 3276 | #undef CSI |
| 3277 | #undef SS3 |
| 3278 | |
| 3279 | const char* out; |
| 3280 | size_t outlen; |
| 3281 | |
| 3282 | // Check for output in any of: |
| 3283 | // * seqstr is set (and strlen can be used to determine the length). |
| 3284 | // * seqbuf and seqbuflen are set |
| 3285 | // Fallback to ch from Windows. |
| 3286 | if (seqstr != NULL) { |
| 3287 | out = seqstr; |
| 3288 | outlen = strlen(seqstr); |
| 3289 | } else if (seqbuflen > 0) { |
| 3290 | out = seqbuf; |
| 3291 | outlen = seqbuflen; |
| 3292 | } else if (ch != '\0') { |
| 3293 | // Use whatever Windows told us it is. |
| 3294 | seqbuf[0] = ch; |
| 3295 | seqbuflen = 1; |
| 3296 | out = seqbuf; |
| 3297 | outlen = seqbuflen; |
| 3298 | } else { |
| 3299 | // No special handling for the virtual key code and Windows isn't |
| 3300 | // telling us a character code, then we don't know how to translate |
| 3301 | // the key press. |
| 3302 | // |
| 3303 | // Consume the input and 'continue' to cause us to get a new key |
| 3304 | // event. |
Yabin Cui | 815ad88 | 2015-09-02 17:44:28 -0700 | [diff] [blame] | 3305 | D("_console_read: unknown virtual key code: %d, enhanced: %s", |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3306 | vk, _is_enhanced_key(control_key_state) ? "true" : "false"); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3307 | continue; |
| 3308 | } |
| 3309 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 3310 | // put output wRepeatCount times into g_console_input_buffer |
| 3311 | while (key_event->wRepeatCount-- > 0) { |
| 3312 | 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] | 3313 | } |
| 3314 | |
Spencer Low | 9c8f746 | 2015-11-10 19:17:16 -0800 | [diff] [blame] | 3315 | // Loop around and try to flush g_console_input_buffer |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3316 | } |
| 3317 | } |
| 3318 | |
| 3319 | static DWORD _old_console_mode; // previous GetConsoleMode() result |
| 3320 | static HANDLE _console_handle; // when set, console mode should be restored |
| 3321 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 3322 | void stdin_raw_init() { |
| 3323 | const HANDLE in = _get_console_handle(STDIN_FILENO, &_old_console_mode); |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3324 | if (in == nullptr) { |
| 3325 | return; |
| 3326 | } |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3327 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 3328 | // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of |
| 3329 | // calling the process Ctrl-C routine (configured by |
| 3330 | // SetConsoleCtrlHandler()). |
| 3331 | // Disable ENABLE_LINE_INPUT so that input is immediately sent. |
| 3332 | // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this |
| 3333 | // flag also seems necessary to have proper line-ending processing. |
| 3334 | if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT | |
| 3335 | ENABLE_LINE_INPUT | |
| 3336 | ENABLE_ECHO_INPUT))) { |
| 3337 | // This really should not fail. |
| 3338 | D("stdin_raw_init: SetConsoleMode() failed: %s", |
| 3339 | SystemErrorCodeToString(GetLastError()).c_str()); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3340 | } |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 3341 | |
| 3342 | // Once this is set, it means that stdin has been configured for |
| 3343 | // reading from and that the old console mode should be restored later. |
| 3344 | _console_handle = in; |
| 3345 | |
| 3346 | // Note that we don't need to configure C Runtime line-ending |
| 3347 | // translation because _console_read() does not call the C Runtime to |
| 3348 | // read from the console. |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3349 | } |
| 3350 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 3351 | void stdin_raw_restore() { |
| 3352 | if (_console_handle != NULL) { |
| 3353 | const HANDLE in = _console_handle; |
| 3354 | _console_handle = NULL; // clear state |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3355 | |
Elliott Hughes | a826579 | 2015-11-03 11:18:40 -0800 | [diff] [blame] | 3356 | if (!SetConsoleMode(in, _old_console_mode)) { |
| 3357 | // This really should not fail. |
| 3358 | D("stdin_raw_restore: SetConsoleMode() failed: %s", |
| 3359 | SystemErrorCodeToString(GetLastError()).c_str()); |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3360 | } |
| 3361 | } |
| 3362 | } |
| 3363 | |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 3364 | // Called by 'adb shell' and 'adb exec-in' to read from stdin. |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3365 | int unix_read(int fd, void* buf, size_t len) { |
| 3366 | if ((fd == STDIN_FILENO) && (_console_handle != NULL)) { |
| 3367 | // If it is a request to read from stdin, and stdin_raw_init() has been |
| 3368 | // called, and it successfully configured the console, then read from |
| 3369 | // the console using Win32 console APIs and partially emulate a unix |
| 3370 | // terminal. |
| 3371 | return _console_read(_console_handle, buf, len); |
| 3372 | } else { |
David Pursell | 3fe11f6 | 2015-10-06 15:30:03 -0700 | [diff] [blame] | 3373 | // On older versions of Windows (definitely 7, definitely not 10), |
| 3374 | // ReadConsole() with a size >= 31367 fails, so if |fd| is a console |
David Pursell | 5880536 | 2015-10-28 14:29:51 -0700 | [diff] [blame] | 3375 | // we need to limit the read size. |
| 3376 | if (len > 4096 && unix_isatty(fd)) { |
David Pursell | 3fe11f6 | 2015-10-06 15:30:03 -0700 | [diff] [blame] | 3377 | len = 4096; |
| 3378 | } |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3379 | // 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] | 3380 | // can do LF/CR translation (which is overridable with _setmode()). |
| 3381 | // Undefine the macro that is set in sysdeps.h which bans calls to |
| 3382 | // plain read() in favor of unix_read() or adb_read(). |
| 3383 | #pragma push_macro("read") |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3384 | #undef read |
| 3385 | return read(fd, buf, len); |
Spencer Low | 3a2421b | 2015-05-22 20:09:06 -0700 | [diff] [blame] | 3386 | #pragma pop_macro("read") |
Spencer Low | beb6198 | 2015-03-01 15:06:21 -0800 | [diff] [blame] | 3387 | } |
| 3388 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3389 | |
| 3390 | /**************************************************************************/ |
| 3391 | /**************************************************************************/ |
| 3392 | /***** *****/ |
| 3393 | /***** Unicode support *****/ |
| 3394 | /***** *****/ |
| 3395 | /**************************************************************************/ |
| 3396 | /**************************************************************************/ |
| 3397 | |
| 3398 | // This implements support for using files with Unicode filenames and for |
| 3399 | // outputting Unicode text to a Win32 console window. This is inspired from |
| 3400 | // http://utf8everywhere.org/. |
| 3401 | // |
| 3402 | // Background |
| 3403 | // ---------- |
| 3404 | // |
| 3405 | // On POSIX systems, to deal with files with Unicode filenames, just pass UTF-8 |
| 3406 | // filenames to APIs such as open(). This works because filenames are largely |
| 3407 | // opaque 'cookies' (perhaps excluding path separators). |
| 3408 | // |
| 3409 | // On Windows, the native file APIs such as CreateFileW() take 2-byte wchar_t |
| 3410 | // UTF-16 strings. There is an API, CreateFileA() that takes 1-byte char |
| 3411 | // strings, but the strings are in the ANSI codepage and not UTF-8. (The |
| 3412 | // CreateFile() API is really just a macro that adds the W/A based on whether |
| 3413 | // the UNICODE preprocessor symbol is defined). |
| 3414 | // |
| 3415 | // Options |
| 3416 | // ------- |
| 3417 | // |
| 3418 | // Thus, to write a portable program, there are a few options: |
| 3419 | // |
| 3420 | // 1. Write the program with wchar_t filenames (wchar_t path[256];). |
| 3421 | // For Windows, just call CreateFileW(). For POSIX, write a wrapper openW() |
| 3422 | // that takes a wchar_t string, converts it to UTF-8 and then calls the real |
| 3423 | // open() API. |
| 3424 | // |
| 3425 | // 2. Write the program with a TCHAR typedef that is 2 bytes on Windows and |
| 3426 | // 1 byte on POSIX. Make T-* wrappers for various OS APIs and call those, |
| 3427 | // potentially touching a lot of code. |
| 3428 | // |
| 3429 | // 3. Write the program with a 1-byte char filenames (char path[256];) that are |
| 3430 | // UTF-8. For POSIX, just call open(). For Windows, write a wrapper that |
| 3431 | // takes a UTF-8 string, converts it to UTF-16 and then calls the real OS |
| 3432 | // or C Runtime API. |
| 3433 | // |
| 3434 | // The Choice |
| 3435 | // ---------- |
| 3436 | // |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3437 | // The code below chooses option 3, the UTF-8 everywhere strategy. It uses |
| 3438 | // 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] | 3439 | // 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] | 3440 | // args that are passed to main() at the beginning of program startup. We also use |
| 3441 | // 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] | 3442 | // implement wrappers below that call UTF-16 OS and C Runtime APIs. |
| 3443 | // |
| 3444 | // Unicode console output |
| 3445 | // ---------------------- |
| 3446 | // |
| 3447 | // The way to output Unicode to a Win32 console window is to call |
| 3448 | // 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] | 3449 | // such as Lucida Console or Consolas, and in the case of East Asian languages |
| 3450 | // (such as Chinese, Japanese, Korean), the user must go to the Control Panel |
| 3451 | // and change the "system locale" to Chinese, etc., which allows a Chinese, etc. |
| 3452 | // font to be used in console windows.) |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3453 | // |
| 3454 | // The problem is getting the C Runtime to make fprintf and related APIs call |
| 3455 | // WriteConsoleW() under the covers. The C Runtime API, _setmode() sounds |
| 3456 | // promising, but the various modes have issues: |
| 3457 | // |
| 3458 | // 1. _setmode(_O_TEXT) (the default) does not use WriteConsoleW() so UTF-8 and |
| 3459 | // UTF-16 do not display properly. |
| 3460 | // 2. _setmode(_O_BINARY) does not use WriteConsoleW() and the text comes out |
| 3461 | // totally wrong. |
| 3462 | // 3. _setmode(_O_U8TEXT) seems to cause the C Runtime _invalid_parameter |
| 3463 | // handler to be called (upon a later I/O call), aborting the process. |
| 3464 | // 4. _setmode(_O_U16TEXT) and _setmode(_O_WTEXT) cause non-wide printf/fprintf |
| 3465 | // to output nothing. |
| 3466 | // |
| 3467 | // So the only solution is to write our own adb_fprintf() that converts UTF-8 |
| 3468 | // to UTF-16 and then calls WriteConsoleW(). |
| 3469 | |
| 3470 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3471 | // Constructor for helper class to convert wmain() UTF-16 args to UTF-8 to |
| 3472 | // be passed to main(). |
| 3473 | NarrowArgs::NarrowArgs(const int argc, wchar_t** const argv) { |
| 3474 | narrow_args = new char*[argc + 1]; |
| 3475 | |
| 3476 | for (int i = 0; i < argc; ++i) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3477 | std::string arg_narrow; |
| 3478 | if (!android::base::WideToUTF8(argv[i], &arg_narrow)) { |
| 3479 | fatal_errno("cannot convert argument from UTF-16 to UTF-8"); |
| 3480 | } |
| 3481 | narrow_args[i] = strdup(arg_narrow.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3482 | } |
| 3483 | narrow_args[argc] = nullptr; // terminate |
| 3484 | } |
| 3485 | |
| 3486 | NarrowArgs::~NarrowArgs() { |
| 3487 | if (narrow_args != nullptr) { |
| 3488 | for (char** argp = narrow_args; *argp != nullptr; ++argp) { |
| 3489 | free(*argp); |
| 3490 | } |
| 3491 | delete[] narrow_args; |
| 3492 | narrow_args = nullptr; |
| 3493 | } |
| 3494 | } |
| 3495 | |
| 3496 | int unix_open(const char* path, int options, ...) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3497 | std::wstring path_wide; |
| 3498 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 3499 | return -1; |
| 3500 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3501 | if ((options & O_CREAT) == 0) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3502 | return _wopen(path_wide.c_str(), options); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3503 | } else { |
| 3504 | int mode; |
| 3505 | va_list args; |
| 3506 | va_start(args, options); |
| 3507 | mode = va_arg(args, int); |
| 3508 | va_end(args); |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3509 | return _wopen(path_wide.c_str(), options, mode); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3510 | } |
| 3511 | } |
| 3512 | |
| 3513 | // Version of stat() that takes a UTF-8 path. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3514 | int adb_stat(const char* path, struct adb_stat* s) { |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3515 | #pragma push_macro("wstat") |
| 3516 | // This definition of wstat seems to be missing from <sys/stat.h>. |
| 3517 | #if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64) |
| 3518 | #ifdef _USE_32BIT_TIME_T |
| 3519 | #define wstat _wstat32i64 |
| 3520 | #else |
| 3521 | #define wstat _wstat64 |
| 3522 | #endif |
| 3523 | #else |
| 3524 | // <sys/stat.h> has a function prototype for wstat() that should be available. |
| 3525 | #endif |
| 3526 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3527 | std::wstring path_wide; |
| 3528 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 3529 | return -1; |
| 3530 | } |
| 3531 | |
| 3532 | return wstat(path_wide.c_str(), s); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3533 | |
| 3534 | #pragma pop_macro("wstat") |
| 3535 | } |
| 3536 | |
| 3537 | // Version of opendir() that takes a UTF-8 path. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3538 | DIR* adb_opendir(const char* path) { |
| 3539 | std::wstring path_wide; |
| 3540 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 3541 | return nullptr; |
| 3542 | } |
| 3543 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3544 | // Just cast _WDIR* to DIR*. This doesn't work if the caller reads any of |
| 3545 | // the fields, but right now all the callers treat the structure as |
| 3546 | // opaque. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3547 | return reinterpret_cast<DIR*>(_wopendir(path_wide.c_str())); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3548 | } |
| 3549 | |
| 3550 | // Version of readdir() that returns UTF-8 paths. |
| 3551 | struct dirent* adb_readdir(DIR* dir) { |
| 3552 | _WDIR* const wdir = reinterpret_cast<_WDIR*>(dir); |
| 3553 | struct _wdirent* const went = _wreaddir(wdir); |
| 3554 | if (went == nullptr) { |
| 3555 | return nullptr; |
| 3556 | } |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3557 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3558 | // Convert from UTF-16 to UTF-8. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3559 | std::string name_utf8; |
| 3560 | if (!android::base::WideToUTF8(went->d_name, &name_utf8)) { |
| 3561 | return nullptr; |
| 3562 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3563 | |
| 3564 | // Cast the _wdirent* to dirent* and overwrite the d_name field (which has |
| 3565 | // space for UTF-16 wchar_t's) with UTF-8 char's. |
| 3566 | struct dirent* ent = reinterpret_cast<struct dirent*>(went); |
| 3567 | |
| 3568 | if (name_utf8.length() + 1 > sizeof(went->d_name)) { |
| 3569 | // Name too big to fit in existing buffer. |
| 3570 | errno = ENOMEM; |
| 3571 | return nullptr; |
| 3572 | } |
| 3573 | |
| 3574 | // Note that sizeof(_wdirent::d_name) is bigger than sizeof(dirent::d_name) |
| 3575 | // because _wdirent contains wchar_t instead of char. So even if name_utf8 |
| 3576 | // can fit in _wdirent::d_name, the resulting dirent::d_name field may be |
| 3577 | // bigger than the caller expects because they expect a dirent structure |
| 3578 | // which has a smaller d_name field. Ignore this since the caller should be |
| 3579 | // resilient. |
| 3580 | |
| 3581 | // Rewrite the UTF-16 d_name field to UTF-8. |
| 3582 | strcpy(ent->d_name, name_utf8.c_str()); |
| 3583 | |
| 3584 | return ent; |
| 3585 | } |
| 3586 | |
| 3587 | // Version of closedir() to go with our version of adb_opendir(). |
| 3588 | int adb_closedir(DIR* dir) { |
| 3589 | return _wclosedir(reinterpret_cast<_WDIR*>(dir)); |
| 3590 | } |
| 3591 | |
| 3592 | // Version of unlink() that takes a UTF-8 path. |
| 3593 | int adb_unlink(const char* path) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3594 | std::wstring wpath; |
| 3595 | if (!android::base::UTF8ToWide(path, &wpath)) { |
| 3596 | return -1; |
| 3597 | } |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3598 | |
| 3599 | int rc = _wunlink(wpath.c_str()); |
| 3600 | |
| 3601 | if (rc == -1 && errno == EACCES) { |
| 3602 | /* unlink returns EACCES when the file is read-only, so we first */ |
| 3603 | /* try to make it writable, then unlink again... */ |
| 3604 | rc = _wchmod(wpath.c_str(), _S_IREAD | _S_IWRITE); |
| 3605 | if (rc == 0) |
| 3606 | rc = _wunlink(wpath.c_str()); |
| 3607 | } |
| 3608 | return rc; |
| 3609 | } |
| 3610 | |
| 3611 | // Version of mkdir() that takes a UTF-8 path. |
| 3612 | int adb_mkdir(const std::string& path, int mode) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3613 | std::wstring path_wide; |
| 3614 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 3615 | return -1; |
| 3616 | } |
| 3617 | |
| 3618 | return _wmkdir(path_wide.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3619 | } |
| 3620 | |
| 3621 | // Version of utime() that takes a UTF-8 path. |
| 3622 | int adb_utime(const char* path, struct utimbuf* u) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3623 | std::wstring path_wide; |
| 3624 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 3625 | return -1; |
| 3626 | } |
| 3627 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3628 | static_assert(sizeof(struct utimbuf) == sizeof(struct _utimbuf), |
| 3629 | "utimbuf and _utimbuf should be the same size because they both " |
| 3630 | "contain the same types, namely time_t"); |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3631 | return _wutime(path_wide.c_str(), reinterpret_cast<struct _utimbuf*>(u)); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3632 | } |
| 3633 | |
| 3634 | // Version of chmod() that takes a UTF-8 path. |
| 3635 | int adb_chmod(const char* path, int mode) { |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3636 | std::wstring path_wide; |
| 3637 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 3638 | return -1; |
| 3639 | } |
| 3640 | |
| 3641 | return _wchmod(path_wide.c_str(), mode); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3642 | } |
| 3643 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3644 | // From libutils/Unicode.cpp, get the length of a UTF-8 sequence given the lead byte. |
| 3645 | static inline size_t utf8_codepoint_len(uint8_t ch) { |
| 3646 | return ((0xe5000000 >> ((ch >> 3) & 0x1e)) & 3) + 1; |
| 3647 | } |
Elliott Hughes | 37be38a | 2015-11-11 18:02:29 +0000 | [diff] [blame] | 3648 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3649 | namespace internal { |
| 3650 | |
| 3651 | // Given a sequence of UTF-8 bytes (denoted by the range [first, last)), return the number of bytes |
| 3652 | // (from the beginning) that are complete UTF-8 sequences and append the remaining bytes to |
| 3653 | // remaining_bytes. |
| 3654 | size_t ParseCompleteUTF8(const char* const first, const char* const last, |
| 3655 | std::vector<char>* const remaining_bytes) { |
| 3656 | // Walk backwards from the end of the sequence looking for the beginning of a UTF-8 sequence. |
| 3657 | // Current_after points one byte past the current byte to be examined. |
| 3658 | for (const char* current_after = last; current_after != first; --current_after) { |
| 3659 | const char* const current = current_after - 1; |
| 3660 | const char ch = *current; |
| 3661 | const char kHighBit = 0x80u; |
| 3662 | const char kTwoHighestBits = 0xC0u; |
| 3663 | if ((ch & kHighBit) == 0) { // high bit not set |
| 3664 | // The buffer ends with a one-byte UTF-8 sequence, possibly followed by invalid trailing |
| 3665 | // bytes with no leading byte, so return the entire buffer. |
| 3666 | break; |
| 3667 | } else if ((ch & kTwoHighestBits) == kTwoHighestBits) { // top two highest bits set |
| 3668 | // Lead byte in UTF-8 sequence, so check if we have all the bytes in the sequence. |
| 3669 | const size_t bytes_available = last - current; |
| 3670 | if (bytes_available < utf8_codepoint_len(ch)) { |
| 3671 | // We don't have all the bytes in the UTF-8 sequence, so return all the bytes |
| 3672 | // preceding the current incomplete UTF-8 sequence and append the remaining bytes |
| 3673 | // to remaining_bytes. |
| 3674 | remaining_bytes->insert(remaining_bytes->end(), current, last); |
| 3675 | return current - first; |
| 3676 | } else { |
| 3677 | // The buffer ends with a complete UTF-8 sequence, possibly followed by invalid |
| 3678 | // trailing bytes with no lead byte, so return the entire buffer. |
| 3679 | break; |
| 3680 | } |
| 3681 | } else { |
| 3682 | // Trailing byte, so keep going backwards looking for the lead byte. |
| 3683 | } |
| 3684 | } |
| 3685 | |
| 3686 | // Return the size of the entire buffer. It is possible that we walked backward past invalid |
| 3687 | // trailing bytes with no lead byte, in which case we want to return all those invalid bytes |
| 3688 | // so that they can be processed. |
| 3689 | return last - first; |
| 3690 | } |
| 3691 | |
| 3692 | } |
| 3693 | |
| 3694 | // Bytes that have not yet been output to the console because they are incomplete UTF-8 sequences. |
| 3695 | // Note that we use only one buffer even though stderr and stdout are logically separate streams. |
| 3696 | // This matches the behavior of Linux. |
| 3697 | // Protected by g_console_output_buffer_lock. |
| 3698 | static auto& g_console_output_buffer = *new std::vector<char>(); |
| 3699 | |
| 3700 | // Internal helper function to write UTF-8 bytes to a console. Returns -1 on error. |
| 3701 | static int _console_write_utf8(const char* const buf, const size_t buf_size, FILE* stream, |
| 3702 | HANDLE console) { |
| 3703 | const int saved_errno = errno; |
| 3704 | std::vector<char> combined_buffer; |
| 3705 | |
| 3706 | // Complete UTF-8 sequences that should be immediately written to the console. |
| 3707 | const char* utf8; |
| 3708 | size_t utf8_size; |
| 3709 | |
| 3710 | adb_mutex_lock(&g_console_output_buffer_lock); |
| 3711 | if (g_console_output_buffer.empty()) { |
| 3712 | // If g_console_output_buffer doesn't have a buffered up incomplete UTF-8 sequence (the |
| 3713 | // common case with plain ASCII), parse buf directly. |
| 3714 | utf8 = buf; |
| 3715 | utf8_size = internal::ParseCompleteUTF8(buf, buf + buf_size, &g_console_output_buffer); |
| 3716 | } else { |
| 3717 | // If g_console_output_buffer has a buffered up incomplete UTF-8 sequence, move it to |
| 3718 | // combined_buffer (and effectively clear g_console_output_buffer) and append buf to |
| 3719 | // combined_buffer, then parse it all together. |
| 3720 | combined_buffer.swap(g_console_output_buffer); |
| 3721 | combined_buffer.insert(combined_buffer.end(), buf, buf + buf_size); |
| 3722 | |
| 3723 | utf8 = combined_buffer.data(); |
| 3724 | utf8_size = internal::ParseCompleteUTF8(utf8, utf8 + combined_buffer.size(), |
| 3725 | &g_console_output_buffer); |
| 3726 | } |
| 3727 | adb_mutex_unlock(&g_console_output_buffer_lock); |
| 3728 | |
| 3729 | std::wstring utf16; |
| 3730 | |
| 3731 | // Try to convert from data that might be UTF-8 to UTF-16, ignoring errors (just like Linux |
| 3732 | // which does not return an error on bad UTF-8). Data might not be UTF-8 if the user cat's |
| 3733 | // random data, runs dmesg (which might have non-UTF-8), etc. |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3734 | // This could throw std::bad_alloc. |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3735 | (void)android::base::UTF8ToWide(utf8, utf8_size, &utf16); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3736 | |
| 3737 | // Note that this does not do \n => \r\n translation because that |
| 3738 | // doesn't seem necessary for the Windows console. For the Windows |
| 3739 | // console \r moves to the beginning of the line and \n moves to a new |
| 3740 | // line. |
| 3741 | |
| 3742 | // Flush any stream buffering so that our output is afterwards which |
| 3743 | // makes sense because our call is afterwards. |
| 3744 | (void)fflush(stream); |
| 3745 | |
| 3746 | // Write UTF-16 to the console. |
| 3747 | DWORD written = 0; |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3748 | if (!WriteConsoleW(console, utf16.c_str(), utf16.length(), &written, NULL)) { |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3749 | errno = EIO; |
| 3750 | return -1; |
| 3751 | } |
| 3752 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3753 | // Return the size of the original buffer passed in, signifying that we consumed it all, even |
| 3754 | // if nothing was displayed, in the case of being passed an incomplete UTF-8 sequence. This |
| 3755 | // matches the Linux behavior. |
| 3756 | errno = saved_errno; |
| 3757 | return buf_size; |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3758 | } |
| 3759 | |
| 3760 | // Function prototype because attributes cannot be placed on func definitions. |
| 3761 | static int _console_vfprintf(const HANDLE console, FILE* stream, |
| 3762 | const char *format, va_list ap) |
| 3763 | __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 3, 0))); |
| 3764 | |
| 3765 | // Internal function to format a UTF-8 string and write it to a Win32 console. |
| 3766 | // Returns -1 on error. |
| 3767 | static int _console_vfprintf(const HANDLE console, FILE* stream, |
| 3768 | const char *format, va_list ap) { |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3769 | const int saved_errno = errno; |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3770 | std::string output_utf8; |
| 3771 | |
| 3772 | // Format the string. |
| 3773 | // This could throw std::bad_alloc. |
| 3774 | android::base::StringAppendV(&output_utf8, format, ap); |
| 3775 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3776 | const int result = _console_write_utf8(output_utf8.c_str(), output_utf8.length(), stream, |
| 3777 | console); |
| 3778 | if (result != -1) { |
| 3779 | errno = saved_errno; |
| 3780 | } else { |
| 3781 | // If -1 was returned, errno has been set. |
| 3782 | } |
| 3783 | return result; |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3784 | } |
| 3785 | |
| 3786 | // Version of vfprintf() that takes UTF-8 and can write Unicode to a |
| 3787 | // Windows console. |
| 3788 | int adb_vfprintf(FILE *stream, const char *format, va_list ap) { |
| 3789 | const HANDLE console = _get_console_handle(stream); |
| 3790 | |
| 3791 | // If there is an associated Win32 console, write to it specially, |
| 3792 | // otherwise defer to the regular C Runtime, passing it UTF-8. |
| 3793 | if (console != NULL) { |
| 3794 | return _console_vfprintf(console, stream, format, ap); |
| 3795 | } else { |
| 3796 | // If vfprintf is a macro, undefine it, so we can call the real |
| 3797 | // C Runtime API. |
| 3798 | #pragma push_macro("vfprintf") |
| 3799 | #undef vfprintf |
| 3800 | return vfprintf(stream, format, ap); |
| 3801 | #pragma pop_macro("vfprintf") |
| 3802 | } |
| 3803 | } |
| 3804 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3805 | // Version of vprintf() that takes UTF-8 and can write Unicode to a Windows console. |
| 3806 | int adb_vprintf(const char *format, va_list ap) { |
| 3807 | return adb_vfprintf(stdout, format, ap); |
| 3808 | } |
| 3809 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3810 | // Version of fprintf() that takes UTF-8 and can write Unicode to a |
| 3811 | // Windows console. |
| 3812 | int adb_fprintf(FILE *stream, const char *format, ...) { |
| 3813 | va_list ap; |
| 3814 | va_start(ap, format); |
| 3815 | const int result = adb_vfprintf(stream, format, ap); |
| 3816 | va_end(ap); |
| 3817 | |
| 3818 | return result; |
| 3819 | } |
| 3820 | |
| 3821 | // Version of printf() that takes UTF-8 and can write Unicode to a |
| 3822 | // Windows console. |
| 3823 | int adb_printf(const char *format, ...) { |
| 3824 | va_list ap; |
| 3825 | va_start(ap, format); |
| 3826 | const int result = adb_vfprintf(stdout, format, ap); |
| 3827 | va_end(ap); |
| 3828 | |
| 3829 | return result; |
| 3830 | } |
| 3831 | |
| 3832 | // Version of fputs() that takes UTF-8 and can write Unicode to a |
| 3833 | // Windows console. |
| 3834 | int adb_fputs(const char* buf, FILE* stream) { |
| 3835 | // adb_fprintf returns -1 on error, which is conveniently the same as EOF |
| 3836 | // which fputs (and hence adb_fputs) should return on error. |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3837 | 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] | 3838 | return adb_fprintf(stream, "%s", buf); |
| 3839 | } |
| 3840 | |
| 3841 | // Version of fputc() that takes UTF-8 and can write Unicode to a |
| 3842 | // Windows console. |
| 3843 | int adb_fputc(int ch, FILE* stream) { |
| 3844 | const int result = adb_fprintf(stream, "%c", ch); |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3845 | if (result == -1) { |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3846 | return EOF; |
| 3847 | } |
| 3848 | // For success, fputc returns the char, cast to unsigned char, then to int. |
| 3849 | return static_cast<unsigned char>(ch); |
| 3850 | } |
| 3851 | |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3852 | // Version of putchar() that takes UTF-8 and can write Unicode to a Windows console. |
| 3853 | int adb_putchar(int ch) { |
| 3854 | return adb_fputc(ch, stdout); |
| 3855 | } |
| 3856 | |
| 3857 | // Version of puts() that takes UTF-8 and can write Unicode to a Windows console. |
| 3858 | int adb_puts(const char* buf) { |
| 3859 | // adb_printf returns -1 on error, which is conveniently the same as EOF |
| 3860 | // which puts (and hence adb_puts) should return on error. |
| 3861 | static_assert(EOF == -1, "EOF is not -1, so this code needs to be fixed"); |
| 3862 | return adb_printf("%s\n", buf); |
| 3863 | } |
| 3864 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3865 | // Internal function to write UTF-8 to a Win32 console. Returns the number of |
| 3866 | // items (of length size) written. On error, returns a short item count or 0. |
| 3867 | static size_t _console_fwrite(const void* ptr, size_t size, size_t nmemb, |
| 3868 | FILE* stream, HANDLE console) { |
Spencer Low | f373c35 | 2015-11-15 16:29:36 -0800 | [diff] [blame^] | 3869 | const int result = _console_write_utf8(reinterpret_cast<const char*>(ptr), size * nmemb, stream, |
| 3870 | console); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3871 | if (result == -1) { |
| 3872 | return 0; |
| 3873 | } |
| 3874 | return result / size; |
| 3875 | } |
| 3876 | |
| 3877 | // Version of fwrite() that takes UTF-8 and can write Unicode to a |
| 3878 | // Windows console. |
| 3879 | size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) { |
| 3880 | const HANDLE console = _get_console_handle(stream); |
| 3881 | |
| 3882 | // If there is an associated Win32 console, write to it specially, |
| 3883 | // otherwise defer to the regular C Runtime, passing it UTF-8. |
| 3884 | if (console != NULL) { |
| 3885 | return _console_fwrite(ptr, size, nmemb, stream, console); |
| 3886 | } else { |
| 3887 | // If fwrite is a macro, undefine it, so we can call the real |
| 3888 | // C Runtime API. |
| 3889 | #pragma push_macro("fwrite") |
| 3890 | #undef fwrite |
| 3891 | return fwrite(ptr, size, nmemb, stream); |
| 3892 | #pragma pop_macro("fwrite") |
| 3893 | } |
| 3894 | } |
| 3895 | |
| 3896 | // Version of fopen() that takes a UTF-8 filename and can access a file with |
| 3897 | // a Unicode filename. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3898 | FILE* adb_fopen(const char* path, const char* mode) { |
| 3899 | std::wstring path_wide; |
| 3900 | if (!android::base::UTF8ToWide(path, &path_wide)) { |
| 3901 | return nullptr; |
| 3902 | } |
| 3903 | |
| 3904 | std::wstring mode_wide; |
| 3905 | if (!android::base::UTF8ToWide(mode, &mode_wide)) { |
| 3906 | return nullptr; |
| 3907 | } |
| 3908 | |
| 3909 | return _wfopen(path_wide.c_str(), mode_wide.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3910 | } |
| 3911 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 3912 | // Return a lowercase version of the argument. Uses C Runtime tolower() on |
| 3913 | // each byte which is not UTF-8 aware, and theoretically uses the current C |
| 3914 | // Runtime locale (which in practice is not changed, so this becomes a ASCII |
| 3915 | // conversion). |
| 3916 | static std::string ToLower(const std::string& anycase) { |
| 3917 | // copy string |
| 3918 | std::string str(anycase); |
| 3919 | // transform the copy |
| 3920 | std::transform(str.begin(), str.end(), str.begin(), tolower); |
| 3921 | return str; |
| 3922 | } |
| 3923 | |
| 3924 | extern "C" int main(int argc, char** argv); |
| 3925 | |
| 3926 | // Link with -municode to cause this wmain() to be used as the program |
| 3927 | // entrypoint. It will convert the args from UTF-16 to UTF-8 and call the |
| 3928 | // regular main() with UTF-8 args. |
| 3929 | extern "C" int wmain(int argc, wchar_t **argv) { |
| 3930 | // Convert args from UTF-16 to UTF-8 and pass that to main(). |
| 3931 | NarrowArgs narrow_args(argc, argv); |
| 3932 | return main(argc, narrow_args.data()); |
| 3933 | } |
| 3934 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3935 | // Shadow UTF-8 environment variable name/value pairs that are created from |
| 3936 | // _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] | 3937 | // currently updated if putenv, setenv, unsetenv are called. Note that no |
| 3938 | // thread synchronization is done, but we're called early enough in |
| 3939 | // single-threaded startup that things work ok. |
Josh Gao | e3a87d0 | 2015-11-11 17:56:12 -0800 | [diff] [blame] | 3940 | static auto& g_environ_utf8 = *new std::unordered_map<std::string, char*>(); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3941 | |
| 3942 | // Make sure that shadow UTF-8 environment variables are setup. |
| 3943 | static void _ensure_env_setup() { |
| 3944 | // If some name/value pairs exist, then we've already done the setup below. |
| 3945 | if (g_environ_utf8.size() != 0) { |
| 3946 | return; |
| 3947 | } |
| 3948 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 3949 | if (_wenviron == nullptr) { |
| 3950 | // If _wenviron is null, then -municode probably wasn't used. That |
| 3951 | // linker flag will cause the entry point to setup _wenviron. It will |
| 3952 | // also require an implementation of wmain() (which we provide above). |
| 3953 | fatal("_wenviron is not set, did you link with -municode?"); |
| 3954 | } |
| 3955 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3956 | // Read name/value pairs from UTF-16 _wenviron and write new name/value |
| 3957 | // pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense |
| 3958 | // to use the D() macro here because that tracing only works if the |
| 3959 | // ADB_TRACE environment variable is setup, but that env var can't be read |
| 3960 | // until this code completes. |
| 3961 | for (wchar_t** env = _wenviron; *env != nullptr; ++env) { |
| 3962 | wchar_t* const equal = wcschr(*env, L'='); |
| 3963 | if (equal == nullptr) { |
| 3964 | // Malformed environment variable with no equal sign. Shouldn't |
| 3965 | // really happen, but we should be resilient to this. |
| 3966 | continue; |
| 3967 | } |
| 3968 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3969 | // If we encounter an error converting UTF-16, don't error-out on account of a single env |
| 3970 | // var because the program might never even read this particular variable. |
| 3971 | std::string name_utf8; |
| 3972 | if (!android::base::WideToUTF8(*env, equal - *env, &name_utf8)) { |
| 3973 | continue; |
| 3974 | } |
| 3975 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 3976 | // Store lowercase name so that we can do case-insensitive searches. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3977 | name_utf8 = ToLower(name_utf8); |
| 3978 | |
| 3979 | std::string value_utf8; |
| 3980 | if (!android::base::WideToUTF8(equal + 1, &value_utf8)) { |
| 3981 | continue; |
| 3982 | } |
| 3983 | |
| 3984 | char* const value_dup = strdup(value_utf8.c_str()); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3985 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 3986 | // Don't overwrite a previus env var with the same name. In reality, |
| 3987 | // the system probably won't let two env vars with the same name exist |
| 3988 | // in _wenviron. |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 3989 | g_environ_utf8.insert({name_utf8, value_dup}); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3990 | } |
| 3991 | } |
| 3992 | |
| 3993 | // Version of getenv() that takes a UTF-8 environment variable name and |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 3994 | // retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows. |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 3995 | char* adb_getenv(const char* name) { |
| 3996 | _ensure_env_setup(); |
| 3997 | |
Spencer Low | 50740f5 | 2015-09-08 17:13:04 -0700 | [diff] [blame] | 3998 | // Case-insensitive search by searching for lowercase name in a map of |
| 3999 | // lowercase names. |
| 4000 | const auto it = g_environ_utf8.find(ToLower(std::string(name))); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 4001 | if (it == g_environ_utf8.end()) { |
| 4002 | return nullptr; |
| 4003 | } |
| 4004 | |
| 4005 | return it->second; |
| 4006 | } |
| 4007 | |
| 4008 | // Version of getcwd() that returns the current working directory in UTF-8. |
| 4009 | char* adb_getcwd(char* buf, int size) { |
| 4010 | wchar_t* wbuf = _wgetcwd(nullptr, 0); |
| 4011 | if (wbuf == nullptr) { |
| 4012 | return nullptr; |
| 4013 | } |
| 4014 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 4015 | std::string buf_utf8; |
| 4016 | const bool narrow_result = android::base::WideToUTF8(wbuf, &buf_utf8); |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 4017 | free(wbuf); |
| 4018 | wbuf = nullptr; |
| 4019 | |
Spencer Low | 50f5bf1 | 2015-11-12 15:20:15 -0800 | [diff] [blame] | 4020 | if (!narrow_result) { |
| 4021 | return nullptr; |
| 4022 | } |
| 4023 | |
Spencer Low | 6815c07 | 2015-05-11 01:08:48 -0700 | [diff] [blame] | 4024 | // If size was specified, make sure all the chars will fit. |
| 4025 | if (size != 0) { |
| 4026 | if (size < static_cast<int>(buf_utf8.length() + 1)) { |
| 4027 | errno = ERANGE; |
| 4028 | return nullptr; |
| 4029 | } |
| 4030 | } |
| 4031 | |
| 4032 | // If buf was not specified, allocate storage. |
| 4033 | if (buf == nullptr) { |
| 4034 | if (size == 0) { |
| 4035 | size = buf_utf8.length() + 1; |
| 4036 | } |
| 4037 | buf = reinterpret_cast<char*>(malloc(size)); |
| 4038 | if (buf == nullptr) { |
| 4039 | return nullptr; |
| 4040 | } |
| 4041 | } |
| 4042 | |
| 4043 | // Destination buffer was allocated with enough space, or we've already |
| 4044 | // checked an existing buffer size for enough space. |
| 4045 | strcpy(buf, buf_utf8.c_str()); |
| 4046 | |
| 4047 | return buf; |
| 4048 | } |