• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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 #pragma once
18 
19 /* this file contains system-dependent definitions used by ADB
20  * they're related to threads, sockets and file descriptors
21  */
22 
23 #ifdef __CYGWIN__
24 #  undef _WIN32
25 #endif
26 
27 #include <errno.h>
28 
29 #include <optional>
30 #include <string>
31 #include <string_view>
32 #include <vector>
33 
34 // Include this before open/close/unlink are defined as macros below.
35 #include <android-base/errors.h>
36 #include <android-base/macros.h>
37 #include <android-base/off64_t.h>
38 #include <android-base/unique_fd.h>
39 #include <android-base/utf8.h>
40 
41 #include "adb_unique_fd.h"
42 #include "sysdeps/errno.h"
43 #include "sysdeps/network.h"
44 #include "sysdeps/stat.h"
45 
46 #if defined(__APPLE__)
mempcpy(void * dst,const void * src,size_t n)47 static inline void* mempcpy(void* dst, const void* src, size_t n) {
48     return static_cast<char*>(memcpy(dst, src, n)) + n;
49 }
50 #endif
51 
52 #ifdef _WIN32
53 
54 // Clang-only nullability specifiers
55 #define _Nonnull
56 #define _Nullable
57 
58 #include <ctype.h>
59 #include <direct.h>
60 #include <dirent.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <io.h>
64 #include <mswsock.h>
65 #include <process.h>
66 #include <stdint.h>
67 #include <sys/stat.h>
68 #include <utime.h>
69 #include <windows.h>
70 #include <winsock2.h>
71 #include <ws2tcpip.h>
72 
73 #include <memory>   // unique_ptr
74 #include <string>
75 
76 #define OS_PATH_SEPARATORS "\\/"
77 #define OS_PATH_SEPARATOR '\\'
78 #define OS_PATH_SEPARATOR_STR "\\"
79 #define ENV_PATH_SEPARATOR_STR ";"
80 
adb_is_separator(char c)81 static inline bool adb_is_separator(char c) {
82     return c == '\\' || c == '/';
83 }
84 
85 extern int adb_thread_setname(const std::string& name);
86 
close_on_exec(borrowed_fd fd)87 static inline void close_on_exec(borrowed_fd fd) {
88     /* nothing really */
89 }
90 
91 extern int adb_unlink(const char* path);
92 #undef unlink
93 #define unlink ___xxx_unlink
94 
95 extern int adb_mkdir(const std::string& path, int mode);
96 #undef mkdir
97 #define mkdir ___xxx_mkdir
98 
99 extern int adb_rename(const char* oldpath, const char* newpath);
100 
101 // See the comments for the !defined(_WIN32) versions of adb_*().
102 extern int adb_open(const char* path, int options);
103 extern int adb_creat(const char* path, int mode);
104 extern int adb_read(borrowed_fd fd, void* buf, int len);
105 extern int adb_pread(borrowed_fd fd, void* buf, int len, off64_t offset);
106 extern int adb_write(borrowed_fd fd, const void* buf, int len);
107 extern int adb_pwrite(borrowed_fd fd, const void* buf, int len, off64_t offset);
108 extern int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where);
109 extern int adb_shutdown(borrowed_fd fd, int direction = SHUT_RDWR);
110 extern int adb_close(int fd);
111 extern int adb_register_socket(SOCKET s);
112 extern HANDLE adb_get_os_handle(borrowed_fd fd);
113 
114 extern int adb_gethostname(char* name, size_t len);
115 extern int adb_getlogin_r(char* buf, size_t bufsize);
116 
117 // See the comments for the !defined(_WIN32) version of unix_close().
unix_close(int fd)118 static inline int unix_close(int fd) {
119     return close(fd);
120 }
121 #undef close
122 #define close ____xxx_close
123 
124 // Like unix_read(), but may return EINTR.
125 extern int unix_read_interruptible(borrowed_fd fd, void* buf, size_t len);
126 
127 // See the comments for the !defined(_WIN32) version of unix_read().
unix_read(borrowed_fd fd,void * buf,size_t len)128 static inline int unix_read(borrowed_fd fd, void* buf, size_t len) {
129     return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
130 }
131 
132 #undef   read
133 #define  read  ___xxx_read
134 
135 #undef pread
136 #define pread ___xxx_pread
137 
138 // See the comments for the !defined(_WIN32) version of unix_write().
unix_write(borrowed_fd fd,const void * buf,size_t len)139 static inline int unix_write(borrowed_fd fd, const void* buf, size_t len) {
140     return write(fd.get(), buf, len);
141 }
142 #undef   write
143 #define  write  ___xxx_write
144 
145 #undef pwrite
146 #define pwrite ___xxx_pwrite
147 
148 // See the comments for the !defined(_WIN32) version of unix_lseek().
unix_lseek(borrowed_fd fd,int pos,int where)149 static inline int unix_lseek(borrowed_fd fd, int pos, int where) {
150     return lseek(fd.get(), pos, where);
151 }
152 #undef lseek
153 #define lseek ___xxx_lseek
154 
155 // See the comments for the !defined(_WIN32) version of adb_open_mode().
adb_open_mode(const char * path,int options,int mode)156 static inline int adb_open_mode(const char* path, int options, int mode) {
157     return adb_open(path, options);
158 }
159 
160 // See the comments for the !defined(_WIN32) version of unix_open().
161 extern int unix_open(std::string_view path, int options, ...);
162 #define  open    ___xxx_unix_open
163 
164 // Checks if |fd| corresponds to a console.
165 // Standard Windows isatty() returns 1 for both console FDs and character
166 // devices like NUL. unix_isatty() performs some extra checking to only match
167 // console FDs.
168 // |fd| must be a real file descriptor, meaning STDxx_FILENO or unix_open() FDs
169 // will work but adb_open() FDs will not. Additionally the OS handle associated
170 // with |fd| must have GENERIC_READ access (which console FDs have by default).
171 // Returns 1 if |fd| is a console FD, 0 otherwise. The value of errno after
172 // calling this function is unreliable and should not be used.
173 int unix_isatty(borrowed_fd fd);
174 #define  isatty  ___xxx_isatty
175 
176 int network_inaddr_any_server(int port, int type, std::string* error);
177 
network_local_client(const char * name,int namespace_id,int type,std::string * error)178 inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
179     abort();
180 }
181 
network_local_server(const char * name,int namespace_id,int type,std::string * error)182 inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
183     abort();
184 }
185 
186 int network_connect(const std::string& host, int port, int type, int timeout,
187                     std::string* error);
188 
189 std::optional<ssize_t> network_peek(borrowed_fd fd);
190 
191 extern int adb_socket_accept(borrowed_fd serverfd, struct sockaddr* addr, socklen_t* addrlen);
192 
193 #undef   accept
194 #define  accept  ___xxx_accept
195 
196 int adb_getsockname(borrowed_fd fd, struct sockaddr* sockaddr, socklen_t* addrlen);
197 
198 // Returns the local port number of a bound socket, or -1 on failure.
199 int adb_socket_get_local_port(borrowed_fd fd);
200 
201 extern int adb_setsockopt(borrowed_fd fd, int level, int optname, const void* optval,
202                           socklen_t optlen);
203 
204 #undef   setsockopt
205 #define  setsockopt  ___xxx_setsockopt
206 
207 // Wrapper around socket() call. On Windows, ADB has an indirection layer for file descriptors.
208 extern int adb_socket(int domain, int type, int protocol);
209 
210 // Wrapper around bind() call, as Windows has indirection layer.
211 extern int adb_bind(borrowed_fd fd, const sockaddr* addr, int namelen);
212 
213 extern int adb_socketpair(int sv[2]);
214 
215 // Posix compatibility layer for msghdr
216 struct adb_msghdr {
217     void* msg_name;
218     socklen_t msg_namelen;
219     struct adb_iovec* msg_iov;
220     size_t msg_iovlen;
221     void* msg_control;
222     size_t msg_controllen;
223     int msg_flags;
224 };
225 
226 ssize_t adb_sendmsg(borrowed_fd fd, const adb_msghdr* msg, int flags);
227 ssize_t adb_recvmsg(borrowed_fd fd, adb_msghdr* msg, int flags);
228 
229 using adb_cmsghdr = WSACMSGHDR;
230 
231 extern adb_cmsghdr* adb_CMSG_FIRSTHDR(adb_msghdr* msgh);
232 extern adb_cmsghdr* adb_CMSG_NXTHDR(adb_msghdr* msgh, adb_cmsghdr* cmsg);
233 extern unsigned char* adb_CMSG_DATA(adb_cmsghdr* cmsg);
234 
235 struct adb_pollfd {
236     int fd;
237     short events;
238     short revents;
239 };
240 extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout);
241 #define poll ___xxx_poll
242 
adb_is_absolute_host_path(const char * path)243 static inline int adb_is_absolute_host_path(const char* path) {
244     return isalpha(path[0]) && path[1] == ':' && path[2] == '\\';
245 }
246 
247 // UTF-8 versions of POSIX APIs.
248 extern DIR* adb_opendir(const char* dirname);
249 extern struct dirent* adb_readdir(DIR* dir);
250 extern int adb_closedir(DIR* dir);
251 
252 extern int adb_utime(const char *, struct utimbuf *);
253 extern int adb_chmod(const char *, int);
254 
255 extern int adb_vfprintf(FILE* stream, const char* format, va_list ap)
256         __attribute__((__format__(__printf__, 2, 0)));
257 extern int adb_vprintf(const char* format, va_list ap) __attribute__((__format__(__printf__, 1, 0)));
258 extern int adb_fprintf(FILE* stream, const char* format, ...)
259         __attribute__((__format__(__printf__, 2, 3)));
260 extern int adb_printf(const char* format, ...) __attribute__((__format__(__printf__, 1, 2)));
261 
262 extern int adb_fputs(const char* buf, FILE* stream);
263 extern int adb_fputc(int ch, FILE* stream);
264 extern int adb_putchar(int ch);
265 extern int adb_puts(const char* buf);
266 extern size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream);
267 
268 extern FILE* adb_fopen(const char* f, const char* m);
269 
270 extern char* adb_getenv(const char* name);
271 
272 extern char* adb_getcwd(char* buf, int size);
273 
274 // Remap calls to POSIX APIs to our UTF-8 versions.
275 #define opendir adb_opendir
276 #define readdir adb_readdir
277 #define closedir adb_closedir
278 #define rewinddir rewinddir_utf8_not_yet_implemented
279 #define telldir telldir_utf8_not_yet_implemented
280 // Some compiler's C++ headers have members named seekdir, so we can't do the
281 // macro technique and instead cause a link error if seekdir is called.
seekdir(DIR *,long)282 inline void seekdir(DIR*, long) {
283     extern int seekdir_utf8_not_yet_implemented;
284     seekdir_utf8_not_yet_implemented = 1;
285 }
286 
287 #define utime adb_utime
288 #define chmod adb_chmod
289 
290 #define vfprintf adb_vfprintf
291 #define vprintf adb_vprintf
292 #define fprintf adb_fprintf
293 #define printf adb_printf
294 #define fputs adb_fputs
295 #define fputc adb_fputc
296 // putc may be a macro, so if so, undefine it, so that we can redefine it.
297 #undef putc
298 #define putc(c, s) adb_fputc(c, s)
299 #define putchar adb_putchar
300 #define puts adb_puts
301 #define fwrite adb_fwrite
302 
303 #define fopen adb_fopen
304 #define freopen freopen_utf8_not_yet_implemented
305 
306 #define getenv adb_getenv
307 #define putenv putenv_utf8_not_yet_implemented
308 #define setenv setenv_utf8_not_yet_implemented
309 #define unsetenv unsetenv_utf8_not_yet_implemented
310 
311 #define getcwd adb_getcwd
312 
313 // A very simple wrapper over a launched child process
314 class Process {
315   public:
h_(h)316     constexpr explicit Process(HANDLE h = nullptr) : h_(h) {}
Process(Process && other)317     constexpr Process(Process&& other) : h_(std::exchange(other.h_, nullptr)) {}
~Process()318     ~Process() { close(); }
319     constexpr explicit operator bool() const { return h_ != nullptr; }
320 
wait()321     void wait() {
322         if (*this) {
323             ::WaitForSingleObject(h_, INFINITE);
324             close();
325         }
326     }
kill()327     void kill() {
328         if (*this) {
329             ::TerminateProcess(h_, -1);
330         }
331     }
332 
333   private:
334     DISALLOW_COPY_AND_ASSIGN(Process);
335 
close()336     void close() {
337         if (*this) {
338             ::CloseHandle(h_);
339             h_ = nullptr;
340         }
341     }
342 
343     HANDLE h_;
344 };
345 
346 Process adb_launch_process(std::string_view executable, std::vector<std::string> args,
347                            std::initializer_list<int> fds_to_inherit = {});
348 
349 // Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
350 // passed to main().
351 class NarrowArgs {
352 public:
353     NarrowArgs(int argc, wchar_t** argv);
354     ~NarrowArgs();
355 
data()356     inline char** data() {
357         return narrow_args;
358     }
359 
360 private:
361     char** narrow_args;
362 };
363 
364 // Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
365 // so they can fit in an int. To convert back, we just need to sign-extend.
366 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
367 // Note that this does not make a HANDLE value work with APIs like open(), nor
368 // does this make a value from open() passable to APIs taking a HANDLE. This
369 // just lets you take a HANDLE, pass it around as an int, and then use it again
370 // as a HANDLE.
cast_handle_to_int(const HANDLE h)371 inline int cast_handle_to_int(const HANDLE h) {
372     // truncate
373     return static_cast<int>(reinterpret_cast<INT_PTR>(h));
374 }
375 
cast_int_to_handle(const int fd)376 inline HANDLE cast_int_to_handle(const int fd) {
377     // sign-extend
378     return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
379 }
380 
381 // Deleter for unique_handle. Adapted from many sources, including:
382 // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
383 // https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
384 class handle_deleter {
385 public:
386     typedef HANDLE pointer;
387 
388     void operator()(HANDLE h);
389 };
390 
391 // Like std::unique_ptr, but for Windows HANDLE objects that should be
392 // CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
393 // but does not check if the handle != INVALID_HANDLE_VALUE.
394 typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
395 
396 namespace internal {
397 
398 size_t ParseCompleteUTF8(const char* first, const char* last, std::vector<char>* remaining_bytes);
399 
400 }
401 
402 #else /* !_WIN32 a.k.a. Unix */
403 
404 #include <fcntl.h>
405 #include <netdb.h>
406 #include <netinet/in.h>
407 #include <netinet/tcp.h>
408 #include <poll.h>
409 #include <pthread.h>
410 #include <signal.h>
411 #include <stdarg.h>
412 #include <stdint.h>
413 #include <string.h>
414 #include <sys/stat.h>
415 #include <sys/wait.h>
416 #include <unistd.h>
417 
418 #include <string>
419 
420 #include <cutils/sockets.h>
421 
422 #define OS_PATH_SEPARATORS "/"
423 #define OS_PATH_SEPARATOR '/'
424 #define OS_PATH_SEPARATOR_STR "/"
425 #define ENV_PATH_SEPARATOR_STR ":"
426 
adb_is_separator(char c)427 static inline bool adb_is_separator(char c) {
428     return c == '/';
429 }
430 
get_fd_flags(borrowed_fd fd)431 static inline int get_fd_flags(borrowed_fd fd) {
432     return fcntl(fd.get(), F_GETFD);
433 }
434 
close_on_exec(borrowed_fd fd)435 static inline void close_on_exec(borrowed_fd fd) {
436     int flags = get_fd_flags(fd);
437     if (flags >= 0 && (flags & FD_CLOEXEC) == 0) {
438         fcntl(fd.get(), F_SETFD, flags | FD_CLOEXEC);
439     }
440 }
441 
442 // Open a file and return a file descriptor that may be used with unix_read(),
443 // unix_write(), unix_close(), but not adb_read(), adb_write(), adb_close().
444 //
445 // On Unix, this is based on open(), so the file descriptor is a real OS file
446 // descriptor, but the Windows implementation (in sysdeps_win32.cpp) returns a
447 // file descriptor that can only be used with C Runtime APIs (which are wrapped
448 // by unix_read(), unix_write(), unix_close()). Also, the C Runtime has
449 // configurable CR/LF translation which defaults to text mode, but is settable
450 // with _setmode().
unix_open(std::string_view path,int options,...)451 static inline int unix_open(std::string_view path, int options, ...) {
452     std::string zero_terminated(path.begin(), path.end());
453     if ((options & O_CREAT) == 0) {
454         return TEMP_FAILURE_RETRY(open(zero_terminated.c_str(), options));
455     } else {
456         int mode;
457         va_list args;
458         va_start(args, options);
459         mode = va_arg(args, int);
460         va_end(args);
461         return TEMP_FAILURE_RETRY(open(zero_terminated.c_str(), options, mode));
462     }
463 }
464 
465 // Similar to the two-argument adb_open(), but takes a mode parameter for file
466 // creation. See adb_open() for more info.
adb_open_mode(const char * pathname,int options,int mode)467 static inline int adb_open_mode(const char* pathname, int options, int mode) {
468     return TEMP_FAILURE_RETRY(open(pathname, options, mode));
469 }
470 
471 // Open a file and return a file descriptor that may be used with adb_read(),
472 // adb_write(), adb_close(), but not unix_read(), unix_write(), unix_close().
473 //
474 // On Unix, this is based on open(), but the Windows implementation (in
475 // sysdeps_win32.cpp) uses Windows native file I/O and bypasses the C Runtime
476 // and its CR/LF translation. The returned file descriptor should be used with
477 // adb_read(), adb_write(), adb_close(), etc.
adb_open(const char * pathname,int options)478 static inline int adb_open(const char* pathname, int options) {
479     int fd = TEMP_FAILURE_RETRY(open(pathname, options));
480     if (fd < 0) return -1;
481     close_on_exec(fd);
482     return fd;
483 }
484 #undef open
485 #define open ___xxx_open
486 
487 static inline int adb_shutdown(borrowed_fd fd, int direction = SHUT_RDWR) {
488     return shutdown(fd.get(), direction);
489 }
490 
491 #undef shutdown
492 #define shutdown ____xxx_shutdown
493 
494 // Closes a file descriptor that came from adb_open() or adb_open_mode(), but
495 // not designed to take a file descriptor from unix_open(). See the comments
496 // for adb_open() for more info.
adb_close(int fd)497 inline int adb_close(int fd) {
498     return close(fd);
499 }
500 #undef close
501 #define close ____xxx_close
502 
503 // On Windows, ADB has an indirection layer for file descriptors. If we get a
504 // Win32 SOCKET object from an external library, we have to map it in to that
505 // indirection layer, which this does.
adb_register_socket(int s)506 inline int adb_register_socket(int s) {
507     return s;
508 }
509 
adb_gethostname(char * name,size_t len)510 static inline int adb_gethostname(char* name, size_t len) {
511     return gethostname(name, len);
512 }
513 
adb_getlogin_r(char * buf,size_t bufsize)514 static inline int adb_getlogin_r(char* buf, size_t bufsize) {
515     return getlogin_r(buf, bufsize);
516 }
517 
adb_read(borrowed_fd fd,void * buf,size_t len)518 static inline int adb_read(borrowed_fd fd, void* buf, size_t len) {
519     return TEMP_FAILURE_RETRY(read(fd.get(), buf, len));
520 }
521 
adb_pread(borrowed_fd fd,void * buf,size_t len,off64_t offset)522 static inline int adb_pread(borrowed_fd fd, void* buf, size_t len, off64_t offset) {
523 #if defined(__APPLE__)
524     return TEMP_FAILURE_RETRY(pread(fd.get(), buf, len, offset));
525 #else
526     return TEMP_FAILURE_RETRY(pread64(fd.get(), buf, len, offset));
527 #endif
528 }
529 
530 // Like unix_read(), but does not handle EINTR.
unix_read_interruptible(borrowed_fd fd,void * buf,size_t len)531 static inline int unix_read_interruptible(borrowed_fd fd, void* buf, size_t len) {
532     return read(fd.get(), buf, len);
533 }
534 
535 #undef read
536 #define read ___xxx_read
537 #undef pread
538 #define pread ___xxx_pread
539 
adb_write(borrowed_fd fd,const void * buf,size_t len)540 static inline int adb_write(borrowed_fd fd, const void* buf, size_t len) {
541     return TEMP_FAILURE_RETRY(write(fd.get(), buf, len));
542 }
543 
adb_pwrite(int fd,const void * buf,size_t len,off64_t offset)544 static inline int adb_pwrite(int fd, const void* buf, size_t len, off64_t offset) {
545 #if defined(__APPLE__)
546     return TEMP_FAILURE_RETRY(pwrite(fd, buf, len, offset));
547 #else
548     return TEMP_FAILURE_RETRY(pwrite64(fd, buf, len, offset));
549 #endif
550 }
551 
552 #undef   write
553 #define  write  ___xxx_write
554 #undef pwrite
555 #define pwrite ___xxx_pwrite
556 
adb_lseek(borrowed_fd fd,int64_t pos,int where)557 static inline int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where) {
558 #if defined(__APPLE__)
559     return lseek(fd.get(), pos, where);
560 #else
561     return lseek64(fd.get(), pos, where);
562 #endif
563 }
564 #undef lseek
565 #define lseek ___xxx_lseek
566 
adb_unlink(const char * path)567 static inline int adb_unlink(const char* path) {
568     return unlink(path);
569 }
570 #undef unlink
571 #define unlink ___xxx_unlink
572 
adb_creat(const char * path,int mode)573 static inline int adb_creat(const char* path, int mode) {
574     int fd = TEMP_FAILURE_RETRY(creat(path, mode));
575 
576     if (fd < 0) return -1;
577 
578     close_on_exec(fd);
579     return fd;
580 }
581 #undef creat
582 #define creat ___xxx_creat
583 
unix_isatty(borrowed_fd fd)584 static inline int unix_isatty(borrowed_fd fd) {
585     return isatty(fd.get());
586 }
587 #define isatty ___xxx_isatty
588 
589 // Helper for network_* functions.
_fd_set_error_str(int fd,std::string * error)590 inline int _fd_set_error_str(int fd, std::string* error) {
591     if (fd == -1) {
592         *error = strerror(errno);
593     }
594     return fd;
595 }
596 
network_inaddr_any_server(int port,int type,std::string * error)597 inline int network_inaddr_any_server(int port, int type, std::string* error) {
598     return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
599 }
600 
network_local_client(const char * name,int namespace_id,int type,std::string * error)601 inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
602     return _fd_set_error_str(socket_local_client(name, namespace_id, type), error);
603 }
604 
network_local_server(const char * name,int namespace_id,int type,std::string * error)605 inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
606     return _fd_set_error_str(socket_local_server(name, namespace_id, type), error);
607 }
608 
609 int network_connect(const std::string& host, int port, int type, int timeout, std::string* error);
610 
network_peek(borrowed_fd fd)611 inline std::optional<ssize_t> network_peek(borrowed_fd fd) {
612     ssize_t ret = recv(fd.get(), nullptr, 0, MSG_PEEK | MSG_TRUNC);
613     return ret == -1 ? std::nullopt : std::make_optional(ret);
614 }
615 
adb_socket_accept(borrowed_fd serverfd,struct sockaddr * addr,socklen_t * addrlen)616 static inline int adb_socket_accept(borrowed_fd serverfd, struct sockaddr* addr,
617                                     socklen_t* addrlen) {
618     int fd;
619 
620     fd = TEMP_FAILURE_RETRY(accept(serverfd.get(), addr, addrlen));
621     if (fd >= 0) close_on_exec(fd);
622 
623     return fd;
624 }
625 
626 #undef accept
627 #define accept ___xxx_accept
628 
adb_getsockname(borrowed_fd fd,struct sockaddr * sockaddr,socklen_t * addrlen)629 inline int adb_getsockname(borrowed_fd fd, struct sockaddr* sockaddr, socklen_t* addrlen) {
630     return getsockname(fd.get(), sockaddr, addrlen);
631 }
632 
adb_socket_get_local_port(borrowed_fd fd)633 inline int adb_socket_get_local_port(borrowed_fd fd) {
634     return socket_get_local_port(fd.get());
635 }
636 
637 // Operate on a file descriptor returned from unix_open() or a well-known file
638 // descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
639 //
640 // On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
641 // adb_write(), adb_close() (which all map to Unix system calls), but the
642 // Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
643 // into the C Runtime and its configurable CR/LF translation (which is settable
644 // via _setmode()).
645 #define unix_read adb_read
646 #define unix_write adb_write
647 #define unix_lseek adb_lseek
648 #define unix_close adb_close
649 
adb_thread_setname(const std::string & name)650 static inline int adb_thread_setname(const std::string& name) {
651 #ifdef __APPLE__
652     return pthread_setname_np(name.c_str());
653 #else
654     // Both bionic and glibc's pthread_setname_np fails rather than truncating long strings.
655     // glibc doesn't have strlcpy, so we have to fake it.
656     char buf[16];  // MAX_TASK_COMM_LEN, but that's not exported by the kernel headers.
657     strncpy(buf, name.c_str(), sizeof(buf) - 1);
658     buf[sizeof(buf) - 1] = '\0';
659     return pthread_setname_np(pthread_self(), buf);
660 #endif
661 }
662 
adb_setsockopt(borrowed_fd fd,int level,int optname,const void * optval,socklen_t optlen)663 static inline int adb_setsockopt(borrowed_fd fd, int level, int optname, const void* optval,
664                                  socklen_t optlen) {
665     return setsockopt(fd.get(), level, optname, optval, optlen);
666 }
667 
668 #undef setsockopt
669 #define setsockopt ___xxx_setsockopt
670 
adb_socket(int domain,int type,int protocol)671 static inline int adb_socket(int domain, int type, int protocol) {
672     return socket(domain, type, protocol);
673 }
674 
adb_bind(borrowed_fd fd,const sockaddr * addr,int namelen)675 static inline int adb_bind(borrowed_fd fd, const sockaddr* addr, int namelen) {
676     return bind(fd.get(), addr, namelen);
677 }
678 
unix_socketpair(int d,int type,int protocol,int sv[2])679 static inline int unix_socketpair(int d, int type, int protocol, int sv[2]) {
680     return socketpair(d, type, protocol, sv);
681 }
682 
adb_socketpair(int sv[2])683 static inline int adb_socketpair(int sv[2]) {
684     int rc;
685 
686     rc = unix_socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
687     if (rc < 0) return -1;
688 
689     close_on_exec(sv[0]);
690     close_on_exec(sv[1]);
691     return 0;
692 }
693 
694 #undef socketpair
695 #define socketpair ___xxx_socketpair
696 
697 typedef struct msghdr adb_msghdr;
adb_sendmsg(borrowed_fd fd,const adb_msghdr * msg,int flags)698 inline ssize_t adb_sendmsg(borrowed_fd fd, const adb_msghdr* msg, int flags) {
699     return sendmsg(fd.get(), msg, flags);
700 }
701 
adb_recvmsg(borrowed_fd fd,adb_msghdr * msg,int flags)702 inline ssize_t adb_recvmsg(borrowed_fd fd, adb_msghdr* msg, int flags) {
703     return recvmsg(fd.get(), msg, flags);
704 }
705 
706 using adb_cmsghdr = cmsghdr;
707 
adb_CMSG_FIRSTHDR(adb_msghdr * msgh)708 inline adb_cmsghdr* adb_CMSG_FIRSTHDR(adb_msghdr* msgh) {
709     return CMSG_FIRSTHDR(msgh);
710 }
711 
adb_CMSG_NXTHDR(adb_msghdr * msgh,adb_cmsghdr * cmsg)712 inline adb_cmsghdr* adb_CMSG_NXTHDR(adb_msghdr* msgh, adb_cmsghdr* cmsg) {
713     return CMSG_NXTHDR(msgh, cmsg);
714 }
715 
adb_CMSG_DATA(adb_cmsghdr * cmsg)716 inline unsigned char* adb_CMSG_DATA(adb_cmsghdr* cmsg) {
717     return CMSG_DATA(cmsg);
718 }
719 
720 typedef struct pollfd adb_pollfd;
adb_poll(adb_pollfd * fds,size_t nfds,int timeout)721 static inline int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
722     return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
723 }
724 
725 #define poll ___xxx_poll
726 
adb_mkdir(const std::string & path,int mode)727 static inline int adb_mkdir(const std::string& path, int mode) {
728     return mkdir(path.c_str(), mode);
729 }
730 
731 #undef mkdir
732 #define mkdir ___xxx_mkdir
733 
adb_rename(const char * oldpath,const char * newpath)734 static inline int adb_rename(const char* oldpath, const char* newpath) {
735     return rename(oldpath, newpath);
736 }
737 
adb_is_absolute_host_path(const char * path)738 static inline int adb_is_absolute_host_path(const char* path) {
739     return path[0] == '/';
740 }
741 
adb_get_os_handle(borrowed_fd fd)742 static inline int adb_get_os_handle(borrowed_fd fd) {
743     return fd.get();
744 }
745 
cast_handle_to_int(int fd)746 static inline int cast_handle_to_int(int fd) {
747     return fd;
748 }
749 
750 // A very simple wrapper over a launched child process
751 class Process {
752   public:
Process(pid_t pid)753     constexpr explicit Process(pid_t pid) : pid_(pid) {}
Process(Process && other)754     constexpr Process(Process&& other) : pid_(std::exchange(other.pid_, -1)) {}
755 
756     constexpr explicit operator bool() const { return pid_ >= 0; }
757 
wait()758     void wait() {
759         if (*this) {
760             int status;
761             ::waitpid(pid_, &status, 0);
762             pid_ = -1;
763         }
764     }
kill()765     void kill() {
766         if (*this) {
767             ::kill(pid_, SIGTERM);
768         }
769     }
770 
771   private:
772     DISALLOW_COPY_AND_ASSIGN(Process);
773 
774     pid_t pid_;
775 };
776 
777 Process adb_launch_process(std::string_view executable, std::vector<std::string> args,
778                            std::initializer_list<int> fds_to_inherit = {});
779 
780 #endif /* !_WIN32 */
781 
disable_tcp_nagle(borrowed_fd fd)782 static inline void disable_tcp_nagle(borrowed_fd fd) {
783     int off = 1;
784     adb_setsockopt(fd.get(), IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
785 }
786 
787 // Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
788 // |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
789 // configured to drop after 10 missed keepalives. Returns true on success.
790 bool set_tcp_keepalive(borrowed_fd fd, int interval_sec);
791 
792 #if defined(_WIN32)
793 // Win32 defines ERROR, which we don't need, but which conflicts with google3 logging.
794 #undef ERROR
795 #endif
796