blob: 9fdc24c8bc1d671e206c1efcd3b46c59ab31d213 [file] [log] [blame]
Dan Albert33134262015-03-19 15:21:08 -07001/*
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
17#define TRACE_TAG TRACE_SYSDEPS
18
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080019#include "sysdeps.h"
Dan Albert33134262015-03-19 15:21:08 -070020
21#include <winsock2.h> /* winsock.h *must* be included before windows.h. */
Stephen Hines2f431a82014-10-01 17:37:06 -070022#include <windows.h>
Dan Albert33134262015-03-19 15:21:08 -070023
24#include <errno.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Christopher Ferris67a7a4a2014-11-06 14:34:24 -080026#include <stdlib.h>
Dan Albert33134262015-03-19 15:21:08 -070027
Spencer Low5200c662015-07-30 23:07:55 -070028#include <memory>
29#include <string>
30
Elliott Hughesd48dbd82015-07-24 11:35:40 -070031#include <cutils/sockets.h>
32
Spencer Low5200c662015-07-30 23:07:55 -070033#include <base/logging.h>
34#include <base/stringprintf.h>
35#include <base/strings.h>
36
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080037#include "adb.h"
38
39extern void fatal(const char *fmt, ...);
40
Elliott Hughesa2f2e562015-04-16 16:47:02 -070041/* forward declarations */
42
43typedef const struct FHClassRec_* FHClass;
44typedef struct FHRec_* FH;
45typedef struct EventHookRec_* EventHook;
46
47typedef struct FHClassRec_ {
48 void (*_fh_init)(FH);
49 int (*_fh_close)(FH);
50 int (*_fh_lseek)(FH, int, int);
51 int (*_fh_read)(FH, void*, int);
52 int (*_fh_write)(FH, const void*, int);
53 void (*_fh_hook)(FH, int, EventHook);
54} FHClassRec;
55
56static void _fh_file_init(FH);
57static int _fh_file_close(FH);
58static int _fh_file_lseek(FH, int, int);
59static int _fh_file_read(FH, void*, int);
60static int _fh_file_write(FH, const void*, int);
61static void _fh_file_hook(FH, int, EventHook);
62
63static const FHClassRec _fh_file_class = {
64 _fh_file_init,
65 _fh_file_close,
66 _fh_file_lseek,
67 _fh_file_read,
68 _fh_file_write,
69 _fh_file_hook
70};
71
72static void _fh_socket_init(FH);
73static int _fh_socket_close(FH);
74static int _fh_socket_lseek(FH, int, int);
75static int _fh_socket_read(FH, void*, int);
76static int _fh_socket_write(FH, const void*, int);
77static void _fh_socket_hook(FH, int, EventHook);
78
79static const FHClassRec _fh_socket_class = {
80 _fh_socket_init,
81 _fh_socket_close,
82 _fh_socket_lseek,
83 _fh_socket_read,
84 _fh_socket_write,
85 _fh_socket_hook
86};
87
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080088#define assert(cond) do { if (!(cond)) fatal( "assertion failed '%s' on %s:%ld\n", #cond, __FILE__, __LINE__ ); } while (0)
89
Spencer Low5200c662015-07-30 23:07:55 -070090std::string SystemErrorCodeToString(const DWORD error_code) {
91 const int kErrorMessageBufferSize = 256;
92 char msgbuf[kErrorMessageBufferSize];
93 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
94 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
95 arraysize(msgbuf), nullptr);
96 if (len == 0) {
97 return android::base::StringPrintf(
98 "Error (%lu) while retrieving error. (%lu)", GetLastError(),
99 error_code);
100 }
101
102 std::string msg(msgbuf);
103 // Messages returned by the system end with line breaks.
104 msg = android::base::Trim(msg);
105 // There are many Windows error messages compared to POSIX, so include the
106 // numeric error code for easier, quicker, accurate identification. Use
107 // decimal instead of hex because there are decimal ranges like 10000-11999
108 // for Winsock.
109 android::base::StringAppendF(&msg, " (%lu)", error_code);
110 return msg;
111}
112
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800113/**************************************************************************/
114/**************************************************************************/
115/***** *****/
116/***** replaces libs/cutils/load_file.c *****/
117/***** *****/
118/**************************************************************************/
119/**************************************************************************/
120
121void *load_file(const char *fn, unsigned *_sz)
122{
123 HANDLE file;
124 char *data;
125 DWORD file_size;
126
127 file = CreateFile( fn,
128 GENERIC_READ,
129 FILE_SHARE_READ,
130 NULL,
131 OPEN_EXISTING,
132 0,
133 NULL );
134
135 if (file == INVALID_HANDLE_VALUE)
136 return NULL;
137
138 file_size = GetFileSize( file, NULL );
139 data = NULL;
140
141 if (file_size > 0) {
142 data = (char*) malloc( file_size + 1 );
143 if (data == NULL) {
144 D("load_file: could not allocate %ld bytes\n", file_size );
145 file_size = 0;
146 } else {
147 DWORD out_bytes;
148
149 if ( !ReadFile( file, data, file_size, &out_bytes, NULL ) ||
150 out_bytes != file_size )
151 {
152 D("load_file: could not read %ld bytes from '%s'\n", file_size, fn);
153 free(data);
154 data = NULL;
155 file_size = 0;
156 }
157 }
158 }
159 CloseHandle( file );
160
161 *_sz = (unsigned) file_size;
162 return data;
163}
164
165/**************************************************************************/
166/**************************************************************************/
167/***** *****/
168/***** common file descriptor handling *****/
169/***** *****/
170/**************************************************************************/
171/**************************************************************************/
172
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800173/* used to emulate unix-domain socket pairs */
174typedef struct SocketPairRec_* SocketPair;
175
176typedef struct FHRec_
177{
178 FHClass clazz;
179 int used;
180 int eof;
181 union {
182 HANDLE handle;
183 SOCKET socket;
184 SocketPair pair;
185 } u;
186
187 HANDLE event;
188 int mask;
189
190 char name[32];
191
192} FHRec;
193
194#define fh_handle u.handle
195#define fh_socket u.socket
196#define fh_pair u.pair
197
198#define WIN32_FH_BASE 100
199
200#define WIN32_MAX_FHS 128
201
202static adb_mutex_t _win32_lock;
203static FHRec _win32_fhs[ WIN32_MAX_FHS ];
204static int _win32_fh_count;
205
206static FH
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700207_fh_from_int( int fd, const char* func )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800208{
209 FH f;
210
211 fd -= WIN32_FH_BASE;
212
213 if (fd < 0 || fd >= _win32_fh_count) {
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700214 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
215 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800216 errno = EBADF;
217 return NULL;
218 }
219
220 f = &_win32_fhs[fd];
221
222 if (f->used == 0) {
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700223 D( "_fh_from_int: invalid fd %d passed to %s\n", fd + WIN32_FH_BASE,
224 func );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800225 errno = EBADF;
226 return NULL;
227 }
228
229 return f;
230}
231
232
233static int
234_fh_to_int( FH f )
235{
236 if (f && f->used && f >= _win32_fhs && f < _win32_fhs + WIN32_MAX_FHS)
237 return (int)(f - _win32_fhs) + WIN32_FH_BASE;
238
239 return -1;
240}
241
242static FH
243_fh_alloc( FHClass clazz )
244{
245 int nn;
246 FH f = NULL;
247
248 adb_mutex_lock( &_win32_lock );
249
250 if (_win32_fh_count < WIN32_MAX_FHS) {
251 f = &_win32_fhs[ _win32_fh_count++ ];
252 goto Exit;
253 }
254
255 for (nn = 0; nn < WIN32_MAX_FHS; nn++) {
256 if ( _win32_fhs[nn].clazz == NULL) {
257 f = &_win32_fhs[nn];
258 goto Exit;
259 }
260 }
261 D( "_fh_alloc: no more free file descriptors\n" );
262Exit:
263 if (f) {
264 f->clazz = clazz;
265 f->used = 1;
266 f->eof = 0;
267 clazz->_fh_init(f);
268 }
269 adb_mutex_unlock( &_win32_lock );
270 return f;
271}
272
273
274static int
275_fh_close( FH f )
276{
277 if ( f->used ) {
278 f->clazz->_fh_close( f );
279 f->used = 0;
280 f->eof = 0;
281 f->clazz = NULL;
282 }
283 return 0;
284}
285
Spencer Low5200c662015-07-30 23:07:55 -0700286// Deleter for unique_fh.
287class fh_deleter {
288 public:
289 void operator()(struct FHRec_* fh) {
290 // We're called from a destructor and destructors should not overwrite
291 // errno because callers may do:
292 // errno = EBLAH;
293 // return -1; // calls destructor, which should not overwrite errno
294 const int saved_errno = errno;
295 _fh_close(fh);
296 errno = saved_errno;
297 }
298};
299
300// Like std::unique_ptr, but calls _fh_close() instead of operator delete().
301typedef std::unique_ptr<struct FHRec_, fh_deleter> unique_fh;
302
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800303/**************************************************************************/
304/**************************************************************************/
305/***** *****/
306/***** file-based descriptor handling *****/
307/***** *****/
308/**************************************************************************/
309/**************************************************************************/
310
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700311static void _fh_file_init( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800312 f->fh_handle = INVALID_HANDLE_VALUE;
313}
314
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700315static int _fh_file_close( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800316 CloseHandle( f->fh_handle );
317 f->fh_handle = INVALID_HANDLE_VALUE;
318 return 0;
319}
320
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700321static int _fh_file_read( FH f, void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800322 DWORD read_bytes;
323
324 if ( !ReadFile( f->fh_handle, buf, (DWORD)len, &read_bytes, NULL ) ) {
325 D( "adb_read: could not read %d bytes from %s\n", len, f->name );
326 errno = EIO;
327 return -1;
328 } else if (read_bytes < (DWORD)len) {
329 f->eof = 1;
330 }
331 return (int)read_bytes;
332}
333
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700334static int _fh_file_write( FH f, const void* buf, int len ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800335 DWORD wrote_bytes;
336
337 if ( !WriteFile( f->fh_handle, buf, (DWORD)len, &wrote_bytes, NULL ) ) {
338 D( "adb_file_write: could not write %d bytes from %s\n", len, f->name );
339 errno = EIO;
340 return -1;
341 } else if (wrote_bytes < (DWORD)len) {
342 f->eof = 1;
343 }
344 return (int)wrote_bytes;
345}
346
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700347static int _fh_file_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800348 DWORD method;
349 DWORD result;
350
351 switch (origin)
352 {
353 case SEEK_SET: method = FILE_BEGIN; break;
354 case SEEK_CUR: method = FILE_CURRENT; break;
355 case SEEK_END: method = FILE_END; break;
356 default:
357 errno = EINVAL;
358 return -1;
359 }
360
361 result = SetFilePointer( f->fh_handle, pos, NULL, method );
362 if (result == INVALID_SET_FILE_POINTER) {
363 errno = EIO;
364 return -1;
365 } else {
366 f->eof = 0;
367 }
368 return (int)result;
369}
370
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800371
372/**************************************************************************/
373/**************************************************************************/
374/***** *****/
375/***** file-based descriptor handling *****/
376/***** *****/
377/**************************************************************************/
378/**************************************************************************/
379
380int adb_open(const char* path, int options)
381{
382 FH f;
383
384 DWORD desiredAccess = 0;
385 DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
386
387 switch (options) {
388 case O_RDONLY:
389 desiredAccess = GENERIC_READ;
390 break;
391 case O_WRONLY:
392 desiredAccess = GENERIC_WRITE;
393 break;
394 case O_RDWR:
395 desiredAccess = GENERIC_READ | GENERIC_WRITE;
396 break;
397 default:
398 D("adb_open: invalid options (0x%0x)\n", options);
399 errno = EINVAL;
400 return -1;
401 }
402
403 f = _fh_alloc( &_fh_file_class );
404 if ( !f ) {
405 errno = ENOMEM;
406 return -1;
407 }
408
409 f->fh_handle = CreateFile( path, desiredAccess, shareMode, NULL, OPEN_EXISTING,
410 0, NULL );
411
412 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700413 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800414 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700415 D( "adb_open: could not open '%s': ", path );
416 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800417 case ERROR_FILE_NOT_FOUND:
418 D( "file not found\n" );
419 errno = ENOENT;
420 return -1;
421
422 case ERROR_PATH_NOT_FOUND:
423 D( "path not found\n" );
424 errno = ENOTDIR;
425 return -1;
426
427 default:
Spencer Low8d8126a2015-07-21 02:06:26 -0700428 D( "unknown error: %ld\n", err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429 errno = ENOENT;
430 return -1;
431 }
432 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800433
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
435 D( "adb_open: '%s' => fd %d\n", path, _fh_to_int(f) );
436 return _fh_to_int(f);
437}
438
439/* ignore mode on Win32 */
440int adb_creat(const char* path, int mode)
441{
442 FH f;
443
444 f = _fh_alloc( &_fh_file_class );
445 if ( !f ) {
446 errno = ENOMEM;
447 return -1;
448 }
449
450 f->fh_handle = CreateFile( path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
451 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL,
452 NULL );
453
454 if ( f->fh_handle == INVALID_HANDLE_VALUE ) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700455 const DWORD err = GetLastError();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800456 _fh_close(f);
Spencer Low8d8126a2015-07-21 02:06:26 -0700457 D( "adb_creat: could not open '%s': ", path );
458 switch (err) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800459 case ERROR_FILE_NOT_FOUND:
460 D( "file not found\n" );
461 errno = ENOENT;
462 return -1;
463
464 case ERROR_PATH_NOT_FOUND:
465 D( "path not found\n" );
466 errno = ENOTDIR;
467 return -1;
468
469 default:
Spencer Low8d8126a2015-07-21 02:06:26 -0700470 D( "unknown error: %ld\n", err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800471 errno = ENOENT;
472 return -1;
473 }
474 }
475 snprintf( f->name, sizeof(f->name), "%d(%s)", _fh_to_int(f), path );
476 D( "adb_creat: '%s' => fd %d\n", path, _fh_to_int(f) );
477 return _fh_to_int(f);
478}
479
480
481int adb_read(int fd, void* buf, int len)
482{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700483 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800484
485 if (f == NULL) {
486 return -1;
487 }
488
489 return f->clazz->_fh_read( f, buf, len );
490}
491
492
493int adb_write(int fd, const void* buf, int len)
494{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700495 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800496
497 if (f == NULL) {
498 return -1;
499 }
500
501 return f->clazz->_fh_write(f, buf, len);
502}
503
504
505int adb_lseek(int fd, int pos, int where)
506{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700507 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800508
509 if (!f) {
510 return -1;
511 }
512
513 return f->clazz->_fh_lseek(f, pos, where);
514}
515
516
517int adb_close(int fd)
518{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700519 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800520
521 if (!f) {
522 return -1;
523 }
524
525 D( "adb_close: %s\n", f->name);
526 _fh_close(f);
527 return 0;
528}
529
530/**************************************************************************/
531/**************************************************************************/
532/***** *****/
533/***** socket-based file descriptors *****/
534/***** *****/
535/**************************************************************************/
536/**************************************************************************/
537
Spencer Lowf055c192015-01-25 14:40:16 -0800538#undef setsockopt
539
Spencer Low5200c662015-07-30 23:07:55 -0700540static void _socket_set_errno( const DWORD err ) {
541 // The Windows C Runtime (MSVCRT.DLL) strerror() does not support a lot of
542 // POSIX and socket error codes, so this can only meaningfully map so much.
543 switch ( err ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800544 case 0: errno = 0; break;
545 case WSAEWOULDBLOCK: errno = EAGAIN; break;
546 case WSAEINTR: errno = EINTR; break;
Spencer Low5200c662015-07-30 23:07:55 -0700547 case WSAEFAULT: errno = EFAULT; break;
548 case WSAEINVAL: errno = EINVAL; break;
549 case WSAEMFILE: errno = EMFILE; break;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800550 default:
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800551 errno = EINVAL;
Spencer Low5200c662015-07-30 23:07:55 -0700552 D( "_socket_set_errno: mapping Windows error code %lu to errno %d\n",
553 err, errno );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554 }
555}
556
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700557static void _fh_socket_init( FH f ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558 f->fh_socket = INVALID_SOCKET;
559 f->event = WSACreateEvent();
Spencer Low5200c662015-07-30 23:07:55 -0700560 if (f->event == WSA_INVALID_EVENT) {
561 D("WSACreateEvent failed: %s\n",
562 SystemErrorCodeToString(WSAGetLastError()).c_str());
563
564 // _event_socket_start assumes that this field is INVALID_HANDLE_VALUE
565 // on failure, instead of NULL which is what Windows really returns on
566 // error. It might be better to change all the other code to look for
567 // NULL, but that is a much riskier change.
568 f->event = INVALID_HANDLE_VALUE;
569 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800570 f->mask = 0;
571}
572
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700573static int _fh_socket_close( FH f ) {
Spencer Low5200c662015-07-30 23:07:55 -0700574 if (f->fh_socket != INVALID_SOCKET) {
575 /* gently tell any peer that we're closing the socket */
576 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
577 // If the socket is not connected, this returns an error. We want to
578 // minimize logging spam, so don't log these errors for now.
579#if 0
580 D("socket shutdown failed: %s\n",
581 SystemErrorCodeToString(WSAGetLastError()).c_str());
582#endif
583 }
584 if (closesocket(f->fh_socket) == SOCKET_ERROR) {
585 D("closesocket failed: %s\n",
586 SystemErrorCodeToString(WSAGetLastError()).c_str());
587 }
588 f->fh_socket = INVALID_SOCKET;
589 }
590 if (f->event != NULL) {
591 if (!CloseHandle(f->event)) {
592 D("CloseHandle failed: %s\n",
593 SystemErrorCodeToString(GetLastError()).c_str());
594 }
595 f->event = NULL;
596 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800597 f->mask = 0;
598 return 0;
599}
600
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700601static int _fh_socket_lseek( FH f, int pos, int origin ) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602 errno = EPIPE;
603 return -1;
604}
605
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700606static int _fh_socket_read(FH f, void* buf, int len) {
607 int result = recv(f->fh_socket, reinterpret_cast<char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700609 const DWORD err = WSAGetLastError();
610 D("recv fd %d failed: %s\n", _fh_to_int(f),
611 SystemErrorCodeToString(err).c_str());
612 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800613 result = -1;
614 }
615 return result;
616}
617
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700618static int _fh_socket_write(FH f, const void* buf, int len) {
619 int result = send(f->fh_socket, reinterpret_cast<const char*>(buf), len, 0);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620 if (result == SOCKET_ERROR) {
Spencer Low5200c662015-07-30 23:07:55 -0700621 const DWORD err = WSAGetLastError();
622 D("send fd %d failed: %s\n", _fh_to_int(f),
623 SystemErrorCodeToString(err).c_str());
624 _socket_set_errno(err);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800625 result = -1;
626 }
627 return result;
628}
629
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630/**************************************************************************/
631/**************************************************************************/
632/***** *****/
633/***** replacement for libs/cutils/socket_xxxx.c *****/
634/***** *****/
635/**************************************************************************/
636/**************************************************************************/
637
638#include <winsock2.h>
639
640static int _winsock_init;
641
642static void
643_cleanup_winsock( void )
644{
Spencer Low5200c662015-07-30 23:07:55 -0700645 // TODO: WSAStartup() might be called multiple times and this won't properly
646 // cleanup the right number of times. Plus, WSACleanup() probably doesn't
647 // make sense since it might interrupt other threads using Winsock (since
648 // our various threads are not explicitly cleanly shutdown at process exit).
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800649 WSACleanup();
650}
651
652static void
653_init_winsock( void )
654{
Spencer Low5200c662015-07-30 23:07:55 -0700655 // TODO: Multiple threads calling this may potentially cause multiple calls
656 // to WSAStartup() and multiple atexit() calls.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800657 if (!_winsock_init) {
658 WSADATA wsaData;
659 int rc = WSAStartup( MAKEWORD(2,2), &wsaData);
660 if (rc != 0) {
Spencer Low5200c662015-07-30 23:07:55 -0700661 fatal( "adb: could not initialize Winsock: %s",
662 SystemErrorCodeToString( rc ).c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800663 }
664 atexit( _cleanup_winsock );
665 _winsock_init = 1;
666 }
667}
668
Spencer Low5200c662015-07-30 23:07:55 -0700669int network_loopback_client(int port, int type, std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800670 struct sockaddr_in addr;
671 SOCKET s;
672
Spencer Low5200c662015-07-30 23:07:55 -0700673 unique_fh f(_fh_alloc(&_fh_socket_class));
674 if (!f) {
675 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800676 return -1;
Spencer Low5200c662015-07-30 23:07:55 -0700677 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800678
679 if (!_winsock_init)
680 _init_winsock();
681
682 memset(&addr, 0, sizeof(addr));
683 addr.sin_family = AF_INET;
684 addr.sin_port = htons(port);
685 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
686
687 s = socket(AF_INET, type, 0);
688 if(s == INVALID_SOCKET) {
Spencer Low5200c662015-07-30 23:07:55 -0700689 *error = SystemErrorCodeToString(WSAGetLastError());
690 D("could not create socket: %s\n", error->c_str());
691 return -1;
692 }
693 f->fh_socket = s;
694
695 if(connect(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
696 *error = SystemErrorCodeToString(WSAGetLastError());
697 D("could not connect to %s:%d: %s\n",
698 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800699 return -1;
700 }
701
Spencer Low5200c662015-07-30 23:07:55 -0700702 const int fd = _fh_to_int(f.get());
703 snprintf( f->name, sizeof(f->name), "%d(lo-client:%s%d)", fd,
704 type != SOCK_STREAM ? "udp:" : "", port );
705 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
706 fd );
707 f.release();
708 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800709}
710
711#define LISTEN_BACKLOG 4
712
Spencer Low5200c662015-07-30 23:07:55 -0700713// interface_address is INADDR_LOOPBACK or INADDR_ANY.
714static int _network_server(int port, int type, u_long interface_address,
715 std::string* error) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800716 struct sockaddr_in addr;
717 SOCKET s;
718 int n;
719
Spencer Low5200c662015-07-30 23:07:55 -0700720 unique_fh f(_fh_alloc(&_fh_socket_class));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800721 if (!f) {
Spencer Low5200c662015-07-30 23:07:55 -0700722 *error = strerror(errno);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800723 return -1;
724 }
725
726 if (!_winsock_init)
727 _init_winsock();
728
729 memset(&addr, 0, sizeof(addr));
730 addr.sin_family = AF_INET;
731 addr.sin_port = htons(port);
Spencer Low5200c662015-07-30 23:07:55 -0700732 addr.sin_addr.s_addr = htonl(interface_address);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733
Spencer Low5200c662015-07-30 23:07:55 -0700734 // TODO: Consider using dual-stack socket that can simultaneously listen on
735 // IPv4 and IPv6.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800736 s = socket(AF_INET, type, 0);
Spencer Low5200c662015-07-30 23:07:55 -0700737 if (s == INVALID_SOCKET) {
738 *error = SystemErrorCodeToString(WSAGetLastError());
739 D("could not create socket: %s\n", error->c_str());
740 return -1;
741 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800742
743 f->fh_socket = s;
744
745 n = 1;
Spencer Low5200c662015-07-30 23:07:55 -0700746 if (setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&n,
747 sizeof(n)) == SOCKET_ERROR) {
748 *error = SystemErrorCodeToString(WSAGetLastError());
749 D("setsockopt level %d optname %d failed: %s\n",
750 SOL_SOCKET, SO_EXCLUSIVEADDRUSE, error->c_str());
751 return -1;
752 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800753
Spencer Low5200c662015-07-30 23:07:55 -0700754 if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) == SOCKET_ERROR) {
755 *error = SystemErrorCodeToString(WSAGetLastError());
756 D("could not bind to %s:%d: %s\n",
757 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800758 return -1;
759 }
760 if (type == SOCK_STREAM) {
Spencer Low5200c662015-07-30 23:07:55 -0700761 if (listen(s, LISTEN_BACKLOG) == SOCKET_ERROR) {
762 *error = SystemErrorCodeToString(WSAGetLastError());
763 D("could not listen on %s:%d: %s\n",
764 type != SOCK_STREAM ? "udp" : "tcp", port, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800765 return -1;
766 }
767 }
Spencer Low5200c662015-07-30 23:07:55 -0700768 const int fd = _fh_to_int(f.get());
769 snprintf( f->name, sizeof(f->name), "%d(%s-server:%s%d)", fd,
770 interface_address == INADDR_LOOPBACK ? "lo" : "any",
771 type != SOCK_STREAM ? "udp:" : "", port );
772 D( "port %d type %s => fd %d\n", port, type != SOCK_STREAM ? "udp" : "tcp",
773 fd );
774 f.release();
775 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800776}
777
Spencer Low5200c662015-07-30 23:07:55 -0700778int network_loopback_server(int port, int type, std::string* error) {
779 return _network_server(port, type, INADDR_LOOPBACK, error);
780}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800781
Spencer Low5200c662015-07-30 23:07:55 -0700782int network_inaddr_any_server(int port, int type, std::string* error) {
783 return _network_server(port, type, INADDR_ANY, error);
784}
785
786int network_connect(const std::string& host, int port, int type, int timeout, std::string* error) {
787 unique_fh f(_fh_alloc(&_fh_socket_class));
788 if (!f) {
789 *error = strerror(errno);
790 return -1;
791 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800792
Elliott Hughes381cfa92015-07-23 17:12:58 -0700793 if (!_winsock_init) _init_winsock();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800794
Spencer Low5200c662015-07-30 23:07:55 -0700795 struct addrinfo hints;
796 memset(&hints, 0, sizeof(hints));
797 hints.ai_family = AF_UNSPEC;
798 hints.ai_socktype = type;
799
800 char port_str[16];
801 snprintf(port_str, sizeof(port_str), "%d", port);
802
803 struct addrinfo* addrinfo_ptr = nullptr;
804 if (getaddrinfo(host.c_str(), port_str, &hints, &addrinfo_ptr) != 0) {
805 *error = SystemErrorCodeToString(WSAGetLastError());
806 D("could not resolve host '%s' and port %s: %s\n", host.c_str(),
807 port_str, error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800808 return -1;
809 }
Spencer Low5200c662015-07-30 23:07:55 -0700810 std::unique_ptr<struct addrinfo, decltype(freeaddrinfo)*>
811 addrinfo(addrinfo_ptr, freeaddrinfo);
812 addrinfo_ptr = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800813
Spencer Low5200c662015-07-30 23:07:55 -0700814 // TODO: Try all the addresses if there's more than one? This just uses
815 // the first. Or, could call WSAConnectByName() (Windows Vista and newer)
816 // which tries all addresses, takes a timeout and more.
817 SOCKET s = socket(addrinfo->ai_family, addrinfo->ai_socktype,
818 addrinfo->ai_protocol);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800819 if(s == INVALID_SOCKET) {
Spencer Low5200c662015-07-30 23:07:55 -0700820 *error = SystemErrorCodeToString(WSAGetLastError());
821 D("could not create socket: %s\n", error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800822 return -1;
823 }
824 f->fh_socket = s;
825
Spencer Low5200c662015-07-30 23:07:55 -0700826 // TODO: Implement timeouts for Windows. Seems like the default in theory
827 // (according to http://serverfault.com/a/671453) and in practice is 21 sec.
828 if(connect(s, addrinfo->ai_addr, addrinfo->ai_addrlen) == SOCKET_ERROR) {
829 *error = SystemErrorCodeToString(WSAGetLastError());
830 D("could not connect to %s:%s:%s: %s\n",
831 type != SOCK_STREAM ? "udp" : "tcp", host.c_str(), port_str,
832 error->c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800833 return -1;
834 }
835
Spencer Low5200c662015-07-30 23:07:55 -0700836 const int fd = _fh_to_int(f.get());
837 snprintf( f->name, sizeof(f->name), "%d(net-client:%s%d)", fd,
838 type != SOCK_STREAM ? "udp:" : "", port );
839 D( "host '%s' port %d type %s => fd %d\n", host.c_str(), port,
840 type != SOCK_STREAM ? "udp" : "tcp", fd );
841 f.release();
842 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800843}
844
845#undef accept
846int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
847{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700848 FH serverfh = _fh_from_int(serverfd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200849
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800850 if ( !serverfh || serverfh->clazz != &_fh_socket_class ) {
Spencer Low5200c662015-07-30 23:07:55 -0700851 D("adb_socket_accept: invalid fd %d\n", serverfd);
852 errno = EBADF;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800853 return -1;
854 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200855
Spencer Low5200c662015-07-30 23:07:55 -0700856 unique_fh fh(_fh_alloc( &_fh_socket_class ));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800857 if (!fh) {
Spencer Low5200c662015-07-30 23:07:55 -0700858 PLOG(ERROR) << "adb_socket_accept: failed to allocate accepted socket "
859 "descriptor";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800860 return -1;
861 }
862
863 fh->fh_socket = accept( serverfh->fh_socket, addr, addrlen );
864 if (fh->fh_socket == INVALID_SOCKET) {
Spencer Low8d8126a2015-07-21 02:06:26 -0700865 const DWORD err = WSAGetLastError();
Spencer Low5200c662015-07-30 23:07:55 -0700866 LOG(ERROR) << "adb_socket_accept: accept on fd " << serverfd <<
867 " failed: " + SystemErrorCodeToString(err);
868 _socket_set_errno( err );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800869 return -1;
870 }
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200871
Spencer Low5200c662015-07-30 23:07:55 -0700872 const int fd = _fh_to_int(fh.get());
873 snprintf( fh->name, sizeof(fh->name), "%d(accept:%s)", fd, serverfh->name );
874 D( "adb_socket_accept on fd %d returns fd %d\n", serverfd, fd );
875 fh.release();
876 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800877}
878
879
Spencer Lowf055c192015-01-25 14:40:16 -0800880int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800881{
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700882 FH fh = _fh_from_int(fd, __func__);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200883
Spencer Lowf055c192015-01-25 14:40:16 -0800884 if ( !fh || fh->clazz != &_fh_socket_class ) {
885 D("adb_setsockopt: invalid fd %d\n", fd);
Spencer Low5200c662015-07-30 23:07:55 -0700886 errno = EBADF;
887 return -1;
888 }
889 int result = setsockopt( fh->fh_socket, level, optname,
890 reinterpret_cast<const char*>(optval), optlen );
891 if ( result == SOCKET_ERROR ) {
892 const DWORD err = WSAGetLastError();
893 D( "adb_setsockopt: setsockopt on fd %d level %d optname %d "
894 "failed: %s\n", fd, level, optname,
895 SystemErrorCodeToString(err).c_str() );
896 _socket_set_errno( err );
897 result = -1;
898 }
899 return result;
900}
901
902
903int adb_shutdown(int fd)
904{
905 FH f = _fh_from_int(fd, __func__);
906
907 if (!f || f->clazz != &_fh_socket_class) {
908 D("adb_shutdown: invalid fd %d\n", fd);
909 errno = EBADF;
Spencer Lowf055c192015-01-25 14:40:16 -0800910 return -1;
911 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800912
Spencer Low5200c662015-07-30 23:07:55 -0700913 D( "adb_shutdown: %s\n", f->name);
914 if (shutdown(f->fh_socket, SD_BOTH) == SOCKET_ERROR) {
915 const DWORD err = WSAGetLastError();
916 D("socket shutdown fd %d failed: %s\n", fd,
917 SystemErrorCodeToString(err).c_str());
918 _socket_set_errno(err);
919 return -1;
920 }
921 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800922}
923
924/**************************************************************************/
925/**************************************************************************/
926/***** *****/
927/***** emulated socketpairs *****/
928/***** *****/
929/**************************************************************************/
930/**************************************************************************/
931
932/* we implement socketpairs directly in use space for the following reasons:
933 * - it avoids copying data from/to the Nt kernel
934 * - it allows us to implement fdevent hooks easily and cheaply, something
935 * that is not possible with standard Win32 pipes !!
936 *
937 * basically, we use two circular buffers, each one corresponding to a given
938 * direction.
939 *
940 * each buffer is implemented as two regions:
941 *
942 * region A which is (a_start,a_end)
943 * region B which is (0, b_end) with b_end <= a_start
944 *
945 * an empty buffer has: a_start = a_end = b_end = 0
946 *
947 * a_start is the pointer where we start reading data
948 * a_end is the pointer where we start writing data, unless it is BUFFER_SIZE,
949 * then you start writing at b_end
950 *
951 * the buffer is full when b_end == a_start && a_end == BUFFER_SIZE
952 *
953 * there is room when b_end < a_start || a_end < BUFER_SIZE
954 *
955 * when reading, a_start is incremented, it a_start meets a_end, then
956 * we do: a_start = 0, a_end = b_end, b_end = 0, and keep going on..
957 */
958
959#define BIP_BUFFER_SIZE 4096
960
961#if 0
962#include <stdio.h>
963# define BIPD(x) D x
964# define BIPDUMP bip_dump_hex
965
966static void bip_dump_hex( const unsigned char* ptr, size_t len )
967{
968 int nn, len2 = len;
969
970 if (len2 > 8) len2 = 8;
971
Vladimir Chtchetkinece480832011-11-30 10:20:27 -0800972 for (nn = 0; nn < len2; nn++)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800973 printf("%02x", ptr[nn]);
974 printf(" ");
975
976 for (nn = 0; nn < len2; nn++) {
977 int c = ptr[nn];
978 if (c < 32 || c > 127)
979 c = '.';
980 printf("%c", c);
981 }
982 printf("\n");
983 fflush(stdout);
984}
985
986#else
987# define BIPD(x) do {} while (0)
988# define BIPDUMP(p,l) BIPD(p)
989#endif
990
991typedef struct BipBufferRec_
992{
993 int a_start;
994 int a_end;
995 int b_end;
996 int fdin;
997 int fdout;
998 int closed;
999 int can_write; /* boolean */
1000 HANDLE evt_write; /* event signaled when one can write to a buffer */
1001 int can_read; /* boolean */
1002 HANDLE evt_read; /* event signaled when one can read from a buffer */
1003 CRITICAL_SECTION lock;
1004 unsigned char buff[ BIP_BUFFER_SIZE ];
1005
1006} BipBufferRec, *BipBuffer;
1007
1008static void
1009bip_buffer_init( BipBuffer buffer )
1010{
1011 D( "bit_buffer_init %p\n", buffer );
1012 buffer->a_start = 0;
1013 buffer->a_end = 0;
1014 buffer->b_end = 0;
1015 buffer->can_write = 1;
1016 buffer->can_read = 0;
1017 buffer->fdin = 0;
1018 buffer->fdout = 0;
1019 buffer->closed = 0;
1020 buffer->evt_write = CreateEvent( NULL, TRUE, TRUE, NULL );
1021 buffer->evt_read = CreateEvent( NULL, TRUE, FALSE, NULL );
1022 InitializeCriticalSection( &buffer->lock );
1023}
1024
1025static void
1026bip_buffer_close( BipBuffer bip )
1027{
1028 bip->closed = 1;
1029
1030 if (!bip->can_read) {
1031 SetEvent( bip->evt_read );
1032 }
1033 if (!bip->can_write) {
1034 SetEvent( bip->evt_write );
1035 }
1036}
1037
1038static void
1039bip_buffer_done( BipBuffer bip )
1040{
1041 BIPD(( "bip_buffer_done: %d->%d\n", bip->fdin, bip->fdout ));
1042 CloseHandle( bip->evt_read );
1043 CloseHandle( bip->evt_write );
1044 DeleteCriticalSection( &bip->lock );
1045}
1046
1047static int
1048bip_buffer_write( BipBuffer bip, const void* src, int len )
1049{
1050 int avail, count = 0;
1051
1052 if (len <= 0)
1053 return 0;
1054
1055 BIPD(( "bip_buffer_write: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1056 BIPDUMP( src, len );
1057
1058 EnterCriticalSection( &bip->lock );
1059
1060 while (!bip->can_write) {
1061 int ret;
1062 LeaveCriticalSection( &bip->lock );
1063
1064 if (bip->closed) {
1065 errno = EPIPE;
1066 return -1;
1067 }
1068 /* spinlocking here is probably unfair, but let's live with it */
1069 ret = WaitForSingleObject( bip->evt_write, INFINITE );
1070 if (ret != WAIT_OBJECT_0) { /* buffer probably closed */
1071 D( "bip_buffer_write: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError() );
1072 return 0;
1073 }
1074 if (bip->closed) {
1075 errno = EPIPE;
1076 return -1;
1077 }
1078 EnterCriticalSection( &bip->lock );
1079 }
1080
1081 BIPD(( "bip_buffer_write: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1082
1083 avail = BIP_BUFFER_SIZE - bip->a_end;
1084 if (avail > 0)
1085 {
1086 /* we can append to region A */
1087 if (avail > len)
1088 avail = len;
1089
1090 memcpy( bip->buff + bip->a_end, src, avail );
Mark Salyzyn60299df2014-04-30 09:10:31 -07001091 src = (const char *)src + avail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001092 count += avail;
1093 len -= avail;
1094
1095 bip->a_end += avail;
1096 if (bip->a_end == BIP_BUFFER_SIZE && bip->a_start == 0) {
1097 bip->can_write = 0;
1098 ResetEvent( bip->evt_write );
1099 goto Exit;
1100 }
1101 }
1102
1103 if (len == 0)
1104 goto Exit;
1105
1106 avail = bip->a_start - bip->b_end;
1107 assert( avail > 0 ); /* since can_write is TRUE */
1108
1109 if (avail > len)
1110 avail = len;
1111
1112 memcpy( bip->buff + bip->b_end, src, avail );
1113 count += avail;
1114 bip->b_end += avail;
1115
1116 if (bip->b_end == bip->a_start) {
1117 bip->can_write = 0;
1118 ResetEvent( bip->evt_write );
1119 }
1120
1121Exit:
1122 assert( count > 0 );
1123
1124 if ( !bip->can_read ) {
1125 bip->can_read = 1;
1126 SetEvent( bip->evt_read );
1127 }
1128
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001129 BIPD(( "bip_buffer_write: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001130 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1131 LeaveCriticalSection( &bip->lock );
1132
1133 return count;
1134 }
1135
1136static int
1137bip_buffer_read( BipBuffer bip, void* dst, int len )
1138{
1139 int avail, count = 0;
1140
1141 if (len <= 0)
1142 return 0;
1143
1144 BIPD(( "bip_buffer_read: enter %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1145
1146 EnterCriticalSection( &bip->lock );
1147 while ( !bip->can_read )
1148 {
1149#if 0
1150 LeaveCriticalSection( &bip->lock );
1151 errno = EAGAIN;
1152 return -1;
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001153#else
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154 int ret;
1155 LeaveCriticalSection( &bip->lock );
1156
1157 if (bip->closed) {
1158 errno = EPIPE;
1159 return -1;
1160 }
1161
1162 ret = WaitForSingleObject( bip->evt_read, INFINITE );
1163 if (ret != WAIT_OBJECT_0) { /* probably closed buffer */
1164 D( "bip_buffer_read: error %d->%d WaitForSingleObject returned %d, error %ld\n", bip->fdin, bip->fdout, ret, GetLastError());
1165 return 0;
1166 }
1167 if (bip->closed) {
1168 errno = EPIPE;
1169 return -1;
1170 }
1171 EnterCriticalSection( &bip->lock );
1172#endif
1173 }
1174
1175 BIPD(( "bip_buffer_read: exec %d->%d len %d\n", bip->fdin, bip->fdout, len ));
1176
1177 avail = bip->a_end - bip->a_start;
1178 assert( avail > 0 ); /* since can_read is TRUE */
1179
1180 if (avail > len)
1181 avail = len;
1182
1183 memcpy( dst, bip->buff + bip->a_start, avail );
Mark Salyzyn60299df2014-04-30 09:10:31 -07001184 dst = (char *)dst + avail;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001185 count += avail;
1186 len -= avail;
1187
1188 bip->a_start += avail;
1189 if (bip->a_start < bip->a_end)
1190 goto Exit;
1191
1192 bip->a_start = 0;
1193 bip->a_end = bip->b_end;
1194 bip->b_end = 0;
1195
1196 avail = bip->a_end;
1197 if (avail > 0) {
1198 if (avail > len)
1199 avail = len;
1200 memcpy( dst, bip->buff, avail );
1201 count += avail;
1202 bip->a_start += avail;
1203
1204 if ( bip->a_start < bip->a_end )
1205 goto Exit;
1206
1207 bip->a_start = bip->a_end = 0;
1208 }
1209
1210 bip->can_read = 0;
1211 ResetEvent( bip->evt_read );
1212
1213Exit:
1214 assert( count > 0 );
1215
1216 if (!bip->can_write ) {
1217 bip->can_write = 1;
1218 SetEvent( bip->evt_write );
1219 }
1220
1221 BIPDUMP( (const unsigned char*)dst - count, count );
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001222 BIPD(( "bip_buffer_read: exit %d->%d count %d (as=%d ae=%d be=%d cw=%d cr=%d\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001223 bip->fdin, bip->fdout, count, bip->a_start, bip->a_end, bip->b_end, bip->can_write, bip->can_read ));
1224 LeaveCriticalSection( &bip->lock );
1225
1226 return count;
1227}
1228
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001229typedef struct SocketPairRec_
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001230{
1231 BipBufferRec a2b_bip;
1232 BipBufferRec b2a_bip;
1233 FH a_fd;
1234 int used;
1235
1236} SocketPairRec;
1237
1238void _fh_socketpair_init( FH f )
1239{
1240 f->fh_pair = NULL;
1241}
1242
1243static int
1244_fh_socketpair_close( FH f )
1245{
1246 if ( f->fh_pair ) {
1247 SocketPair pair = f->fh_pair;
1248
1249 if ( f == pair->a_fd ) {
1250 pair->a_fd = NULL;
1251 }
1252
1253 bip_buffer_close( &pair->b2a_bip );
1254 bip_buffer_close( &pair->a2b_bip );
1255
1256 if ( --pair->used == 0 ) {
1257 bip_buffer_done( &pair->b2a_bip );
1258 bip_buffer_done( &pair->a2b_bip );
1259 free( pair );
1260 }
1261 f->fh_pair = NULL;
1262 }
1263 return 0;
1264}
1265
1266static int
1267_fh_socketpair_lseek( FH f, int pos, int origin )
1268{
1269 errno = ESPIPE;
1270 return -1;
1271}
1272
1273static int
1274_fh_socketpair_read( FH f, void* buf, int len )
1275{
1276 SocketPair pair = f->fh_pair;
1277 BipBuffer bip;
1278
1279 if (!pair)
1280 return -1;
1281
1282 if ( f == pair->a_fd )
1283 bip = &pair->b2a_bip;
1284 else
1285 bip = &pair->a2b_bip;
1286
1287 return bip_buffer_read( bip, buf, len );
1288}
1289
1290static int
1291_fh_socketpair_write( FH f, const void* buf, int len )
1292{
1293 SocketPair pair = f->fh_pair;
1294 BipBuffer bip;
1295
1296 if (!pair)
1297 return -1;
1298
1299 if ( f == pair->a_fd )
1300 bip = &pair->a2b_bip;
1301 else
1302 bip = &pair->b2a_bip;
1303
1304 return bip_buffer_write( bip, buf, len );
1305}
1306
1307
1308static void _fh_socketpair_hook( FH f, int event, EventHook hook ); /* forward */
1309
1310static const FHClassRec _fh_socketpair_class =
1311{
1312 _fh_socketpair_init,
1313 _fh_socketpair_close,
1314 _fh_socketpair_lseek,
1315 _fh_socketpair_read,
1316 _fh_socketpair_write,
1317 _fh_socketpair_hook
1318};
1319
1320
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001321int adb_socketpair(int sv[2]) {
1322 SocketPair pair;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001323
Spencer Low5200c662015-07-30 23:07:55 -07001324 unique_fh fa(_fh_alloc(&_fh_socketpair_class));
1325 if (!fa) {
1326 return -1;
1327 }
1328 unique_fh fb(_fh_alloc(&_fh_socketpair_class));
1329 if (!fb) {
1330 return -1;
1331 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001332
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001333 pair = reinterpret_cast<SocketPair>(malloc(sizeof(*pair)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001334 if (pair == NULL) {
1335 D("adb_socketpair: not enough memory to allocate pipes\n" );
Spencer Low5200c662015-07-30 23:07:55 -07001336 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001337 }
1338
1339 bip_buffer_init( &pair->a2b_bip );
1340 bip_buffer_init( &pair->b2a_bip );
1341
1342 fa->fh_pair = pair;
1343 fb->fh_pair = pair;
1344 pair->used = 2;
Spencer Low5200c662015-07-30 23:07:55 -07001345 pair->a_fd = fa.get();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001346
Spencer Low5200c662015-07-30 23:07:55 -07001347 sv[0] = _fh_to_int(fa.get());
1348 sv[1] = _fh_to_int(fb.get());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001349
1350 pair->a2b_bip.fdin = sv[0];
1351 pair->a2b_bip.fdout = sv[1];
1352 pair->b2a_bip.fdin = sv[1];
1353 pair->b2a_bip.fdout = sv[0];
1354
1355 snprintf( fa->name, sizeof(fa->name), "%d(pair:%d)", sv[0], sv[1] );
1356 snprintf( fb->name, sizeof(fb->name), "%d(pair:%d)", sv[1], sv[0] );
1357 D( "adb_socketpair: returns (%d, %d)\n", sv[0], sv[1] );
Spencer Low5200c662015-07-30 23:07:55 -07001358 fa.release();
1359 fb.release();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001360 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001361}
1362
1363/**************************************************************************/
1364/**************************************************************************/
1365/***** *****/
1366/***** fdevents emulation *****/
1367/***** *****/
1368/***** this is a very simple implementation, we rely on the fact *****/
1369/***** that ADB doesn't use FDE_ERROR. *****/
1370/***** *****/
1371/**************************************************************************/
1372/**************************************************************************/
1373
1374#define FATAL(x...) fatal(__FUNCTION__, x)
1375
1376#if DEBUG
1377static void dump_fde(fdevent *fde, const char *info)
1378{
1379 fprintf(stderr,"FDE #%03d %c%c%c %s\n", fde->fd,
1380 fde->state & FDE_READ ? 'R' : ' ',
1381 fde->state & FDE_WRITE ? 'W' : ' ',
1382 fde->state & FDE_ERROR ? 'E' : ' ',
1383 info);
1384}
1385#else
1386#define dump_fde(fde, info) do { } while(0)
1387#endif
1388
1389#define FDE_EVENTMASK 0x00ff
1390#define FDE_STATEMASK 0xff00
1391
1392#define FDE_ACTIVE 0x0100
1393#define FDE_PENDING 0x0200
1394#define FDE_CREATED 0x0400
1395
1396static void fdevent_plist_enqueue(fdevent *node);
1397static void fdevent_plist_remove(fdevent *node);
1398static fdevent *fdevent_plist_dequeue(void);
1399
1400static fdevent list_pending = {
1401 .next = &list_pending,
1402 .prev = &list_pending,
1403};
1404
1405static fdevent **fd_table = 0;
1406static int fd_table_max = 0;
1407
1408typedef struct EventLooperRec_* EventLooper;
1409
1410typedef struct EventHookRec_
1411{
1412 EventHook next;
1413 FH fh;
1414 HANDLE h;
1415 int wanted; /* wanted event flags */
1416 int ready; /* ready event flags */
1417 void* aux;
1418 void (*prepare)( EventHook hook );
1419 int (*start) ( EventHook hook );
1420 void (*stop) ( EventHook hook );
1421 int (*check) ( EventHook hook );
1422 int (*peek) ( EventHook hook );
1423} EventHookRec;
1424
1425static EventHook _free_hooks;
1426
1427static EventHook
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001428event_hook_alloc(FH fh) {
1429 EventHook hook = _free_hooks;
1430 if (hook != NULL) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001431 _free_hooks = hook->next;
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001432 } else {
1433 hook = reinterpret_cast<EventHook>(malloc(sizeof(*hook)));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001434 if (hook == NULL)
1435 fatal( "could not allocate event hook\n" );
1436 }
1437 hook->next = NULL;
1438 hook->fh = fh;
1439 hook->wanted = 0;
1440 hook->ready = 0;
1441 hook->h = INVALID_HANDLE_VALUE;
1442 hook->aux = NULL;
1443
1444 hook->prepare = NULL;
1445 hook->start = NULL;
1446 hook->stop = NULL;
1447 hook->check = NULL;
1448 hook->peek = NULL;
1449
1450 return hook;
1451}
1452
1453static void
1454event_hook_free( EventHook hook )
1455{
1456 hook->fh = NULL;
1457 hook->wanted = 0;
1458 hook->ready = 0;
1459 hook->next = _free_hooks;
1460 _free_hooks = hook;
1461}
1462
1463
1464static void
1465event_hook_signal( EventHook hook )
1466{
1467 FH f = hook->fh;
1468 int fd = _fh_to_int(f);
1469 fdevent* fde = fd_table[ fd - WIN32_FH_BASE ];
1470
1471 if (fde != NULL && fde->fd == fd) {
1472 if ((fde->state & FDE_PENDING) == 0) {
1473 fde->state |= FDE_PENDING;
1474 fdevent_plist_enqueue( fde );
1475 }
1476 fde->events |= hook->wanted;
1477 }
1478}
1479
1480
1481#define MAX_LOOPER_HANDLES WIN32_MAX_FHS
1482
1483typedef struct EventLooperRec_
1484{
1485 EventHook hooks;
1486 HANDLE htab[ MAX_LOOPER_HANDLES ];
1487 int htab_count;
1488
1489} EventLooperRec;
1490
1491static EventHook*
1492event_looper_find_p( EventLooper looper, FH fh )
1493{
1494 EventHook *pnode = &looper->hooks;
1495 EventHook node = *pnode;
1496 for (;;) {
1497 if ( node == NULL || node->fh == fh )
1498 break;
1499 pnode = &node->next;
1500 node = *pnode;
1501 }
1502 return pnode;
1503}
1504
1505static void
1506event_looper_hook( EventLooper looper, int fd, int events )
1507{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001508 FH f = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001509 EventHook *pnode;
1510 EventHook node;
1511
1512 if (f == NULL) /* invalid arg */ {
1513 D("event_looper_hook: invalid fd=%d\n", fd);
1514 return;
1515 }
1516
1517 pnode = event_looper_find_p( looper, f );
1518 node = *pnode;
1519 if ( node == NULL ) {
1520 node = event_hook_alloc( f );
1521 node->next = *pnode;
1522 *pnode = node;
1523 }
1524
1525 if ( (node->wanted & events) != events ) {
1526 /* this should update start/stop/check/peek */
1527 D("event_looper_hook: call hook for %d (new=%x, old=%x)\n",
1528 fd, node->wanted, events);
1529 f->clazz->_fh_hook( f, events & ~node->wanted, node );
1530 node->wanted |= events;
1531 } else {
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001532 D("event_looper_hook: ignoring events %x for %d wanted=%x)\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001533 events, fd, node->wanted);
1534 }
1535}
1536
1537static void
1538event_looper_unhook( EventLooper looper, int fd, int events )
1539{
Spencer Low6ac5d7d2015-05-22 20:09:06 -07001540 FH fh = _fh_from_int(fd, __func__);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001541 EventHook *pnode = event_looper_find_p( looper, fh );
1542 EventHook node = *pnode;
1543
1544 if (node != NULL) {
1545 int events2 = events & node->wanted;
1546 if ( events2 == 0 ) {
1547 D( "event_looper_unhook: events %x not registered for fd %d\n", events, fd );
1548 return;
1549 }
1550 node->wanted &= ~events2;
1551 if (!node->wanted) {
1552 *pnode = node->next;
1553 event_hook_free( node );
1554 }
1555 }
1556}
1557
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001558/*
1559 * A fixer for WaitForMultipleObjects on condition that there are more than 64
1560 * handles to wait on.
1561 *
1562 * In cetain cases DDMS may establish more than 64 connections with ADB. For
1563 * instance, this may happen if there are more than 64 processes running on a
1564 * device, or there are multiple devices connected (including the emulator) with
1565 * the combined number of running processes greater than 64. In this case using
1566 * WaitForMultipleObjects to wait on connection events simply wouldn't cut,
1567 * because of the API limitations (64 handles max). So, we need to provide a way
1568 * to scale WaitForMultipleObjects to accept an arbitrary number of handles. The
1569 * easiest (and "Microsoft recommended") way to do that would be dividing the
1570 * handle array into chunks with the chunk size less than 64, and fire up as many
1571 * waiting threads as there are chunks. Then each thread would wait on a chunk of
1572 * handles, and will report back to the caller which handle has been set.
1573 * Here is the implementation of that algorithm.
1574 */
1575
1576/* Number of handles to wait on in each wating thread. */
1577#define WAIT_ALL_CHUNK_SIZE 63
1578
1579/* Descriptor for a wating thread */
1580typedef struct WaitForAllParam {
1581 /* A handle to an event to signal when waiting is over. This handle is shared
1582 * accross all the waiting threads, so each waiting thread knows when any
1583 * other thread has exited, so it can exit too. */
1584 HANDLE main_event;
1585 /* Upon exit from a waiting thread contains the index of the handle that has
1586 * been signaled. The index is an absolute index of the signaled handle in
1587 * the original array. This pointer is shared accross all the waiting threads
1588 * and it's not guaranteed (due to a race condition) that when all the
1589 * waiting threads exit, the value contained here would indicate the first
1590 * handle that was signaled. This is fine, because the caller cares only
1591 * about any handle being signaled. It doesn't care about the order, nor
1592 * about the whole list of handles that were signaled. */
1593 LONG volatile *signaled_index;
1594 /* Array of handles to wait on in a waiting thread. */
1595 HANDLE* handles;
1596 /* Number of handles in 'handles' array to wait on. */
1597 int handles_count;
1598 /* Index inside the main array of the first handle in the 'handles' array. */
1599 int first_handle_index;
1600 /* Waiting thread handle. */
1601 HANDLE thread;
1602} WaitForAllParam;
1603
1604/* Waiting thread routine. */
1605static unsigned __stdcall
1606_in_waiter_thread(void* arg)
1607{
1608 HANDLE wait_on[WAIT_ALL_CHUNK_SIZE + 1];
1609 int res;
1610 WaitForAllParam* const param = (WaitForAllParam*)arg;
1611
1612 /* We have to wait on the main_event in order to be notified when any of the
1613 * sibling threads is exiting. */
1614 wait_on[0] = param->main_event;
1615 /* The rest of the handles go behind the main event handle. */
1616 memcpy(wait_on + 1, param->handles, param->handles_count * sizeof(HANDLE));
1617
1618 res = WaitForMultipleObjects(param->handles_count + 1, wait_on, FALSE, INFINITE);
1619 if (res > 0 && res < (param->handles_count + 1)) {
1620 /* One of the original handles got signaled. Save its absolute index into
1621 * the output variable. */
1622 InterlockedCompareExchange(param->signaled_index,
1623 res - 1L + param->first_handle_index, -1L);
1624 }
1625
1626 /* Notify the caller (and the siblings) that the wait is over. */
1627 SetEvent(param->main_event);
1628
1629 _endthreadex(0);
1630 return 0;
1631}
1632
1633/* WaitForMultipeObjects fixer routine.
1634 * Param:
1635 * handles Array of handles to wait on.
1636 * handles_count Number of handles in the array.
1637 * Return:
1638 * (>= 0 && < handles_count) - Index of the signaled handle in the array, or
1639 * WAIT_FAILED on an error.
1640 */
1641static int
1642_wait_for_all(HANDLE* handles, int handles_count)
1643{
1644 WaitForAllParam* threads;
1645 HANDLE main_event;
1646 int chunks, chunk, remains;
1647
1648 /* This variable is going to be accessed by several threads at the same time,
1649 * this is bound to fail randomly when the core is run on multi-core machines.
1650 * To solve this, we need to do the following (1 _and_ 2):
1651 * 1. Use the "volatile" qualifier to ensure the compiler doesn't optimize
1652 * out the reads/writes in this function unexpectedly.
1653 * 2. Ensure correct memory ordering. The "simple" way to do that is to wrap
1654 * all accesses inside a critical section. But we can also use
1655 * InterlockedCompareExchange() which always provide a full memory barrier
1656 * on Win32.
1657 */
1658 volatile LONG sig_index = -1;
1659
1660 /* Calculate number of chunks, and allocate thread param array. */
1661 chunks = handles_count / WAIT_ALL_CHUNK_SIZE;
1662 remains = handles_count % WAIT_ALL_CHUNK_SIZE;
1663 threads = (WaitForAllParam*)malloc((chunks + (remains ? 1 : 0)) *
1664 sizeof(WaitForAllParam));
1665 if (threads == NULL) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001666 D("Unable to allocate thread array for %d handles.\n", handles_count);
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001667 return (int)WAIT_FAILED;
1668 }
1669
1670 /* Create main event to wait on for all waiting threads. This is a "manualy
1671 * reset" event that will remain set once it was set. */
1672 main_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1673 if (main_event == NULL) {
Spencer Low8d8126a2015-07-21 02:06:26 -07001674 D("Unable to create main event. Error: %ld\n", GetLastError());
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001675 free(threads);
1676 return (int)WAIT_FAILED;
1677 }
1678
1679 /*
1680 * Initialize waiting thread parameters.
1681 */
1682
1683 for (chunk = 0; chunk < chunks; chunk++) {
1684 threads[chunk].main_event = main_event;
1685 threads[chunk].signaled_index = &sig_index;
1686 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1687 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1688 threads[chunk].handles_count = WAIT_ALL_CHUNK_SIZE;
1689 }
1690 if (remains) {
1691 threads[chunk].main_event = main_event;
1692 threads[chunk].signaled_index = &sig_index;
1693 threads[chunk].first_handle_index = WAIT_ALL_CHUNK_SIZE * chunk;
1694 threads[chunk].handles = handles + threads[chunk].first_handle_index;
1695 threads[chunk].handles_count = remains;
1696 chunks++;
1697 }
1698
1699 /* Start the waiting threads. */
1700 for (chunk = 0; chunk < chunks; chunk++) {
1701 /* Note that using adb_thread_create is not appropriate here, since we
1702 * need a handle to wait on for thread termination. */
1703 threads[chunk].thread = (HANDLE)_beginthreadex(NULL, 0, _in_waiter_thread,
1704 &threads[chunk], 0, NULL);
1705 if (threads[chunk].thread == NULL) {
1706 /* Unable to create a waiter thread. Collapse. */
Spencer Low8d8126a2015-07-21 02:06:26 -07001707 D("Unable to create a waiting thread %d of %d. errno=%d\n",
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001708 chunk, chunks, errno);
1709 chunks = chunk;
1710 SetEvent(main_event);
1711 break;
1712 }
1713 }
1714
1715 /* Wait on any of the threads to get signaled. */
1716 WaitForSingleObject(main_event, INFINITE);
1717
1718 /* Wait on all the waiting threads to exit. */
1719 for (chunk = 0; chunk < chunks; chunk++) {
1720 WaitForSingleObject(threads[chunk].thread, INFINITE);
1721 CloseHandle(threads[chunk].thread);
1722 }
1723
1724 CloseHandle(main_event);
1725 free(threads);
1726
1727
1728 const int ret = (int)InterlockedCompareExchange(&sig_index, -1, -1);
1729 return (ret >= 0) ? ret : (int)WAIT_FAILED;
1730}
1731
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001732static EventLooperRec win32_looper;
1733
1734static void fdevent_init(void)
1735{
1736 win32_looper.htab_count = 0;
1737 win32_looper.hooks = NULL;
1738}
1739
1740static void fdevent_connect(fdevent *fde)
1741{
1742 EventLooper looper = &win32_looper;
1743 int events = fde->state & FDE_EVENTMASK;
1744
1745 if (events != 0)
1746 event_looper_hook( looper, fde->fd, events );
1747}
1748
1749static void fdevent_disconnect(fdevent *fde)
1750{
1751 EventLooper looper = &win32_looper;
1752 int events = fde->state & FDE_EVENTMASK;
1753
1754 if (events != 0)
1755 event_looper_unhook( looper, fde->fd, events );
1756}
1757
1758static void fdevent_update(fdevent *fde, unsigned events)
1759{
1760 EventLooper looper = &win32_looper;
1761 unsigned events0 = fde->state & FDE_EVENTMASK;
1762
1763 if (events != events0) {
1764 int removes = events0 & ~events;
1765 int adds = events & ~events0;
1766 if (removes) {
1767 D("fdevent_update: remove %x from %d\n", removes, fde->fd);
1768 event_looper_unhook( looper, fde->fd, removes );
1769 }
1770 if (adds) {
1771 D("fdevent_update: add %x to %d\n", adds, fde->fd);
1772 event_looper_hook ( looper, fde->fd, adds );
1773 }
1774 }
1775}
1776
1777static void fdevent_process()
1778{
1779 EventLooper looper = &win32_looper;
1780 EventHook hook;
1781 int gotone = 0;
1782
1783 /* if we have at least one ready hook, execute it/them */
1784 for (hook = looper->hooks; hook; hook = hook->next) {
1785 hook->ready = 0;
1786 if (hook->prepare) {
1787 hook->prepare(hook);
1788 if (hook->ready != 0) {
1789 event_hook_signal( hook );
1790 gotone = 1;
1791 }
1792 }
1793 }
1794
1795 /* nothing's ready yet, so wait for something to happen */
1796 if (!gotone)
1797 {
1798 looper->htab_count = 0;
1799
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001800 for (hook = looper->hooks; hook; hook = hook->next)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001801 {
1802 if (hook->start && !hook->start(hook)) {
1803 D( "fdevent_process: error when starting a hook\n" );
1804 return;
1805 }
1806 if (hook->h != INVALID_HANDLE_VALUE) {
1807 int nn;
1808
1809 for (nn = 0; nn < looper->htab_count; nn++)
1810 {
1811 if ( looper->htab[nn] == hook->h )
1812 goto DontAdd;
1813 }
1814 looper->htab[ looper->htab_count++ ] = hook->h;
1815 DontAdd:
1816 ;
1817 }
1818 }
1819
1820 if (looper->htab_count == 0) {
1821 D( "fdevent_process: nothing to wait for !!\n" );
1822 return;
1823 }
1824
1825 do
1826 {
1827 int wait_ret;
1828
1829 D( "adb_win32: waiting for %d events\n", looper->htab_count );
1830 if (looper->htab_count > MAXIMUM_WAIT_OBJECTS) {
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001831 D("handle count %d exceeds MAXIMUM_WAIT_OBJECTS.\n", looper->htab_count);
1832 wait_ret = _wait_for_all(looper->htab, looper->htab_count);
1833 } else {
1834 wait_ret = WaitForMultipleObjects( looper->htab_count, looper->htab, FALSE, INFINITE );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001835 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001836 if (wait_ret == (int)WAIT_FAILED) {
1837 D( "adb_win32: wait failed, error %ld\n", GetLastError() );
1838 } else {
1839 D( "adb_win32: got one (index %d)\n", wait_ret );
1840
1841 /* according to Cygwin, some objects like consoles wake up on "inappropriate" events
1842 * like mouse movements. we need to filter these with the "check" function
1843 */
1844 if ((unsigned)wait_ret < (unsigned)looper->htab_count)
1845 {
1846 for (hook = looper->hooks; hook; hook = hook->next)
1847 {
1848 if ( looper->htab[wait_ret] == hook->h &&
1849 (!hook->check || hook->check(hook)) )
1850 {
1851 D( "adb_win32: signaling %s for %x\n", hook->fh->name, hook->ready );
1852 event_hook_signal( hook );
1853 gotone = 1;
1854 break;
1855 }
1856 }
1857 }
1858 }
1859 }
1860 while (!gotone);
1861
1862 for (hook = looper->hooks; hook; hook = hook->next) {
1863 if (hook->stop)
1864 hook->stop( hook );
1865 }
1866 }
1867
1868 for (hook = looper->hooks; hook; hook = hook->next) {
1869 if (hook->peek && hook->peek(hook))
1870 event_hook_signal( hook );
1871 }
1872}
1873
1874
1875static void fdevent_register(fdevent *fde)
1876{
1877 int fd = fde->fd - WIN32_FH_BASE;
1878
1879 if(fd < 0) {
1880 FATAL("bogus negative fd (%d)\n", fde->fd);
1881 }
1882
1883 if(fd >= fd_table_max) {
1884 int oldmax = fd_table_max;
1885 if(fde->fd > 32000) {
1886 FATAL("bogus huuuuge fd (%d)\n", fde->fd);
1887 }
1888 if(fd_table_max == 0) {
1889 fdevent_init();
1890 fd_table_max = 256;
1891 }
1892 while(fd_table_max <= fd) {
1893 fd_table_max *= 2;
1894 }
Elliott Hughesa2f2e562015-04-16 16:47:02 -07001895 fd_table = reinterpret_cast<fdevent**>(realloc(fd_table, sizeof(fdevent*) * fd_table_max));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001896 if(fd_table == 0) {
1897 FATAL("could not expand fd_table to %d entries\n", fd_table_max);
1898 }
1899 memset(fd_table + oldmax, 0, sizeof(int) * (fd_table_max - oldmax));
1900 }
1901
1902 fd_table[fd] = fde;
1903}
1904
1905static void fdevent_unregister(fdevent *fde)
1906{
1907 int fd = fde->fd - WIN32_FH_BASE;
1908
1909 if((fd < 0) || (fd >= fd_table_max)) {
1910 FATAL("fd out of range (%d)\n", fde->fd);
1911 }
1912
1913 if(fd_table[fd] != fde) {
1914 FATAL("fd_table out of sync");
1915 }
1916
1917 fd_table[fd] = 0;
1918
1919 if(!(fde->state & FDE_DONT_CLOSE)) {
1920 dump_fde(fde, "close");
1921 adb_close(fde->fd);
1922 }
1923}
1924
1925static void fdevent_plist_enqueue(fdevent *node)
1926{
1927 fdevent *list = &list_pending;
1928
1929 node->next = list;
1930 node->prev = list->prev;
1931 node->prev->next = node;
1932 list->prev = node;
1933}
1934
1935static void fdevent_plist_remove(fdevent *node)
1936{
1937 node->prev->next = node->next;
1938 node->next->prev = node->prev;
1939 node->next = 0;
1940 node->prev = 0;
1941}
1942
1943static fdevent *fdevent_plist_dequeue(void)
1944{
1945 fdevent *list = &list_pending;
1946 fdevent *node = list->next;
1947
1948 if(node == list) return 0;
1949
1950 list->next = node->next;
1951 list->next->prev = list;
1952 node->next = 0;
1953 node->prev = 0;
1954
1955 return node;
1956}
1957
1958fdevent *fdevent_create(int fd, fd_func func, void *arg)
1959{
1960 fdevent *fde = (fdevent*) malloc(sizeof(fdevent));
1961 if(fde == 0) return 0;
1962 fdevent_install(fde, fd, func, arg);
1963 fde->state |= FDE_CREATED;
1964 return fde;
1965}
1966
1967void fdevent_destroy(fdevent *fde)
1968{
1969 if(fde == 0) return;
1970 if(!(fde->state & FDE_CREATED)) {
1971 FATAL("fde %p not created by fdevent_create()\n", fde);
1972 }
1973 fdevent_remove(fde);
1974}
1975
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001976void fdevent_install(fdevent *fde, int fd, fd_func func, void *arg)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001977{
1978 memset(fde, 0, sizeof(fdevent));
1979 fde->state = FDE_ACTIVE;
1980 fde->fd = fd;
1981 fde->func = func;
1982 fde->arg = arg;
1983
1984 fdevent_register(fde);
1985 dump_fde(fde, "connect");
1986 fdevent_connect(fde);
1987 fde->state |= FDE_ACTIVE;
1988}
1989
1990void fdevent_remove(fdevent *fde)
1991{
1992 if(fde->state & FDE_PENDING) {
1993 fdevent_plist_remove(fde);
1994 }
1995
1996 if(fde->state & FDE_ACTIVE) {
1997 fdevent_disconnect(fde);
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08001998 dump_fde(fde, "disconnect");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001999 fdevent_unregister(fde);
2000 }
2001
2002 fde->state = 0;
2003 fde->events = 0;
2004}
2005
2006
2007void fdevent_set(fdevent *fde, unsigned events)
2008{
2009 events &= FDE_EVENTMASK;
2010
2011 if((fde->state & FDE_EVENTMASK) == (int)events) return;
2012
2013 if(fde->state & FDE_ACTIVE) {
2014 fdevent_update(fde, events);
2015 dump_fde(fde, "update");
2016 }
2017
2018 fde->state = (fde->state & FDE_STATEMASK) | events;
2019
2020 if(fde->state & FDE_PENDING) {
2021 /* if we're pending, make sure
2022 ** we don't signal an event that
2023 ** is no longer wanted.
2024 */
2025 fde->events &= (~events);
2026 if(fde->events == 0) {
2027 fdevent_plist_remove(fde);
2028 fde->state &= (~FDE_PENDING);
2029 }
2030 }
2031}
2032
2033void fdevent_add(fdevent *fde, unsigned events)
2034{
2035 fdevent_set(
2036 fde, (fde->state & FDE_EVENTMASK) | (events & FDE_EVENTMASK));
2037}
2038
2039void fdevent_del(fdevent *fde, unsigned events)
2040{
2041 fdevent_set(
2042 fde, (fde->state & FDE_EVENTMASK) & (~(events & FDE_EVENTMASK)));
2043}
2044
2045void fdevent_loop()
2046{
2047 fdevent *fde;
2048
2049 for(;;) {
2050#if DEBUG
2051 fprintf(stderr,"--- ---- waiting for events\n");
2052#endif
2053 fdevent_process();
2054
2055 while((fde = fdevent_plist_dequeue())) {
2056 unsigned events = fde->events;
2057 fde->events = 0;
2058 fde->state &= (~FDE_PENDING);
2059 dump_fde(fde, "callback");
2060 fde->func(fde->fd, events, fde->arg);
2061 }
2062 }
2063}
2064
2065/** FILE EVENT HOOKS
2066 **/
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +02002067
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002068static void _event_file_prepare( EventHook hook )
2069{
2070 if (hook->wanted & (FDE_READ|FDE_WRITE)) {
2071 /* we can always read/write */
2072 hook->ready |= hook->wanted & (FDE_READ|FDE_WRITE);
2073 }
2074}
2075
2076static int _event_file_peek( EventHook hook )
2077{
2078 return (hook->wanted & (FDE_READ|FDE_WRITE));
2079}
2080
2081static void _fh_file_hook( FH f, int events, EventHook hook )
2082{
2083 hook->h = f->fh_handle;
2084 hook->prepare = _event_file_prepare;
2085 hook->peek = _event_file_peek;
2086}
2087
2088/** SOCKET EVENT HOOKS
2089 **/
2090
2091static void _event_socket_verify( EventHook hook, WSANETWORKEVENTS* evts )
2092{
2093 if ( evts->lNetworkEvents & (FD_READ|FD_ACCEPT|FD_CLOSE) ) {
2094 if (hook->wanted & FDE_READ)
2095 hook->ready |= FDE_READ;
2096 if ((evts->iErrorCode[FD_READ] != 0) && hook->wanted & FDE_ERROR)
2097 hook->ready |= FDE_ERROR;
2098 }
2099 if ( evts->lNetworkEvents & (FD_WRITE|FD_CONNECT|FD_CLOSE) ) {
2100 if (hook->wanted & FDE_WRITE)
2101 hook->ready |= FDE_WRITE;
2102 if ((evts->iErrorCode[FD_WRITE] != 0) && hook->wanted & FDE_ERROR)
2103 hook->ready |= FDE_ERROR;
2104 }
2105 if ( evts->lNetworkEvents & FD_OOB ) {
2106 if (hook->wanted & FDE_ERROR)
2107 hook->ready |= FDE_ERROR;
2108 }
2109}
2110
2111static void _event_socket_prepare( EventHook hook )
2112{
2113 WSANETWORKEVENTS evts;
2114
2115 /* look if some of the events we want already happened ? */
2116 if (!WSAEnumNetworkEvents( hook->fh->fh_socket, NULL, &evts ))
2117 _event_socket_verify( hook, &evts );
2118}
2119
2120static int _socket_wanted_to_flags( int wanted )
2121{
2122 int flags = 0;
2123 if (wanted & FDE_READ)
2124 flags |= FD_READ | FD_ACCEPT | FD_CLOSE;
2125
2126 if (wanted & FDE_WRITE)
2127 flags |= FD_WRITE | FD_CONNECT | FD_CLOSE;
2128
2129 if (wanted & FDE_ERROR)
2130 flags |= FD_OOB;
2131
2132 return flags;
2133}
2134
2135static int _event_socket_start( EventHook hook )
2136{
2137 /* create an event which we're going to wait for */
2138 FH fh = hook->fh;
2139 long flags = _socket_wanted_to_flags( hook->wanted );
2140
2141 hook->h = fh->event;
2142 if (hook->h == INVALID_HANDLE_VALUE) {
2143 D( "_event_socket_start: no event for %s\n", fh->name );
2144 return 0;
2145 }
2146
2147 if ( flags != fh->mask ) {
2148 D( "_event_socket_start: hooking %s for %x (flags %ld)\n", hook->fh->name, hook->wanted, flags );
2149 if ( WSAEventSelect( fh->fh_socket, hook->h, flags ) ) {
2150 D( "_event_socket_start: WSAEventSelect() for %s failed, error %d\n", hook->fh->name, WSAGetLastError() );
2151 CloseHandle( hook->h );
2152 hook->h = INVALID_HANDLE_VALUE;
2153 exit(1);
2154 return 0;
2155 }
2156 fh->mask = flags;
2157 }
2158 return 1;
2159}
2160
2161static void _event_socket_stop( EventHook hook )
2162{
2163 hook->h = INVALID_HANDLE_VALUE;
2164}
2165
2166static int _event_socket_check( EventHook hook )
2167{
2168 int result = 0;
2169 FH fh = hook->fh;
2170 WSANETWORKEVENTS evts;
2171
2172 if (!WSAEnumNetworkEvents( fh->fh_socket, hook->h, &evts ) ) {
2173 _event_socket_verify( hook, &evts );
2174 result = (hook->ready != 0);
2175 if (result) {
2176 ResetEvent( hook->h );
2177 }
2178 }
2179 D( "_event_socket_check %s returns %d\n", fh->name, result );
2180 return result;
2181}
2182
2183static int _event_socket_peek( EventHook hook )
2184{
2185 WSANETWORKEVENTS evts;
2186 FH fh = hook->fh;
2187
2188 /* look if some of the events we want already happened ? */
2189 if (!WSAEnumNetworkEvents( fh->fh_socket, NULL, &evts )) {
2190 _event_socket_verify( hook, &evts );
2191 if (hook->ready)
2192 ResetEvent( hook->h );
2193 }
2194
2195 return hook->ready != 0;
2196}
2197
2198
2199
2200static void _fh_socket_hook( FH f, int events, EventHook hook )
2201{
2202 hook->prepare = _event_socket_prepare;
2203 hook->start = _event_socket_start;
2204 hook->stop = _event_socket_stop;
2205 hook->check = _event_socket_check;
2206 hook->peek = _event_socket_peek;
2207
Spencer Low5200c662015-07-30 23:07:55 -07002208 // TODO: check return value?
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002209 _event_socket_start( hook );
2210}
2211
2212/** SOCKETPAIR EVENT HOOKS
2213 **/
2214
2215static void _event_socketpair_prepare( EventHook hook )
2216{
2217 FH fh = hook->fh;
2218 SocketPair pair = fh->fh_pair;
2219 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2220 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2221
2222 if (hook->wanted & FDE_READ && rbip->can_read)
2223 hook->ready |= FDE_READ;
2224
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08002225 if (hook->wanted & FDE_WRITE && wbip->can_write)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002226 hook->ready |= FDE_WRITE;
2227 }
2228
2229 static int _event_socketpair_start( EventHook hook )
2230 {
2231 FH fh = hook->fh;
2232 SocketPair pair = fh->fh_pair;
2233 BipBuffer rbip = (pair->a_fd == fh) ? &pair->b2a_bip : &pair->a2b_bip;
2234 BipBuffer wbip = (pair->a_fd == fh) ? &pair->a2b_bip : &pair->b2a_bip;
2235
2236 if (hook->wanted == FDE_READ)
2237 hook->h = rbip->evt_read;
2238
2239 else if (hook->wanted == FDE_WRITE)
2240 hook->h = wbip->evt_write;
2241
2242 else {
2243 D("_event_socketpair_start: can't handle FDE_READ+FDE_WRITE\n" );
2244 return 0;
2245 }
Vladimir Chtchetkinece480832011-11-30 10:20:27 -08002246 D( "_event_socketpair_start: hook %s for %x wanted=%x\n",
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08002247 hook->fh->name, _fh_to_int(fh), hook->wanted);
2248 return 1;
2249}
2250
2251static int _event_socketpair_peek( EventHook hook )
2252{
2253 _event_socketpair_prepare( hook );
2254 return hook->ready != 0;
2255}
2256
2257static void _fh_socketpair_hook( FH fh, int events, EventHook hook )
2258{
2259 hook->prepare = _event_socketpair_prepare;
2260 hook->start = _event_socketpair_start;
2261 hook->peek = _event_socketpair_peek;
2262}
2263
2264
2265void
2266adb_sysdeps_init( void )
2267{
2268#define ADB_MUTEX(x) InitializeCriticalSection( & x );
2269#include "mutex_list.h"
2270 InitializeCriticalSection( &_win32_lock );
2271}
2272
Spencer Low50184062015-03-01 15:06:21 -08002273/**************************************************************************/
2274/**************************************************************************/
2275/***** *****/
2276/***** Console Window Terminal Emulation *****/
2277/***** *****/
2278/**************************************************************************/
2279/**************************************************************************/
2280
2281// This reads input from a Win32 console window and translates it into Unix
2282// terminal-style sequences. This emulates mostly Gnome Terminal (in Normal
2283// mode, not Application mode), which itself emulates xterm. Gnome Terminal
2284// is emulated instead of xterm because it is probably more popular than xterm:
2285// Ubuntu's default Ctrl-Alt-T shortcut opens Gnome Terminal, Gnome Terminal
2286// supports modern fonts, etc. It seems best to emulate the terminal that most
2287// Android developers use because they'll fix apps (the shell, etc.) to keep
2288// working with that terminal's emulation.
2289//
2290// The point of this emulation is not to be perfect or to solve all issues with
2291// console windows on Windows, but to be better than the original code which
2292// just called read() (which called ReadFile(), which called ReadConsoleA())
2293// which did not support Ctrl-C, tab completion, shell input line editing
2294// keys, server echo, and more.
2295//
2296// This implementation reconfigures the console with SetConsoleMode(), then
2297// calls ReadConsoleInput() to get raw input which it remaps to Unix
2298// terminal-style sequences which is returned via unix_read() which is used
2299// by the 'adb shell' command.
2300//
2301// Code organization:
2302//
2303// * stdin_raw_init() and stdin_raw_restore() reconfigure the console.
2304// * unix_read() detects console windows (as opposed to pipes, files, etc.).
2305// * _console_read() is the main code of the emulation.
2306
2307
2308// Read an input record from the console; one that should be processed.
2309static bool _get_interesting_input_record_uncached(const HANDLE console,
2310 INPUT_RECORD* const input_record) {
2311 for (;;) {
2312 DWORD read_count = 0;
2313 memset(input_record, 0, sizeof(*input_record));
2314 if (!ReadConsoleInputA(console, input_record, 1, &read_count)) {
2315 D("_get_interesting_input_record_uncached: ReadConsoleInputA() "
2316 "failure, error %ld\n", GetLastError());
2317 errno = EIO;
2318 return false;
2319 }
2320
2321 if (read_count == 0) { // should be impossible
2322 fatal("ReadConsoleInputA returned 0");
2323 }
2324
2325 if (read_count != 1) { // should be impossible
2326 fatal("ReadConsoleInputA did not return one input record");
2327 }
2328
2329 if ((input_record->EventType == KEY_EVENT) &&
2330 (input_record->Event.KeyEvent.bKeyDown)) {
2331 if (input_record->Event.KeyEvent.wRepeatCount == 0) {
2332 fatal("ReadConsoleInputA returned a key event with zero repeat"
2333 " count");
2334 }
2335
2336 // Got an interesting INPUT_RECORD, so return
2337 return true;
2338 }
2339 }
2340}
2341
2342// Cached input record (in case _console_read() is passed a buffer that doesn't
2343// have enough space to fit wRepeatCount number of key sequences). A non-zero
2344// wRepeatCount indicates that a record is cached.
2345static INPUT_RECORD _win32_input_record;
2346
2347// Get the next KEY_EVENT_RECORD that should be processed.
2348static KEY_EVENT_RECORD* _get_key_event_record(const HANDLE console) {
2349 // If nothing cached, read directly from the console until we get an
2350 // interesting record.
2351 if (_win32_input_record.Event.KeyEvent.wRepeatCount == 0) {
2352 if (!_get_interesting_input_record_uncached(console,
2353 &_win32_input_record)) {
2354 // There was an error, so make sure wRepeatCount is zero because
2355 // that signifies no cached input record.
2356 _win32_input_record.Event.KeyEvent.wRepeatCount = 0;
2357 return NULL;
2358 }
2359 }
2360
2361 return &_win32_input_record.Event.KeyEvent;
2362}
2363
2364static __inline__ bool _is_shift_pressed(const DWORD control_key_state) {
2365 return (control_key_state & SHIFT_PRESSED) != 0;
2366}
2367
2368static __inline__ bool _is_ctrl_pressed(const DWORD control_key_state) {
2369 return (control_key_state & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2370}
2371
2372static __inline__ bool _is_alt_pressed(const DWORD control_key_state) {
2373 return (control_key_state & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) != 0;
2374}
2375
2376static __inline__ bool _is_numlock_on(const DWORD control_key_state) {
2377 return (control_key_state & NUMLOCK_ON) != 0;
2378}
2379
2380static __inline__ bool _is_capslock_on(const DWORD control_key_state) {
2381 return (control_key_state & CAPSLOCK_ON) != 0;
2382}
2383
2384static __inline__ bool _is_enhanced_key(const DWORD control_key_state) {
2385 return (control_key_state & ENHANCED_KEY) != 0;
2386}
2387
2388// Constants from MSDN for ToAscii().
2389static const BYTE TOASCII_KEY_OFF = 0x00;
2390static const BYTE TOASCII_KEY_DOWN = 0x80;
2391static const BYTE TOASCII_KEY_TOGGLED_ON = 0x01; // for CapsLock
2392
2393// Given a key event, ignore a modifier key and return the character that was
2394// entered without the modifier. Writes to *ch and returns the number of bytes
2395// written.
2396static size_t _get_char_ignoring_modifier(char* const ch,
2397 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state,
2398 const WORD modifier) {
2399 // If there is no character from Windows, try ignoring the specified
2400 // modifier and look for a character. Note that if AltGr is being used,
2401 // there will be a character from Windows.
2402 if (key_event->uChar.AsciiChar == '\0') {
2403 // Note that we read the control key state from the passed in argument
2404 // instead of from key_event since the argument has been normalized.
2405 if (((modifier == VK_SHIFT) &&
2406 _is_shift_pressed(control_key_state)) ||
2407 ((modifier == VK_CONTROL) &&
2408 _is_ctrl_pressed(control_key_state)) ||
2409 ((modifier == VK_MENU) && _is_alt_pressed(control_key_state))) {
2410
2411 BYTE key_state[256] = {0};
2412 key_state[VK_SHIFT] = _is_shift_pressed(control_key_state) ?
2413 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2414 key_state[VK_CONTROL] = _is_ctrl_pressed(control_key_state) ?
2415 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2416 key_state[VK_MENU] = _is_alt_pressed(control_key_state) ?
2417 TOASCII_KEY_DOWN : TOASCII_KEY_OFF;
2418 key_state[VK_CAPITAL] = _is_capslock_on(control_key_state) ?
2419 TOASCII_KEY_TOGGLED_ON : TOASCII_KEY_OFF;
2420
2421 // cause this modifier to be ignored
2422 key_state[modifier] = TOASCII_KEY_OFF;
2423
2424 WORD translated = 0;
2425 if (ToAscii(key_event->wVirtualKeyCode,
2426 key_event->wVirtualScanCode, key_state, &translated, 0) == 1) {
2427 // Ignoring the modifier, we found a character.
2428 *ch = (CHAR)translated;
2429 return 1;
2430 }
2431 }
2432 }
2433
2434 // Just use whatever Windows told us originally.
2435 *ch = key_event->uChar.AsciiChar;
2436
2437 // If the character from Windows is NULL, return a size of zero.
2438 return (*ch == '\0') ? 0 : 1;
2439}
2440
2441// If a Ctrl key is pressed, lookup the character, ignoring the Ctrl key,
2442// but taking into account the shift key. This is because for a sequence like
2443// Ctrl-Alt-0, we want to find the character '0' and for Ctrl-Alt-Shift-0,
2444// we want to find the character ')'.
2445//
2446// Note that Windows doesn't seem to pass bKeyDown for Ctrl-Shift-NoAlt-0
2447// because it is the default key-sequence to switch the input language.
2448// This is configurable in the Region and Language control panel.
2449static __inline__ size_t _get_non_control_char(char* const ch,
2450 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2451 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2452 VK_CONTROL);
2453}
2454
2455// Get without Alt.
2456static __inline__ size_t _get_non_alt_char(char* const ch,
2457 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2458 return _get_char_ignoring_modifier(ch, key_event, control_key_state,
2459 VK_MENU);
2460}
2461
2462// Ignore the control key, find the character from Windows, and apply any
2463// Control key mappings (for example, Ctrl-2 is a NULL character). Writes to
2464// *pch and returns number of bytes written.
2465static size_t _get_control_character(char* const pch,
2466 const KEY_EVENT_RECORD* const key_event, const DWORD control_key_state) {
2467 const size_t len = _get_non_control_char(pch, key_event,
2468 control_key_state);
2469
2470 if ((len == 1) && _is_ctrl_pressed(control_key_state)) {
2471 char ch = *pch;
2472 switch (ch) {
2473 case '2':
2474 case '@':
2475 case '`':
2476 ch = '\0';
2477 break;
2478 case '3':
2479 case '[':
2480 case '{':
2481 ch = '\x1b';
2482 break;
2483 case '4':
2484 case '\\':
2485 case '|':
2486 ch = '\x1c';
2487 break;
2488 case '5':
2489 case ']':
2490 case '}':
2491 ch = '\x1d';
2492 break;
2493 case '6':
2494 case '^':
2495 case '~':
2496 ch = '\x1e';
2497 break;
2498 case '7':
2499 case '-':
2500 case '_':
2501 ch = '\x1f';
2502 break;
2503 case '8':
2504 ch = '\x7f';
2505 break;
2506 case '/':
2507 if (!_is_alt_pressed(control_key_state)) {
2508 ch = '\x1f';
2509 }
2510 break;
2511 case '?':
2512 if (!_is_alt_pressed(control_key_state)) {
2513 ch = '\x7f';
2514 }
2515 break;
2516 }
2517 *pch = ch;
2518 }
2519
2520 return len;
2521}
2522
2523static DWORD _normalize_altgr_control_key_state(
2524 const KEY_EVENT_RECORD* const key_event) {
2525 DWORD control_key_state = key_event->dwControlKeyState;
2526
2527 // If we're in an AltGr situation where the AltGr key is down (depending on
2528 // the keyboard layout, that might be the physical right alt key which
2529 // produces a control_key_state where Right-Alt and Left-Ctrl are down) or
2530 // AltGr-equivalent keys are down (any Ctrl key + any Alt key), and we have
2531 // a character (which indicates that there was an AltGr mapping), then act
2532 // as if alt and control are not really down for the purposes of modifiers.
2533 // This makes it so that if the user with, say, a German keyboard layout
2534 // presses AltGr-] (which we see as Right-Alt + Left-Ctrl + key), we just
2535 // output the key and we don't see the Alt and Ctrl keys.
2536 if (_is_ctrl_pressed(control_key_state) &&
2537 _is_alt_pressed(control_key_state)
2538 && (key_event->uChar.AsciiChar != '\0')) {
2539 // Try to remove as few bits as possible to improve our chances of
2540 // detecting combinations like Left-Alt + AltGr, Right-Ctrl + AltGr, or
2541 // Left-Alt + Right-Ctrl + AltGr.
2542 if ((control_key_state & RIGHT_ALT_PRESSED) != 0) {
2543 // Remove Right-Alt.
2544 control_key_state &= ~RIGHT_ALT_PRESSED;
2545 // If uChar is set, a Ctrl key is pressed, and Right-Alt is
2546 // pressed, Left-Ctrl is almost always set, except if the user
2547 // presses Right-Ctrl, then AltGr (in that specific order) for
2548 // whatever reason. At any rate, make sure the bit is not set.
2549 control_key_state &= ~LEFT_CTRL_PRESSED;
2550 } else if ((control_key_state & LEFT_ALT_PRESSED) != 0) {
2551 // Remove Left-Alt.
2552 control_key_state &= ~LEFT_ALT_PRESSED;
2553 // Whichever Ctrl key is down, remove it from the state. We only
2554 // remove one key, to improve our chances of detecting the
2555 // corner-case of Left-Ctrl + Left-Alt + Right-Ctrl.
2556 if ((control_key_state & LEFT_CTRL_PRESSED) != 0) {
2557 // Remove Left-Ctrl.
2558 control_key_state &= ~LEFT_CTRL_PRESSED;
2559 } else if ((control_key_state & RIGHT_CTRL_PRESSED) != 0) {
2560 // Remove Right-Ctrl.
2561 control_key_state &= ~RIGHT_CTRL_PRESSED;
2562 }
2563 }
2564
2565 // Note that this logic isn't 100% perfect because Windows doesn't
2566 // allow us to detect all combinations because a physical AltGr key
2567 // press shows up as two bits, plus some combinations are ambiguous
2568 // about what is actually physically pressed.
2569 }
2570
2571 return control_key_state;
2572}
2573
2574// If NumLock is on and Shift is pressed, SHIFT_PRESSED is not set in
2575// dwControlKeyState for the following keypad keys: period, 0-9. If we detect
2576// this scenario, set the SHIFT_PRESSED bit so we can add modifiers
2577// appropriately.
2578static DWORD _normalize_keypad_control_key_state(const WORD vk,
2579 const DWORD control_key_state) {
2580 if (!_is_numlock_on(control_key_state)) {
2581 return control_key_state;
2582 }
2583 if (!_is_enhanced_key(control_key_state)) {
2584 switch (vk) {
2585 case VK_INSERT: // 0
2586 case VK_DELETE: // .
2587 case VK_END: // 1
2588 case VK_DOWN: // 2
2589 case VK_NEXT: // 3
2590 case VK_LEFT: // 4
2591 case VK_CLEAR: // 5
2592 case VK_RIGHT: // 6
2593 case VK_HOME: // 7
2594 case VK_UP: // 8
2595 case VK_PRIOR: // 9
2596 return control_key_state | SHIFT_PRESSED;
2597 }
2598 }
2599
2600 return control_key_state;
2601}
2602
2603static const char* _get_keypad_sequence(const DWORD control_key_state,
2604 const char* const normal, const char* const shifted) {
2605 if (_is_shift_pressed(control_key_state)) {
2606 // Shift is pressed and NumLock is off
2607 return shifted;
2608 } else {
2609 // Shift is not pressed and NumLock is off, or,
2610 // Shift is pressed and NumLock is on, in which case we want the
2611 // NumLock and Shift to neutralize each other, thus, we want the normal
2612 // sequence.
2613 return normal;
2614 }
2615 // If Shift is not pressed and NumLock is on, a different virtual key code
2616 // is returned by Windows, which can be taken care of by a different case
2617 // statement in _console_read().
2618}
2619
2620// Write sequence to buf and return the number of bytes written.
2621static size_t _get_modifier_sequence(char* const buf, const WORD vk,
2622 DWORD control_key_state, const char* const normal) {
2623 // Copy the base sequence into buf.
2624 const size_t len = strlen(normal);
2625 memcpy(buf, normal, len);
2626
2627 int code = 0;
2628
2629 control_key_state = _normalize_keypad_control_key_state(vk,
2630 control_key_state);
2631
2632 if (_is_shift_pressed(control_key_state)) {
2633 code |= 0x1;
2634 }
2635 if (_is_alt_pressed(control_key_state)) { // any alt key pressed
2636 code |= 0x2;
2637 }
2638 if (_is_ctrl_pressed(control_key_state)) { // any control key pressed
2639 code |= 0x4;
2640 }
2641 // If some modifier was held down, then we need to insert the modifier code
2642 if (code != 0) {
2643 if (len == 0) {
2644 // Should be impossible because caller should pass a string of
2645 // non-zero length.
2646 return 0;
2647 }
2648 size_t index = len - 1;
2649 const char lastChar = buf[index];
2650 if (lastChar != '~') {
2651 buf[index++] = '1';
2652 }
2653 buf[index++] = ';'; // modifier separator
2654 // 2 = shift, 3 = alt, 4 = shift & alt, 5 = control,
2655 // 6 = shift & control, 7 = alt & control, 8 = shift & alt & control
2656 buf[index++] = '1' + code;
2657 buf[index++] = lastChar; // move ~ (or other last char) to the end
2658 return index;
2659 }
2660 return len;
2661}
2662
2663// Write sequence to buf and return the number of bytes written.
2664static size_t _get_modifier_keypad_sequence(char* const buf, const WORD vk,
2665 const DWORD control_key_state, const char* const normal,
2666 const char shifted) {
2667 if (_is_shift_pressed(control_key_state)) {
2668 // Shift is pressed and NumLock is off
2669 if (shifted != '\0') {
2670 buf[0] = shifted;
2671 return sizeof(buf[0]);
2672 } else {
2673 return 0;
2674 }
2675 } else {
2676 // Shift is not pressed and NumLock is off, or,
2677 // Shift is pressed and NumLock is on, in which case we want the
2678 // NumLock and Shift to neutralize each other, thus, we want the normal
2679 // sequence.
2680 return _get_modifier_sequence(buf, vk, control_key_state, normal);
2681 }
2682 // If Shift is not pressed and NumLock is on, a different virtual key code
2683 // is returned by Windows, which can be taken care of by a different case
2684 // statement in _console_read().
2685}
2686
2687// The decimal key on the keypad produces a '.' for U.S. English and a ',' for
2688// Standard German. Figure this out at runtime so we know what to output for
2689// Shift-VK_DELETE.
2690static char _get_decimal_char() {
2691 return (char)MapVirtualKeyA(VK_DECIMAL, MAPVK_VK_TO_CHAR);
2692}
2693
2694// Prefix the len bytes in buf with the escape character, and then return the
2695// new buffer length.
2696size_t _escape_prefix(char* const buf, const size_t len) {
2697 // If nothing to prefix, don't do anything. We might be called with
2698 // len == 0, if alt was held down with a dead key which produced nothing.
2699 if (len == 0) {
2700 return 0;
2701 }
2702
2703 memmove(&buf[1], buf, len);
2704 buf[0] = '\x1b';
2705 return len + 1;
2706}
2707
2708// Writes to buffer buf (of length len), returning number of bytes written or
2709// -1 on error. Never returns zero because Win32 consoles are never 'closed'
2710// (as far as I can tell).
2711static int _console_read(const HANDLE console, void* buf, size_t len) {
2712 for (;;) {
2713 KEY_EVENT_RECORD* const key_event = _get_key_event_record(console);
2714 if (key_event == NULL) {
2715 return -1;
2716 }
2717
2718 const WORD vk = key_event->wVirtualKeyCode;
2719 const CHAR ch = key_event->uChar.AsciiChar;
2720 const DWORD control_key_state = _normalize_altgr_control_key_state(
2721 key_event);
2722
2723 // The following emulation code should write the output sequence to
2724 // either seqstr or to seqbuf and seqbuflen.
2725 const char* seqstr = NULL; // NULL terminated C-string
2726 // Enough space for max sequence string below, plus modifiers and/or
2727 // escape prefix.
2728 char seqbuf[16];
2729 size_t seqbuflen = 0; // Space used in seqbuf.
2730
2731#define MATCH(vk, normal) \
2732 case (vk): \
2733 { \
2734 seqstr = (normal); \
2735 } \
2736 break;
2737
2738 // Modifier keys should affect the output sequence.
2739#define MATCH_MODIFIER(vk, normal) \
2740 case (vk): \
2741 { \
2742 seqbuflen = _get_modifier_sequence(seqbuf, (vk), \
2743 control_key_state, (normal)); \
2744 } \
2745 break;
2746
2747 // The shift key should affect the output sequence.
2748#define MATCH_KEYPAD(vk, normal, shifted) \
2749 case (vk): \
2750 { \
2751 seqstr = _get_keypad_sequence(control_key_state, (normal), \
2752 (shifted)); \
2753 } \
2754 break;
2755
2756 // The shift key and other modifier keys should affect the output
2757 // sequence.
2758#define MATCH_MODIFIER_KEYPAD(vk, normal, shifted) \
2759 case (vk): \
2760 { \
2761 seqbuflen = _get_modifier_keypad_sequence(seqbuf, (vk), \
2762 control_key_state, (normal), (shifted)); \
2763 } \
2764 break;
2765
2766#define ESC "\x1b"
2767#define CSI ESC "["
2768#define SS3 ESC "O"
2769
2770 // Only support normal mode, not application mode.
2771
2772 // Enhanced keys:
2773 // * 6-pack: insert, delete, home, end, page up, page down
2774 // * cursor keys: up, down, right, left
2775 // * keypad: divide, enter
2776 // * Undocumented: VK_PAUSE (Ctrl-NumLock), VK_SNAPSHOT,
2777 // VK_CANCEL (Ctrl-Pause/Break), VK_NUMLOCK
2778 if (_is_enhanced_key(control_key_state)) {
2779 switch (vk) {
2780 case VK_RETURN: // Enter key on keypad
2781 if (_is_ctrl_pressed(control_key_state)) {
2782 seqstr = "\n";
2783 } else {
2784 seqstr = "\r";
2785 }
2786 break;
2787
2788 MATCH_MODIFIER(VK_PRIOR, CSI "5~"); // Page Up
2789 MATCH_MODIFIER(VK_NEXT, CSI "6~"); // Page Down
2790
2791 // gnome-terminal currently sends SS3 "F" and SS3 "H", but that
2792 // will be fixed soon to match xterm which sends CSI "F" and
2793 // CSI "H". https://bugzilla.redhat.com/show_bug.cgi?id=1119764
2794 MATCH(VK_END, CSI "F");
2795 MATCH(VK_HOME, CSI "H");
2796
2797 MATCH_MODIFIER(VK_LEFT, CSI "D");
2798 MATCH_MODIFIER(VK_UP, CSI "A");
2799 MATCH_MODIFIER(VK_RIGHT, CSI "C");
2800 MATCH_MODIFIER(VK_DOWN, CSI "B");
2801
2802 MATCH_MODIFIER(VK_INSERT, CSI "2~");
2803 MATCH_MODIFIER(VK_DELETE, CSI "3~");
2804
2805 MATCH(VK_DIVIDE, "/");
2806 }
2807 } else { // Non-enhanced keys:
2808 switch (vk) {
2809 case VK_BACK: // backspace
2810 if (_is_alt_pressed(control_key_state)) {
2811 seqstr = ESC "\x7f";
2812 } else {
2813 seqstr = "\x7f";
2814 }
2815 break;
2816
2817 case VK_TAB:
2818 if (_is_shift_pressed(control_key_state)) {
2819 seqstr = CSI "Z";
2820 } else {
2821 seqstr = "\t";
2822 }
2823 break;
2824
2825 // Number 5 key in keypad when NumLock is off, or if NumLock is
2826 // on and Shift is down.
2827 MATCH_KEYPAD(VK_CLEAR, CSI "E", "5");
2828
2829 case VK_RETURN: // Enter key on main keyboard
2830 if (_is_alt_pressed(control_key_state)) {
2831 seqstr = ESC "\n";
2832 } else if (_is_ctrl_pressed(control_key_state)) {
2833 seqstr = "\n";
2834 } else {
2835 seqstr = "\r";
2836 }
2837 break;
2838
2839 // VK_ESCAPE: Don't do any special handling. The OS uses many
2840 // of the sequences with Escape and many of the remaining
2841 // sequences don't produce bKeyDown messages, only !bKeyDown
2842 // for whatever reason.
2843
2844 case VK_SPACE:
2845 if (_is_alt_pressed(control_key_state)) {
2846 seqstr = ESC " ";
2847 } else if (_is_ctrl_pressed(control_key_state)) {
2848 seqbuf[0] = '\0'; // NULL char
2849 seqbuflen = 1;
2850 } else {
2851 seqstr = " ";
2852 }
2853 break;
2854
2855 MATCH_MODIFIER_KEYPAD(VK_PRIOR, CSI "5~", '9'); // Page Up
2856 MATCH_MODIFIER_KEYPAD(VK_NEXT, CSI "6~", '3'); // Page Down
2857
2858 MATCH_KEYPAD(VK_END, CSI "4~", "1");
2859 MATCH_KEYPAD(VK_HOME, CSI "1~", "7");
2860
2861 MATCH_MODIFIER_KEYPAD(VK_LEFT, CSI "D", '4');
2862 MATCH_MODIFIER_KEYPAD(VK_UP, CSI "A", '8');
2863 MATCH_MODIFIER_KEYPAD(VK_RIGHT, CSI "C", '6');
2864 MATCH_MODIFIER_KEYPAD(VK_DOWN, CSI "B", '2');
2865
2866 MATCH_MODIFIER_KEYPAD(VK_INSERT, CSI "2~", '0');
2867 MATCH_MODIFIER_KEYPAD(VK_DELETE, CSI "3~",
2868 _get_decimal_char());
2869
2870 case 0x30: // 0
2871 case 0x31: // 1
2872 case 0x39: // 9
2873 case VK_OEM_1: // ;:
2874 case VK_OEM_PLUS: // =+
2875 case VK_OEM_COMMA: // ,<
2876 case VK_OEM_PERIOD: // .>
2877 case VK_OEM_7: // '"
2878 case VK_OEM_102: // depends on keyboard, could be <> or \|
2879 case VK_OEM_2: // /?
2880 case VK_OEM_3: // `~
2881 case VK_OEM_4: // [{
2882 case VK_OEM_5: // \|
2883 case VK_OEM_6: // ]}
2884 {
2885 seqbuflen = _get_control_character(seqbuf, key_event,
2886 control_key_state);
2887
2888 if (_is_alt_pressed(control_key_state)) {
2889 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2890 }
2891 }
2892 break;
2893
2894 case 0x32: // 2
2895 case 0x36: // 6
2896 case VK_OEM_MINUS: // -_
2897 {
2898 seqbuflen = _get_control_character(seqbuf, key_event,
2899 control_key_state);
2900
2901 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2902 // prefix with escape.
2903 if (_is_alt_pressed(control_key_state) &&
2904 !(_is_ctrl_pressed(control_key_state) &&
2905 !_is_shift_pressed(control_key_state))) {
2906 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2907 }
2908 }
2909 break;
2910
2911 case 0x33: // 3
2912 case 0x34: // 4
2913 case 0x35: // 5
2914 case 0x37: // 7
2915 case 0x38: // 8
2916 {
2917 seqbuflen = _get_control_character(seqbuf, key_event,
2918 control_key_state);
2919
2920 // If Alt is pressed and it isn't Ctrl-Alt-ShiftUp, then
2921 // prefix with escape.
2922 if (_is_alt_pressed(control_key_state) &&
2923 !(_is_ctrl_pressed(control_key_state) &&
2924 !_is_shift_pressed(control_key_state))) {
2925 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2926 }
2927 }
2928 break;
2929
2930 case 0x41: // a
2931 case 0x42: // b
2932 case 0x43: // c
2933 case 0x44: // d
2934 case 0x45: // e
2935 case 0x46: // f
2936 case 0x47: // g
2937 case 0x48: // h
2938 case 0x49: // i
2939 case 0x4a: // j
2940 case 0x4b: // k
2941 case 0x4c: // l
2942 case 0x4d: // m
2943 case 0x4e: // n
2944 case 0x4f: // o
2945 case 0x50: // p
2946 case 0x51: // q
2947 case 0x52: // r
2948 case 0x53: // s
2949 case 0x54: // t
2950 case 0x55: // u
2951 case 0x56: // v
2952 case 0x57: // w
2953 case 0x58: // x
2954 case 0x59: // y
2955 case 0x5a: // z
2956 {
2957 seqbuflen = _get_non_alt_char(seqbuf, key_event,
2958 control_key_state);
2959
2960 // If Alt is pressed, then prefix with escape.
2961 if (_is_alt_pressed(control_key_state)) {
2962 seqbuflen = _escape_prefix(seqbuf, seqbuflen);
2963 }
2964 }
2965 break;
2966
2967 // These virtual key codes are generated by the keys on the
2968 // keypad *when NumLock is on* and *Shift is up*.
2969 MATCH(VK_NUMPAD0, "0");
2970 MATCH(VK_NUMPAD1, "1");
2971 MATCH(VK_NUMPAD2, "2");
2972 MATCH(VK_NUMPAD3, "3");
2973 MATCH(VK_NUMPAD4, "4");
2974 MATCH(VK_NUMPAD5, "5");
2975 MATCH(VK_NUMPAD6, "6");
2976 MATCH(VK_NUMPAD7, "7");
2977 MATCH(VK_NUMPAD8, "8");
2978 MATCH(VK_NUMPAD9, "9");
2979
2980 MATCH(VK_MULTIPLY, "*");
2981 MATCH(VK_ADD, "+");
2982 MATCH(VK_SUBTRACT, "-");
2983 // VK_DECIMAL is generated by the . key on the keypad *when
2984 // NumLock is on* and *Shift is up* and the sequence is not
2985 // Ctrl-Alt-NoShift-. (which causes Ctrl-Alt-Del and the
2986 // Windows Security screen to come up).
2987 case VK_DECIMAL:
2988 // U.S. English uses '.', Germany German uses ','.
2989 seqbuflen = _get_non_control_char(seqbuf, key_event,
2990 control_key_state);
2991 break;
2992
2993 MATCH_MODIFIER(VK_F1, SS3 "P");
2994 MATCH_MODIFIER(VK_F2, SS3 "Q");
2995 MATCH_MODIFIER(VK_F3, SS3 "R");
2996 MATCH_MODIFIER(VK_F4, SS3 "S");
2997 MATCH_MODIFIER(VK_F5, CSI "15~");
2998 MATCH_MODIFIER(VK_F6, CSI "17~");
2999 MATCH_MODIFIER(VK_F7, CSI "18~");
3000 MATCH_MODIFIER(VK_F8, CSI "19~");
3001 MATCH_MODIFIER(VK_F9, CSI "20~");
3002 MATCH_MODIFIER(VK_F10, CSI "21~");
3003 MATCH_MODIFIER(VK_F11, CSI "23~");
3004 MATCH_MODIFIER(VK_F12, CSI "24~");
3005
3006 MATCH_MODIFIER(VK_F13, CSI "25~");
3007 MATCH_MODIFIER(VK_F14, CSI "26~");
3008 MATCH_MODIFIER(VK_F15, CSI "28~");
3009 MATCH_MODIFIER(VK_F16, CSI "29~");
3010 MATCH_MODIFIER(VK_F17, CSI "31~");
3011 MATCH_MODIFIER(VK_F18, CSI "32~");
3012 MATCH_MODIFIER(VK_F19, CSI "33~");
3013 MATCH_MODIFIER(VK_F20, CSI "34~");
3014
3015 // MATCH_MODIFIER(VK_F21, ???);
3016 // MATCH_MODIFIER(VK_F22, ???);
3017 // MATCH_MODIFIER(VK_F23, ???);
3018 // MATCH_MODIFIER(VK_F24, ???);
3019 }
3020 }
3021
3022#undef MATCH
3023#undef MATCH_MODIFIER
3024#undef MATCH_KEYPAD
3025#undef MATCH_MODIFIER_KEYPAD
3026#undef ESC
3027#undef CSI
3028#undef SS3
3029
3030 const char* out;
3031 size_t outlen;
3032
3033 // Check for output in any of:
3034 // * seqstr is set (and strlen can be used to determine the length).
3035 // * seqbuf and seqbuflen are set
3036 // Fallback to ch from Windows.
3037 if (seqstr != NULL) {
3038 out = seqstr;
3039 outlen = strlen(seqstr);
3040 } else if (seqbuflen > 0) {
3041 out = seqbuf;
3042 outlen = seqbuflen;
3043 } else if (ch != '\0') {
3044 // Use whatever Windows told us it is.
3045 seqbuf[0] = ch;
3046 seqbuflen = 1;
3047 out = seqbuf;
3048 outlen = seqbuflen;
3049 } else {
3050 // No special handling for the virtual key code and Windows isn't
3051 // telling us a character code, then we don't know how to translate
3052 // the key press.
3053 //
3054 // Consume the input and 'continue' to cause us to get a new key
3055 // event.
3056 D("_console_read: unknown virtual key code: %d, enhanced: %s\n",
3057 vk, _is_enhanced_key(control_key_state) ? "true" : "false");
3058 key_event->wRepeatCount = 0;
3059 continue;
3060 }
3061
3062 int bytesRead = 0;
3063
3064 // put output wRepeatCount times into buf/len
3065 while (key_event->wRepeatCount > 0) {
3066 if (len >= outlen) {
3067 // Write to buf/len
3068 memcpy(buf, out, outlen);
3069 buf = (void*)((char*)buf + outlen);
3070 len -= outlen;
3071 bytesRead += outlen;
3072
3073 // consume the input
3074 --key_event->wRepeatCount;
3075 } else {
3076 // Not enough space, so just leave it in _win32_input_record
3077 // for a subsequent retrieval.
3078 if (bytesRead == 0) {
3079 // We didn't write anything because there wasn't enough
3080 // space to even write one sequence. This should never
3081 // happen if the caller uses sensible buffer sizes
3082 // (i.e. >= maximum sequence length which is probably a
3083 // few bytes long).
3084 D("_console_read: no buffer space to write one sequence; "
3085 "buffer: %ld, sequence: %ld\n", (long)len,
3086 (long)outlen);
3087 errno = ENOMEM;
3088 return -1;
3089 } else {
3090 // Stop trying to write to buf/len, just return whatever
3091 // we wrote so far.
3092 break;
3093 }
3094 }
3095 }
3096
3097 return bytesRead;
3098 }
3099}
3100
3101static DWORD _old_console_mode; // previous GetConsoleMode() result
3102static HANDLE _console_handle; // when set, console mode should be restored
3103
3104void stdin_raw_init(const int fd) {
3105 if (STDIN_FILENO == fd) {
3106 const HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
3107 if ((in == INVALID_HANDLE_VALUE) || (in == NULL)) {
3108 return;
3109 }
3110
3111 if (GetFileType(in) != FILE_TYPE_CHAR) {
3112 // stdin might be a file or pipe.
3113 return;
3114 }
3115
3116 if (!GetConsoleMode(in, &_old_console_mode)) {
3117 // If GetConsoleMode() fails, stdin is probably is not a console.
3118 return;
3119 }
3120
3121 // Disable ENABLE_PROCESSED_INPUT so that Ctrl-C is read instead of
3122 // calling the process Ctrl-C routine (configured by
3123 // SetConsoleCtrlHandler()).
3124 // Disable ENABLE_LINE_INPUT so that input is immediately sent.
3125 // Disable ENABLE_ECHO_INPUT to disable local echo. Disabling this
3126 // flag also seems necessary to have proper line-ending processing.
3127 if (!SetConsoleMode(in, _old_console_mode & ~(ENABLE_PROCESSED_INPUT |
3128 ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT))) {
3129 // This really should not fail.
3130 D("stdin_raw_init: SetConsoleMode() failure, error %ld\n",
3131 GetLastError());
3132 }
3133
3134 // Once this is set, it means that stdin has been configured for
3135 // reading from and that the old console mode should be restored later.
3136 _console_handle = in;
3137
3138 // Note that we don't need to configure C Runtime line-ending
3139 // translation because _console_read() does not call the C Runtime to
3140 // read from the console.
3141 }
3142}
3143
3144void stdin_raw_restore(const int fd) {
3145 if (STDIN_FILENO == fd) {
3146 if (_console_handle != NULL) {
3147 const HANDLE in = _console_handle;
3148 _console_handle = NULL; // clear state
3149
3150 if (!SetConsoleMode(in, _old_console_mode)) {
3151 // This really should not fail.
3152 D("stdin_raw_restore: SetConsoleMode() failure, error %ld\n",
3153 GetLastError());
3154 }
3155 }
3156 }
3157}
3158
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003159// Called by 'adb shell' and 'adb exec-in' to read from stdin.
Spencer Low50184062015-03-01 15:06:21 -08003160int unix_read(int fd, void* buf, size_t len) {
3161 if ((fd == STDIN_FILENO) && (_console_handle != NULL)) {
3162 // If it is a request to read from stdin, and stdin_raw_init() has been
3163 // called, and it successfully configured the console, then read from
3164 // the console using Win32 console APIs and partially emulate a unix
3165 // terminal.
3166 return _console_read(_console_handle, buf, len);
3167 } else {
3168 // Just call into C Runtime which can read from pipes/files and which
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003169 // can do LF/CR translation (which is overridable with _setmode()).
3170 // Undefine the macro that is set in sysdeps.h which bans calls to
3171 // plain read() in favor of unix_read() or adb_read().
3172#pragma push_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003173#undef read
3174 return read(fd, buf, len);
Spencer Low6ac5d7d2015-05-22 20:09:06 -07003175#pragma pop_macro("read")
Spencer Low50184062015-03-01 15:06:21 -08003176 }
3177}