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