sysdeps.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. /* this file contains system-dependent definitions used by ADB
  17. * they're related to threads, sockets and file descriptors
  18. */
  19. #ifndef _ADB_SYSDEPS_H
  20. #define _ADB_SYSDEPS_H
  21. #ifdef __CYGWIN__
  22. # undef _WIN32
  23. #endif
  24. #include <errno.h>
  25. #include <string>
  26. #include <string_view>
  27. #include <vector>
  28. // Include this before open/close/unlink are defined as macros below.
  29. #include <android-base/errors.h>
  30. #include <android-base/macros.h>
  31. #include <android-base/unique_fd.h>
  32. #include <android-base/utf8.h>
  33. #include "sysdeps/errno.h"
  34. #include "sysdeps/network.h"
  35. #include "sysdeps/stat.h"
  36. #ifdef _WIN32
  37. // Clang-only nullability specifiers
  38. #define _Nonnull
  39. #define _Nullable
  40. #include <ctype.h>
  41. #include <direct.h>
  42. #include <dirent.h>
  43. #include <errno.h>
  44. #include <fcntl.h>
  45. #include <io.h>
  46. #include <process.h>
  47. #include <stdint.h>
  48. #include <sys/stat.h>
  49. #include <utime.h>
  50. #include <windows.h>
  51. #include <winsock2.h>
  52. #include <ws2tcpip.h>
  53. #include <memory> // unique_ptr
  54. #include <string>
  55. #include "fdevent.h"
  56. #define OS_PATH_SEPARATORS "\\/"
  57. #define OS_PATH_SEPARATOR '\\'
  58. #define OS_PATH_SEPARATOR_STR "\\"
  59. #define ENV_PATH_SEPARATOR_STR ";"
  60. static __inline__ bool adb_is_separator(char c) {
  61. return c == '\\' || c == '/';
  62. }
  63. extern int adb_thread_setname(const std::string& name);
  64. static __inline__ void close_on_exec(int fd)
  65. {
  66. /* nothing really */
  67. }
  68. extern int adb_unlink(const char* path);
  69. #undef unlink
  70. #define unlink ___xxx_unlink
  71. extern int adb_mkdir(const std::string& path, int mode);
  72. #undef mkdir
  73. #define mkdir ___xxx_mkdir
  74. // See the comments for the !defined(_WIN32) versions of adb_*().
  75. extern int adb_open(const char* path, int options);
  76. extern int adb_creat(const char* path, int mode);
  77. extern int adb_read(int fd, void* buf, int len);
  78. extern int adb_write(int fd, const void* buf, int len);
  79. extern int64_t adb_lseek(int fd, int64_t pos, int where);
  80. extern int adb_shutdown(int fd, int direction = SHUT_RDWR);
  81. extern int adb_close(int fd);
  82. extern int adb_register_socket(SOCKET s);
  83. // See the comments for the !defined(_WIN32) version of unix_close().
  84. static __inline__ int unix_close(int fd)
  85. {
  86. return close(fd);
  87. }
  88. #undef close
  89. #define close ____xxx_close
  90. // Like unix_read(), but may return EINTR.
  91. extern int unix_read_interruptible(int fd, void* buf, size_t len);
  92. // See the comments for the !defined(_WIN32) version of unix_read().
  93. static __inline__ int unix_read(int fd, void* buf, size_t len) {
  94. return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
  95. }
  96. #undef read
  97. #define read ___xxx_read
  98. // See the comments for the !defined(_WIN32) version of unix_write().
  99. static __inline__ int unix_write(int fd, const void* buf, size_t len)
  100. {
  101. return write(fd, buf, len);
  102. }
  103. #undef write
  104. #define write ___xxx_write
  105. // See the comments for the !defined(_WIN32) version of unix_lseek().
  106. static __inline__ int unix_lseek(int fd, int pos, int where) {
  107. return lseek(fd, pos, where);
  108. }
  109. #undef lseek
  110. #define lseek ___xxx_lseek
  111. // See the comments for the !defined(_WIN32) version of adb_open_mode().
  112. static __inline__ int adb_open_mode(const char* path, int options, int mode)
  113. {
  114. return adb_open(path, options);
  115. }
  116. // See the comments for the !defined(_WIN32) version of unix_open().
  117. extern int unix_open(std::string_view path, int options, ...);
  118. #define open ___xxx_unix_open
  119. // Checks if |fd| corresponds to a console.
  120. // Standard Windows isatty() returns 1 for both console FDs and character
  121. // devices like NUL. unix_isatty() performs some extra checking to only match
  122. // console FDs.
  123. // |fd| must be a real file descriptor, meaning STDxx_FILENO or unix_open() FDs
  124. // will work but adb_open() FDs will not. Additionally the OS handle associated
  125. // with |fd| must have GENERIC_READ access (which console FDs have by default).
  126. // Returns 1 if |fd| is a console FD, 0 otherwise. The value of errno after
  127. // calling this function is unreliable and should not be used.
  128. int unix_isatty(int fd);
  129. #define isatty ___xxx_isatty
  130. int network_inaddr_any_server(int port, int type, std::string* error);
  131. inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
  132. abort();
  133. }
  134. inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
  135. abort();
  136. }
  137. int network_connect(const std::string& host, int port, int type, int timeout,
  138. std::string* error);
  139. extern int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen);
  140. #undef accept
  141. #define accept ___xxx_accept
  142. // Returns the local port number of a bound socket, or -1 on failure.
  143. int adb_socket_get_local_port(int fd);
  144. extern int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen);
  145. #undef setsockopt
  146. #define setsockopt ___xxx_setsockopt
  147. extern int adb_socketpair( int sv[2] );
  148. struct adb_pollfd {
  149. int fd;
  150. short events;
  151. short revents;
  152. };
  153. extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout);
  154. #define poll ___xxx_poll
  155. static __inline__ int adb_is_absolute_host_path(const char* path) {
  156. return isalpha(path[0]) && path[1] == ':' && path[2] == '\\';
  157. }
  158. // UTF-8 versions of POSIX APIs.
  159. extern DIR* adb_opendir(const char* dirname);
  160. extern struct dirent* adb_readdir(DIR* dir);
  161. extern int adb_closedir(DIR* dir);
  162. extern int adb_utime(const char *, struct utimbuf *);
  163. extern int adb_chmod(const char *, int);
  164. extern int adb_vfprintf(FILE* stream, const char* format, va_list ap)
  165. __attribute__((__format__(__printf__, 2, 0)));
  166. extern int adb_vprintf(const char* format, va_list ap) __attribute__((__format__(__printf__, 1, 0)));
  167. extern int adb_fprintf(FILE* stream, const char* format, ...)
  168. __attribute__((__format__(__printf__, 2, 3)));
  169. extern int adb_printf(const char* format, ...) __attribute__((__format__(__printf__, 1, 2)));
  170. extern int adb_fputs(const char* buf, FILE* stream);
  171. extern int adb_fputc(int ch, FILE* stream);
  172. extern int adb_putchar(int ch);
  173. extern int adb_puts(const char* buf);
  174. extern size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb,
  175. FILE* stream);
  176. extern FILE* adb_fopen(const char* f, const char* m);
  177. extern char* adb_getenv(const char* name);
  178. extern char* adb_getcwd(char* buf, int size);
  179. // Remap calls to POSIX APIs to our UTF-8 versions.
  180. #define opendir adb_opendir
  181. #define readdir adb_readdir
  182. #define closedir adb_closedir
  183. #define rewinddir rewinddir_utf8_not_yet_implemented
  184. #define telldir telldir_utf8_not_yet_implemented
  185. // Some compiler's C++ headers have members named seekdir, so we can't do the
  186. // macro technique and instead cause a link error if seekdir is called.
  187. inline void seekdir(DIR*, long) {
  188. extern int seekdir_utf8_not_yet_implemented;
  189. seekdir_utf8_not_yet_implemented = 1;
  190. }
  191. #define utime adb_utime
  192. #define chmod adb_chmod
  193. #define vfprintf adb_vfprintf
  194. #define vprintf adb_vprintf
  195. #define fprintf adb_fprintf
  196. #define printf adb_printf
  197. #define fputs adb_fputs
  198. #define fputc adb_fputc
  199. // putc may be a macro, so if so, undefine it, so that we can redefine it.
  200. #undef putc
  201. #define putc(c, s) adb_fputc(c, s)
  202. #define putchar adb_putchar
  203. #define puts adb_puts
  204. #define fwrite adb_fwrite
  205. #define fopen adb_fopen
  206. #define freopen freopen_utf8_not_yet_implemented
  207. #define getenv adb_getenv
  208. #define putenv putenv_utf8_not_yet_implemented
  209. #define setenv setenv_utf8_not_yet_implemented
  210. #define unsetenv unsetenv_utf8_not_yet_implemented
  211. #define getcwd adb_getcwd
  212. // Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
  213. // passed to main().
  214. class NarrowArgs {
  215. public:
  216. NarrowArgs(int argc, wchar_t** argv);
  217. ~NarrowArgs();
  218. inline char** data() {
  219. return narrow_args;
  220. }
  221. private:
  222. char** narrow_args;
  223. };
  224. // Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
  225. // so they can fit in an int. To convert back, we just need to sign-extend.
  226. // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
  227. // Note that this does not make a HANDLE value work with APIs like open(), nor
  228. // does this make a value from open() passable to APIs taking a HANDLE. This
  229. // just lets you take a HANDLE, pass it around as an int, and then use it again
  230. // as a HANDLE.
  231. inline int cast_handle_to_int(const HANDLE h) {
  232. // truncate
  233. return static_cast<int>(reinterpret_cast<INT_PTR>(h));
  234. }
  235. inline HANDLE cast_int_to_handle(const int fd) {
  236. // sign-extend
  237. return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
  238. }
  239. // Deleter for unique_handle. Adapted from many sources, including:
  240. // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
  241. // https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
  242. class handle_deleter {
  243. public:
  244. typedef HANDLE pointer;
  245. void operator()(HANDLE h);
  246. };
  247. // Like std::unique_ptr, but for Windows HANDLE objects that should be
  248. // CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
  249. // but does not check if the handle != INVALID_HANDLE_VALUE.
  250. typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
  251. namespace internal {
  252. size_t ParseCompleteUTF8(const char* first, const char* last, std::vector<char>* remaining_bytes);
  253. }
  254. #else /* !_WIN32 a.k.a. Unix */
  255. #include <fcntl.h>
  256. #include <netdb.h>
  257. #include <netinet/in.h>
  258. #include <netinet/tcp.h>
  259. #include <poll.h>
  260. #include <pthread.h>
  261. #include <signal.h>
  262. #include <stdarg.h>
  263. #include <stdint.h>
  264. #include <string.h>
  265. #include <sys/stat.h>
  266. #include <sys/wait.h>
  267. #include <unistd.h>
  268. #include <string>
  269. #include <cutils/sockets.h>
  270. #define OS_PATH_SEPARATORS "/"
  271. #define OS_PATH_SEPARATOR '/'
  272. #define OS_PATH_SEPARATOR_STR "/"
  273. #define ENV_PATH_SEPARATOR_STR ":"
  274. static __inline__ bool adb_is_separator(char c) {
  275. return c == '/';
  276. }
  277. static __inline__ void close_on_exec(int fd)
  278. {
  279. fcntl( fd, F_SETFD, FD_CLOEXEC );
  280. }
  281. // Open a file and return a file descriptor that may be used with unix_read(),
  282. // unix_write(), unix_close(), but not adb_read(), adb_write(), adb_close().
  283. //
  284. // On Unix, this is based on open(), so the file descriptor is a real OS file
  285. // descriptor, but the Windows implementation (in sysdeps_win32.cpp) returns a
  286. // file descriptor that can only be used with C Runtime APIs (which are wrapped
  287. // by unix_read(), unix_write(), unix_close()). Also, the C Runtime has
  288. // configurable CR/LF translation which defaults to text mode, but is settable
  289. // with _setmode().
  290. static __inline__ int unix_open(std::string_view path, int options, ...) {
  291. std::string zero_terminated(path.begin(), path.end());
  292. if ((options & O_CREAT) == 0) {
  293. return TEMP_FAILURE_RETRY(open(zero_terminated.c_str(), options));
  294. } else {
  295. int mode;
  296. va_list args;
  297. va_start(args, options);
  298. mode = va_arg(args, int);
  299. va_end(args);
  300. return TEMP_FAILURE_RETRY(open(zero_terminated.c_str(), options, mode));
  301. }
  302. }
  303. // Similar to the two-argument adb_open(), but takes a mode parameter for file
  304. // creation. See adb_open() for more info.
  305. static __inline__ int adb_open_mode( const char* pathname, int options, int mode )
  306. {
  307. return TEMP_FAILURE_RETRY( open( pathname, options, mode ) );
  308. }
  309. // Open a file and return a file descriptor that may be used with adb_read(),
  310. // adb_write(), adb_close(), but not unix_read(), unix_write(), unix_close().
  311. //
  312. // On Unix, this is based on open(), but the Windows implementation (in
  313. // sysdeps_win32.cpp) uses Windows native file I/O and bypasses the C Runtime
  314. // and its CR/LF translation. The returned file descriptor should be used with
  315. // adb_read(), adb_write(), adb_close(), etc.
  316. static __inline__ int adb_open( const char* pathname, int options )
  317. {
  318. int fd = TEMP_FAILURE_RETRY( open( pathname, options ) );
  319. if (fd < 0)
  320. return -1;
  321. close_on_exec( fd );
  322. return fd;
  323. }
  324. #undef open
  325. #define open ___xxx_open
  326. static __inline__ int adb_shutdown(int fd, int direction = SHUT_RDWR) {
  327. return shutdown(fd, direction);
  328. }
  329. #undef shutdown
  330. #define shutdown ____xxx_shutdown
  331. // Closes a file descriptor that came from adb_open() or adb_open_mode(), but
  332. // not designed to take a file descriptor from unix_open(). See the comments
  333. // for adb_open() for more info.
  334. __inline__ int adb_close(int fd) {
  335. return close(fd);
  336. }
  337. #undef close
  338. #define close ____xxx_close
  339. // On Windows, ADB has an indirection layer for file descriptors. If we get a
  340. // Win32 SOCKET object from an external library, we have to map it in to that
  341. // indirection layer, which this does.
  342. __inline__ int adb_register_socket(int s) {
  343. return s;
  344. }
  345. static __inline__ int adb_read(int fd, void* buf, size_t len)
  346. {
  347. return TEMP_FAILURE_RETRY( read( fd, buf, len ) );
  348. }
  349. // Like unix_read(), but does not handle EINTR.
  350. static __inline__ int unix_read_interruptible(int fd, void* buf, size_t len) {
  351. return read(fd, buf, len);
  352. }
  353. #undef read
  354. #define read ___xxx_read
  355. static __inline__ int adb_write(int fd, const void* buf, size_t len)
  356. {
  357. return TEMP_FAILURE_RETRY( write( fd, buf, len ) );
  358. }
  359. #undef write
  360. #define write ___xxx_write
  361. static __inline__ int64_t adb_lseek(int fd, int64_t pos, int where) {
  362. #if defined(__APPLE__)
  363. return lseek(fd, pos, where);
  364. #else
  365. return lseek64(fd, pos, where);
  366. #endif
  367. }
  368. #undef lseek
  369. #define lseek ___xxx_lseek
  370. static __inline__ int adb_unlink(const char* path)
  371. {
  372. return unlink(path);
  373. }
  374. #undef unlink
  375. #define unlink ___xxx_unlink
  376. static __inline__ int adb_creat(const char* path, int mode)
  377. {
  378. int fd = TEMP_FAILURE_RETRY( creat( path, mode ) );
  379. if ( fd < 0 )
  380. return -1;
  381. close_on_exec(fd);
  382. return fd;
  383. }
  384. #undef creat
  385. #define creat ___xxx_creat
  386. static __inline__ int unix_isatty(int fd) {
  387. return isatty(fd);
  388. }
  389. #define isatty ___xxx_isatty
  390. // Helper for network_* functions.
  391. inline int _fd_set_error_str(int fd, std::string* error) {
  392. if (fd == -1) {
  393. *error = strerror(errno);
  394. }
  395. return fd;
  396. }
  397. inline int network_inaddr_any_server(int port, int type, std::string* error) {
  398. return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
  399. }
  400. inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
  401. return _fd_set_error_str(socket_local_client(name, namespace_id, type), error);
  402. }
  403. inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
  404. return _fd_set_error_str(socket_local_server(name, namespace_id, type), error);
  405. }
  406. int network_connect(const std::string& host, int port, int type, int timeout, std::string* error);
  407. static __inline__ int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
  408. {
  409. int fd;
  410. fd = TEMP_FAILURE_RETRY( accept( serverfd, addr, addrlen ) );
  411. if (fd >= 0)
  412. close_on_exec(fd);
  413. return fd;
  414. }
  415. #undef accept
  416. #define accept ___xxx_accept
  417. inline int adb_socket_get_local_port(int fd) {
  418. return socket_get_local_port(fd);
  419. }
  420. // Operate on a file descriptor returned from unix_open() or a well-known file
  421. // descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
  422. //
  423. // On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
  424. // adb_write(), adb_close() (which all map to Unix system calls), but the
  425. // Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
  426. // into the C Runtime and its configurable CR/LF translation (which is settable
  427. // via _setmode()).
  428. #define unix_read adb_read
  429. #define unix_write adb_write
  430. #define unix_lseek adb_lseek
  431. #define unix_close adb_close
  432. static __inline__ int adb_thread_setname(const std::string& name) {
  433. #ifdef __APPLE__
  434. return pthread_setname_np(name.c_str());
  435. #else
  436. // Both bionic and glibc's pthread_setname_np fails rather than truncating long strings.
  437. // glibc doesn't have strlcpy, so we have to fake it.
  438. char buf[16]; // MAX_TASK_COMM_LEN, but that's not exported by the kernel headers.
  439. strncpy(buf, name.c_str(), sizeof(buf) - 1);
  440. buf[sizeof(buf) - 1] = '\0';
  441. return pthread_setname_np(pthread_self(), buf);
  442. #endif
  443. }
  444. static __inline__ int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
  445. {
  446. return setsockopt( fd, level, optname, optval, optlen );
  447. }
  448. #undef setsockopt
  449. #define setsockopt ___xxx_setsockopt
  450. static __inline__ int unix_socketpair( int d, int type, int protocol, int sv[2] )
  451. {
  452. return socketpair( d, type, protocol, sv );
  453. }
  454. static __inline__ int adb_socketpair( int sv[2] )
  455. {
  456. int rc;
  457. rc = unix_socketpair( AF_UNIX, SOCK_STREAM, 0, sv );
  458. if (rc < 0)
  459. return -1;
  460. close_on_exec( sv[0] );
  461. close_on_exec( sv[1] );
  462. return 0;
  463. }
  464. #undef socketpair
  465. #define socketpair ___xxx_socketpair
  466. typedef struct pollfd adb_pollfd;
  467. static __inline__ int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
  468. return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
  469. }
  470. #define poll ___xxx_poll
  471. static __inline__ int adb_mkdir(const std::string& path, int mode)
  472. {
  473. return mkdir(path.c_str(), mode);
  474. }
  475. #undef mkdir
  476. #define mkdir ___xxx_mkdir
  477. static __inline__ int adb_is_absolute_host_path(const char* path) {
  478. return path[0] == '/';
  479. }
  480. #endif /* !_WIN32 */
  481. static inline void disable_tcp_nagle(int fd) {
  482. int off = 1;
  483. adb_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
  484. }
  485. // Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
  486. // |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
  487. // configured to drop after 10 missed keepalives. Returns true on success.
  488. bool set_tcp_keepalive(int fd, int interval_sec);
  489. #if defined(_WIN32)
  490. // Win32 defines ERROR, which we don't need, but which conflicts with google3 logging.
  491. #undef ERROR
  492. #endif
  493. #endif /* _ADB_SYSDEPS_H */