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