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