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