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