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