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/isatty/unlink are defined as macros below.
35 #include <android-base/errors.h>
36 #include <android-base/logging.h>
37 #include <android-base/macros.h>
38 #include <android-base/off64_t.h>
39 #include <android-base/unique_fd.h>
40 #include <android-base/utf8.h>
41 #if __has_include(<print>)
42 #include <print>
43 #endif
44 
45 #include "adb_unique_fd.h"
46 #include "sysdeps/errno.h"
47 #include "sysdeps/network.h"
48 #include "sysdeps/stat.h"
49 
50 #if defined(__APPLE__)
mempcpy(void * dst,const void * src,size_t n)51 static inline void* mempcpy(void* dst, const void* src, size_t n) {
52     return static_cast<char*>(memcpy(dst, src, n)) + n;
53 }
54 #endif
55 
56 std::optional<ssize_t> network_peek(borrowed_fd fd);
57 
58 #ifdef _WIN32
59 
60 #include <ctype.h>
61 #include <direct.h>
62 #include <dirent.h>
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <io.h>
66 #include <mswsock.h>
67 #include <process.h>
68 #include <stdint.h>
69 #include <sys/stat.h>
70 #include <utime.h>
71 #include <windows.h>
72 #include <winsock2.h>
73 #include <ws2tcpip.h>
74 
75 #include <memory>   // unique_ptr
76 #include <string>
77 
78 #define OS_PATH_SEPARATORS "\\/"
79 #define OS_PATH_SEPARATOR '\\'
80 #define OS_PATH_SEPARATOR_STR "\\"
81 #define ENV_PATH_SEPARATOR_STR ";"
82 
adb_is_separator(char c)83 static inline bool adb_is_separator(char c) {
84     return c == '\\' || c == '/';
85 }
86 
87 extern int adb_thread_setname(const std::string& name);
88 
close_on_exec(borrowed_fd fd)89 static inline void close_on_exec(borrowed_fd fd) {
90     /* nothing really */
91 }
92 
93 extern int adb_unlink(const char* path);
94 #undef unlink
95 #define unlink ___xxx_unlink
96 
97 extern int adb_mkdir(const std::string& path, int mode);
98 #undef mkdir
99 #define mkdir ___xxx_mkdir
100 
101 extern int adb_rename(const char* oldpath, const char* newpath);
102 
103 // See the comments for the !defined(_WIN32) versions of adb_*().
104 extern int adb_open(const char* path, int options);
105 extern int adb_creat(const char* path, int mode);
106 extern int adb_read(borrowed_fd fd, void* buf, int len);
107 extern int adb_pread(borrowed_fd fd, void* buf, int len, off64_t offset);
108 extern int adb_write(borrowed_fd fd, const void* buf, int len);
109 extern int adb_pwrite(borrowed_fd fd, const void* buf, int len, off64_t offset);
110 extern int64_t adb_lseek(borrowed_fd fd, int64_t pos, int where);
111 extern int adb_shutdown(borrowed_fd fd, int direction = SHUT_RDWR);
112 extern int adb_close(int fd);
113 extern int adb_register_socket(SOCKET s);
114 extern HANDLE adb_get_os_handle(borrowed_fd fd);
115 
116 extern int adb_gethostname(char* name, size_t len);
117 extern int adb_getlogin_r(char* buf, size_t bufsize);
118 
119 // See the comments for the !defined(_WIN32) version of unix_close().
unix_close(int fd)120 static inline int unix_close(int fd) {
121     return close(fd);
122 }
123 #undef close
124 #define close ____xxx_close
125 
126 // Like unix_read(), but may return EINTR.
127 extern int unix_read_interruptible(borrowed_fd fd, void* buf, size_t len);
128 
129 // See the comments for the !defined(_WIN32) version of unix_read().
unix_read(borrowed_fd fd,void * buf,size_t len)130 static inline int unix_read(borrowed_fd fd, void* buf, size_t len) {
131     return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
132 }
133 
134 #undef   read
135 #define  read  ___xxx_read
136 
137 #undef pread
138 #define pread ___xxx_pread
139 
140 // See the comments for the !defined(_WIN32) version of unix_write().
unix_write(borrowed_fd fd,const void * buf,size_t len)141 static inline int unix_write(borrowed_fd fd, const void* buf, size_t len) {
142     return write(fd.get(), buf, len);
143 }
144 #undef   write
145 #define  write  ___xxx_write
146 
147 #undef pwrite
148 #define pwrite ___xxx_pwrite
149 
150 // See the comments for the !defined(_WIN32) version of unix_lseek().
unix_lseek(borrowed_fd fd,int pos,int where)151 static inline int unix_lseek(borrowed_fd fd, int pos, int where) {
152     return lseek(fd.get(), pos, where);
153 }
154 #undef lseek
155 #define lseek ___xxx_lseek
156 
157 // See the comments for the !defined(_WIN32) version of adb_open_mode().
adb_open_mode(const char * path,int options,int mode)158 static inline int adb_open_mode(const char* path, int options, int mode) {
159     return adb_open(path, options);
160 }
161 
162 // See the comments for the !defined(_WIN32) version of unix_open().
163 extern int unix_open(std::string_view path, int options, ...);
164 #define  open    ___xxx_unix_open
165 
166 // Checks if |fd| corresponds to a console.
167 // Standard Windows isatty() returns 1 for both console FDs and character
168 // devices like NUL. unix_isatty() performs some extra checking to only match
169 // console FDs.
170 // |fd| must be a real file descriptor, meaning STDxx_FILENO or unix_open() FDs
171 // will work but adb_open() FDs will not. Additionally the OS handle associated
172 // with |fd| must have GENERIC_READ access (which console FDs have by default).
173 // Returns 1 if |fd| is a console FD, 0 otherwise. The value of errno after
174 // calling this function is unreliable and should not be used.
175 int unix_isatty(borrowed_fd fd);
176 #define  isatty  ___xxx_isatty
177 
178 int network_inaddr_any_server(int port, int type, std::string* error);
179 
network_local_client(const char * name,int namespace_id,int type,std::string * error)180 inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
181     abort();
182 }
183 
network_local_server(const char * name,int namespace_id,int type,std::string * error)184 inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
185     abort();
186 }
187 
188 int network_connect(const std::string& host, int port, int type, int timeout,
189                     std::string* error);
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 
adb_socket_accept(borrowed_fd serverfd,struct sockaddr * addr,socklen_t * addrlen)611 static inline int adb_socket_accept(borrowed_fd serverfd, struct sockaddr* addr,
612                                     socklen_t* addrlen) {
613     int fd;
614 
615     fd = TEMP_FAILURE_RETRY(accept(serverfd.get(), addr, addrlen));
616     if (fd >= 0) close_on_exec(fd);
617 
618     return fd;
619 }
620 
621 #undef accept
622 #define accept ___xxx_accept
623 
adb_getsockname(borrowed_fd fd,struct sockaddr * sockaddr,socklen_t * addrlen)624 inline int adb_getsockname(borrowed_fd fd, struct sockaddr* sockaddr, socklen_t* addrlen) {
625     return getsockname(fd.get(), sockaddr, addrlen);
626 }
627 
adb_socket_get_local_port(borrowed_fd fd)628 inline int adb_socket_get_local_port(borrowed_fd fd) {
629     return socket_get_local_port(fd.get());
630 }
631 
632 // Operate on a file descriptor returned from unix_open() or a well-known file
633 // descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
634 //
635 // On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
636 // adb_write(), adb_close() (which all map to Unix system calls), but the
637 // Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
638 // into the C Runtime and its configurable CR/LF translation (which is settable
639 // via _setmode()).
640 #define unix_read adb_read
641 #define unix_write adb_write
642 #define unix_lseek adb_lseek
643 #define unix_close adb_close
644 
adb_thread_setname(const std::string & name)645 static inline int adb_thread_setname(const std::string& name) {
646 #ifdef __APPLE__
647     return pthread_setname_np(name.c_str());
648 #else
649     // Both bionic and glibc's pthread_setname_np fails rather than truncating long strings.
650     // glibc doesn't have strlcpy, so we have to fake it.
651     char buf[16];  // MAX_TASK_COMM_LEN, but that's not exported by the kernel headers.
652     strncpy(buf, name.c_str(), sizeof(buf) - 1);
653     buf[sizeof(buf) - 1] = '\0';
654     return pthread_setname_np(pthread_self(), buf);
655 #endif
656 }
657 
adb_setsockopt(borrowed_fd fd,int level,int optname,const void * optval,socklen_t optlen)658 static inline int adb_setsockopt(borrowed_fd fd, int level, int optname, const void* optval,
659                                  socklen_t optlen) {
660     return setsockopt(fd.get(), level, optname, optval, optlen);
661 }
662 
663 #undef setsockopt
664 #define setsockopt ___xxx_setsockopt
665 
adb_socket(int domain,int type,int protocol)666 static inline int adb_socket(int domain, int type, int protocol) {
667     return socket(domain, type, protocol);
668 }
669 
adb_bind(borrowed_fd fd,const sockaddr * addr,int namelen)670 static inline int adb_bind(borrowed_fd fd, const sockaddr* addr, int namelen) {
671     return bind(fd.get(), addr, namelen);
672 }
673 
unix_socketpair(int d,int type,int protocol,int sv[2])674 static inline int unix_socketpair(int d, int type, int protocol, int sv[2]) {
675     return socketpair(d, type, protocol, sv);
676 }
677 
adb_socketpair(int sv[2])678 static inline int adb_socketpair(int sv[2]) {
679     int rc;
680 
681     rc = unix_socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
682     if (rc < 0) return -1;
683 
684     close_on_exec(sv[0]);
685     close_on_exec(sv[1]);
686     return 0;
687 }
688 
689 #undef socketpair
690 #define socketpair ___xxx_socketpair
691 
692 typedef struct msghdr adb_msghdr;
adb_sendmsg(borrowed_fd fd,const adb_msghdr * msg,int flags)693 inline ssize_t adb_sendmsg(borrowed_fd fd, const adb_msghdr* msg, int flags) {
694     return sendmsg(fd.get(), msg, flags);
695 }
696 
adb_recvmsg(borrowed_fd fd,adb_msghdr * msg,int flags)697 inline ssize_t adb_recvmsg(borrowed_fd fd, adb_msghdr* msg, int flags) {
698     ssize_t ret = recvmsg(fd.get(), msg, flags);
699     if (ret == -1) {
700         PLOG(ERROR) << "adb_recmsg error";
701     }
702     return ret;
703 }
704 
705 using adb_cmsghdr = cmsghdr;
706 
adb_CMSG_FIRSTHDR(adb_msghdr * msgh)707 inline adb_cmsghdr* adb_CMSG_FIRSTHDR(adb_msghdr* msgh) {
708     return CMSG_FIRSTHDR(msgh);
709 }
710 
adb_CMSG_NXTHDR(adb_msghdr * msgh,adb_cmsghdr * cmsg)711 inline adb_cmsghdr* adb_CMSG_NXTHDR(adb_msghdr* msgh, adb_cmsghdr* cmsg) {
712     return CMSG_NXTHDR(msgh, cmsg);
713 }
714 
adb_CMSG_DATA(adb_cmsghdr * cmsg)715 inline unsigned char* adb_CMSG_DATA(adb_cmsghdr* cmsg) {
716     return CMSG_DATA(cmsg);
717 }
718 
719 typedef struct pollfd adb_pollfd;
adb_poll(adb_pollfd * fds,size_t nfds,int timeout)720 static inline int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
721     return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
722 }
723 
724 #define poll ___xxx_poll
725 
adb_mkdir(const std::string & path,int mode)726 static inline int adb_mkdir(const std::string& path, int mode) {
727     return mkdir(path.c_str(), mode);
728 }
729 
730 #undef mkdir
731 #define mkdir ___xxx_mkdir
732 
adb_rename(const char * oldpath,const char * newpath)733 static inline int adb_rename(const char* oldpath, const char* newpath) {
734     return rename(oldpath, newpath);
735 }
736 
adb_is_absolute_host_path(const char * path)737 static inline int adb_is_absolute_host_path(const char* path) {
738     return path[0] == '/';
739 }
740 
adb_get_os_handle(borrowed_fd fd)741 static inline int adb_get_os_handle(borrowed_fd fd) {
742     return fd.get();
743 }
744 
cast_handle_to_int(int fd)745 static inline int cast_handle_to_int(int fd) {
746     return fd;
747 }
748 
749 // A very simple wrapper over a launched child process
750 class Process {
751   public:
Process(pid_t pid)752     constexpr explicit Process(pid_t pid) : pid_(pid) {}
Process(Process && other)753     constexpr Process(Process&& other) : pid_(std::exchange(other.pid_, -1)) {}
754 
755     constexpr explicit operator bool() const { return pid_ >= 0; }
756 
wait()757     void wait() {
758         if (*this) {
759             int status;
760             ::waitpid(pid_, &status, 0);
761             pid_ = -1;
762         }
763     }
kill()764     void kill() {
765         if (*this) {
766             ::kill(pid_, SIGTERM);
767         }
768     }
769 
770   private:
771     DISALLOW_COPY_AND_ASSIGN(Process);
772 
773     pid_t pid_;
774 };
775 
776 Process adb_launch_process(std::string_view executable, std::vector<std::string> args,
777                            std::initializer_list<int> fds_to_inherit = {});
778 
779 #endif /* !_WIN32 */
780 
disable_tcp_nagle(borrowed_fd fd)781 static inline void disable_tcp_nagle(borrowed_fd fd) {
782     int off = 1;
783     adb_setsockopt(fd.get(), IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
784 }
785 
786 // Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
787 // |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
788 // configured to drop after 10 missed keepalives. Returns true on success.
789 bool set_tcp_keepalive(borrowed_fd fd, int interval_sec);
790 
791 // Returns a human-readable OS version string.
792 extern std::string GetOSVersion();
793 
794 #if defined(_WIN32)
795 // Win32 defines ERROR, which we don't need, but which conflicts with google3 logging.
796 #undef ERROR
797 #endif
798