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