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