blob: f95a8556faca2aede5eb79ec7b27a43c4aa5cdee [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
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
Elliott Hughes381cfa92015-07-23 17:12:58 -070027#include <errno.h>
28
Spencer Low5200c662015-07-30 23:07:55 -070029#include <string>
Spencer Lowa30b79a2015-11-15 16:29:36 -080030#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070031
Josh Gao13ea01d2016-05-13 14:52:06 -070032// Include this before open/close/unlink are defined as macros below.
Josh Gao3b3e10d2016-02-09 14:59:09 -080033#include <android-base/errors.h>
Josh Gao13ea01d2016-05-13 14:52:06 -070034#include <android-base/unique_fd.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080035#include <android-base/utf8.h>
Spencer Lowd21dc822015-11-12 15:20:15 -080036
Josh Gaoa3577e12016-12-05 13:24:48 -080037#include "sysdeps/errno.h"
Josh Gaof551ea02016-07-28 18:09:48 -070038#include "sysdeps/stat.h"
39
Dan Albertcc731cc2015-02-24 21:26:58 -080040/*
41 * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
42 * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
43 * not already defined, then define it here.
44 */
45#ifndef TEMP_FAILURE_RETRY
46/* Used to retry syscalls that can return EINTR. */
47#define TEMP_FAILURE_RETRY(exp) ({ \
48 typeof (exp) _rc; \
49 do { \
50 _rc = (exp); \
51 } while (_rc == -1 && errno == EINTR); \
52 _rc; })
53#endif
54
Spencer Lowcf4ff642015-05-11 01:08:48 -070055// Some printf-like functions are implemented in terms of
56// android::base::StringAppendV, so they should use the same attribute for
57// compile-time format string checking. On Windows, if the mingw version of
58// vsnprintf is used in StringAppendV, use `gnu_printf' which allows z in %zd
59// and PRIu64 (and related) to be recognized by the compile-time checking.
60#define ADB_FORMAT_ARCHETYPE __printf__
61#ifdef __USE_MINGW_ANSI_STDIO
62#if __USE_MINGW_ANSI_STDIO
63#undef ADB_FORMAT_ARCHETYPE
64#define ADB_FORMAT_ARCHETYPE gnu_printf
65#endif
66#endif
67
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080068#ifdef _WIN32
69
Josh Gaoa166e712016-01-29 12:08:34 -080070// Clang-only nullability specifiers
71#define _Nonnull
72#define _Nullable
73
Dan Albert630b9af2014-11-24 23:34:35 -080074#include <ctype.h>
75#include <direct.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070076#include <dirent.h>
Dan Albert630b9af2014-11-24 23:34:35 -080077#include <errno.h>
78#include <fcntl.h>
79#include <io.h>
80#include <process.h>
81#include <sys/stat.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070082#include <utime.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080083#include <winsock2.h>
Stephen Hines2f431a82014-10-01 17:37:06 -070084#include <windows.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080085#include <ws2tcpip.h>
Dan Albert630b9af2014-11-24 23:34:35 -080086
Spencer Low2122c7a2015-08-26 18:46:09 -070087#include <memory> // unique_ptr
Spencer Lowd21dc822015-11-12 15:20:15 -080088#include <string>
Alex Vallée47d67c92015-05-06 16:26:00 -040089
Dan Albert630b9af2014-11-24 23:34:35 -080090#include "fdevent.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080091
Elliott Hughes5c742702015-07-30 17:42:01 -070092#define OS_PATH_SEPARATORS "\\/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080093#define OS_PATH_SEPARATOR '\\'
94#define OS_PATH_SEPARATOR_STR "\\"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070095#define ENV_PATH_SEPARATOR_STR ";"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080096
Josh Gao07db1192015-11-07 15:38:19 -080097static __inline__ bool adb_is_separator(char c) {
98 return c == '\\' || c == '/';
99}
100
Josh Gaob5fea142016-02-12 14:31:15 -0800101typedef void (*adb_thread_func_t)(void* arg);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800102typedef HANDLE adb_thread_t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800103
Josh Gaob5fea142016-02-12 14:31:15 -0800104struct adb_winthread_args {
Josh Gao3b3e10d2016-02-09 14:59:09 -0800105 adb_thread_func_t func;
106 void* arg;
107};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800108
Josh Gaob5fea142016-02-12 14:31:15 -0800109static unsigned __stdcall adb_winthread_wrapper(void* heap_args) {
110 // Move the arguments from the heap onto the thread's stack.
111 adb_winthread_args thread_args = *static_cast<adb_winthread_args*>(heap_args);
112 delete static_cast<adb_winthread_args*>(heap_args);
113 thread_args.func(thread_args.arg);
114 return 0;
Josh Gao3b3e10d2016-02-09 14:59:09 -0800115}
116
117static __inline__ bool adb_thread_create(adb_thread_func_t func, void* arg,
118 adb_thread_t* thread = nullptr) {
Josh Gaob5fea142016-02-12 14:31:15 -0800119 adb_winthread_args* args = new adb_winthread_args{.func = func, .arg = arg};
120 uintptr_t handle = _beginthreadex(nullptr, 0, adb_winthread_wrapper, args, 0, nullptr);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800121 if (handle != static_cast<uintptr_t>(0)) {
122 if (thread) {
123 *thread = reinterpret_cast<HANDLE>(handle);
124 } else {
125 CloseHandle(thread);
126 }
127 return true;
128 }
129 return false;
130}
131
132static __inline__ bool adb_thread_join(adb_thread_t thread) {
133 switch (WaitForSingleObject(thread, INFINITE)) {
134 case WAIT_OBJECT_0:
135 CloseHandle(thread);
136 return true;
137
138 case WAIT_FAILED:
139 fprintf(stderr, "adb_thread_join failed: %s\n",
140 android::base::SystemErrorCodeToString(GetLastError()).c_str());
141 break;
142
143 default:
144 abort();
145 }
146
147 return false;
148}
149
150static __inline__ bool adb_thread_detach(adb_thread_t thread) {
151 CloseHandle(thread);
152 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800153}
154
Josh Gaob5fea142016-02-12 14:31:15 -0800155static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
Josh Gaod7b37492016-02-12 15:45:04 -0800156 _endthreadex(0);
Josh Gaob5fea142016-02-12 14:31:15 -0800157}
158
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700159static __inline__ int adb_thread_setname(const std::string& name) {
160 // TODO: See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx for how to set
161 // the thread name in Windows. Unfortunately, it only works during debugging, but
162 // our build process doesn't generate PDB files needed for debugging.
163 return 0;
164}
165
Josh Gao3777d2e2016-02-16 17:34:53 -0800166static __inline__ adb_thread_t adb_thread_self() {
167 return GetCurrentThread();
168}
169
170static __inline__ bool adb_thread_equal(adb_thread_t lhs, adb_thread_t rhs) {
171 return GetThreadId(lhs) == GetThreadId(rhs);
172}
173
leozwangcbf02672014-08-15 09:51:27 -0700174static __inline__ unsigned long adb_thread_id()
175{
176 return GetCurrentThreadId();
177}
178
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800179static __inline__ void close_on_exec(int fd)
180{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200181 /* nothing really */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800182}
183
Spencer Lowcf4ff642015-05-11 01:08:48 -0700184extern int adb_unlink(const char* path);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800185#undef unlink
186#define unlink ___xxx_unlink
187
Spencer Lowcf4ff642015-05-11 01:08:48 -0700188extern int adb_mkdir(const std::string& path, int mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189#undef mkdir
190#define mkdir ___xxx_mkdir
191
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700192// See the comments for the !defined(_WIN32) versions of adb_*().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800193extern int adb_open(const char* path, int options);
194extern int adb_creat(const char* path, int mode);
195extern int adb_read(int fd, void* buf, int len);
196extern int adb_write(int fd, const void* buf, int len);
197extern int adb_lseek(int fd, int pos, int where);
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400198extern int adb_shutdown(int fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800199extern int adb_close(int fd);
Casey Dahlin2fe9b602016-09-21 14:03:39 -0700200extern int adb_register_socket(SOCKET s);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700202// See the comments for the !defined(_WIN32) version of unix_close().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800203static __inline__ int unix_close(int fd)
204{
205 return close(fd);
206}
207#undef close
208#define close ____xxx_close
209
Spencer Low2e02dc62015-11-07 17:34:39 -0800210// Like unix_read(), but may return EINTR.
211extern int unix_read_interruptible(int fd, void* buf, size_t len);
212
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700213// See the comments for the !defined(_WIN32) version of unix_read().
Spencer Low2e02dc62015-11-07 17:34:39 -0800214static __inline__ int unix_read(int fd, void* buf, size_t len) {
215 return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
216}
Spencer Low50184062015-03-01 15:06:21 -0800217
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800218#undef read
219#define read ___xxx_read
220
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700221// See the comments for the !defined(_WIN32) version of unix_write().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800222static __inline__ int unix_write(int fd, const void* buf, size_t len)
223{
224 return write(fd, buf, len);
225}
226#undef write
227#define write ___xxx_write
228
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700229// See the comments for the !defined(_WIN32) version of adb_open_mode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800230static __inline__ int adb_open_mode(const char* path, int options, int mode)
231{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200232 return adb_open(path, options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800233}
234
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700235// See the comments for the !defined(_WIN32) version of unix_open().
Spencer Lowcf4ff642015-05-11 01:08:48 -0700236extern int unix_open(const char* path, int options, ...);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800237#define open ___xxx_unix_open
238
David Pursellc5b8ad82015-10-28 14:29:51 -0700239// Checks if |fd| corresponds to a console.
240// Standard Windows isatty() returns 1 for both console FDs and character
241// devices like NUL. unix_isatty() performs some extra checking to only match
242// console FDs.
243// |fd| must be a real file descriptor, meaning STDxx_FILENO or unix_open() FDs
244// will work but adb_open() FDs will not. Additionally the OS handle associated
245// with |fd| must have GENERIC_READ access (which console FDs have by default).
246// Returns 1 if |fd| is a console FD, 0 otherwise. The value of errno after
247// calling this function is unreliable and should not be used.
248int unix_isatty(int fd);
249#define isatty ___xxx_isatty
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800250
Spencer Low5200c662015-07-30 23:07:55 -0700251int network_loopback_client(int port, int type, std::string* error);
252int network_loopback_server(int port, int type, std::string* error);
253int network_inaddr_any_server(int port, int type, std::string* error);
Josh Gaocfb21412016-08-24 18:38:44 -0700254
255inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
256 abort();
257}
258
259inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
260 abort();
261}
262
Spencer Low5200c662015-07-30 23:07:55 -0700263int network_connect(const std::string& host, int port, int type, int timeout,
264 std::string* error);
265
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800266extern int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen);
267
268#undef accept
269#define accept ___xxx_accept
270
David Purselleaae97e2016-04-07 11:25:48 -0700271// Returns the local port number of a bound socket, or -1 on failure.
272int adb_socket_get_local_port(int fd);
273
Spencer Lowf055c192015-01-25 14:40:16 -0800274extern int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen);
275
276#undef setsockopt
277#define setsockopt ___xxx_setsockopt
278
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800279extern int adb_socketpair( int sv[2] );
280
Josh Gao3777d2e2016-02-16 17:34:53 -0800281struct adb_pollfd {
282 int fd;
283 short events;
284 short revents;
285};
286extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout);
287#define poll ___xxx_poll
288
Elliott Hughes5c742702015-07-30 17:42:01 -0700289static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800290 return isalpha(path[0]) && path[1] == ':' && path[2] == '\\';
291}
292
Spencer Lowcf4ff642015-05-11 01:08:48 -0700293// UTF-8 versions of POSIX APIs.
294extern DIR* adb_opendir(const char* dirname);
295extern struct dirent* adb_readdir(DIR* dir);
296extern int adb_closedir(DIR* dir);
297
298extern int adb_utime(const char *, struct utimbuf *);
299extern int adb_chmod(const char *, int);
300
301extern int adb_vfprintf(FILE *stream, const char *format, va_list ap)
302 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 0)));
Spencer Lowa30b79a2015-11-15 16:29:36 -0800303extern int adb_vprintf(const char *format, va_list ap)
304 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -0700305extern int adb_fprintf(FILE *stream, const char *format, ...)
306 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3)));
307extern int adb_printf(const char *format, ...)
308 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
309
310extern int adb_fputs(const char* buf, FILE* stream);
311extern int adb_fputc(int ch, FILE* stream);
Spencer Lowa30b79a2015-11-15 16:29:36 -0800312extern int adb_putchar(int ch);
313extern int adb_puts(const char* buf);
Spencer Lowcf4ff642015-05-11 01:08:48 -0700314extern size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb,
315 FILE* stream);
316
317extern FILE* adb_fopen(const char* f, const char* m);
318
319extern char* adb_getenv(const char* name);
320
321extern char* adb_getcwd(char* buf, int size);
322
323// Remap calls to POSIX APIs to our UTF-8 versions.
324#define opendir adb_opendir
325#define readdir adb_readdir
326#define closedir adb_closedir
327#define rewinddir rewinddir_utf8_not_yet_implemented
328#define telldir telldir_utf8_not_yet_implemented
Spencer Low363af562015-11-07 18:51:54 -0800329// Some compiler's C++ headers have members named seekdir, so we can't do the
330// macro technique and instead cause a link error if seekdir is called.
331inline void seekdir(DIR*, long) {
332 extern int seekdir_utf8_not_yet_implemented;
333 seekdir_utf8_not_yet_implemented = 1;
334}
Spencer Lowcf4ff642015-05-11 01:08:48 -0700335
336#define utime adb_utime
337#define chmod adb_chmod
338
339#define vfprintf adb_vfprintf
Spencer Lowa30b79a2015-11-15 16:29:36 -0800340#define vprintf adb_vprintf
Spencer Lowcf4ff642015-05-11 01:08:48 -0700341#define fprintf adb_fprintf
342#define printf adb_printf
343#define fputs adb_fputs
344#define fputc adb_fputc
Spencer Lowa30b79a2015-11-15 16:29:36 -0800345// putc may be a macro, so if so, undefine it, so that we can redefine it.
346#undef putc
347#define putc(c, s) adb_fputc(c, s)
348#define putchar adb_putchar
349#define puts adb_puts
Spencer Lowcf4ff642015-05-11 01:08:48 -0700350#define fwrite adb_fwrite
351
352#define fopen adb_fopen
Spencer Lowa30b79a2015-11-15 16:29:36 -0800353#define freopen freopen_utf8_not_yet_implemented
Spencer Lowcf4ff642015-05-11 01:08:48 -0700354
355#define getenv adb_getenv
356#define putenv putenv_utf8_not_yet_implemented
357#define setenv setenv_utf8_not_yet_implemented
358#define unsetenv unsetenv_utf8_not_yet_implemented
359
360#define getcwd adb_getcwd
361
Spencer Lowcf4ff642015-05-11 01:08:48 -0700362// Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
363// passed to main().
364class NarrowArgs {
365public:
366 NarrowArgs(int argc, wchar_t** argv);
367 ~NarrowArgs();
368
369 inline char** data() {
370 return narrow_args;
371 }
372
373private:
374 char** narrow_args;
375};
376
Spencer Low5c398d22015-08-08 15:07:07 -0700377// Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
378// so they can fit in an int. To convert back, we just need to sign-extend.
379// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
380// Note that this does not make a HANDLE value work with APIs like open(), nor
381// does this make a value from open() passable to APIs taking a HANDLE. This
382// just lets you take a HANDLE, pass it around as an int, and then use it again
383// as a HANDLE.
384inline int cast_handle_to_int(const HANDLE h) {
385 // truncate
386 return static_cast<int>(reinterpret_cast<INT_PTR>(h));
387}
388
389inline HANDLE cast_int_to_handle(const int fd) {
390 // sign-extend
391 return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
392}
393
Spencer Low2122c7a2015-08-26 18:46:09 -0700394// Deleter for unique_handle. Adapted from many sources, including:
395// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
396// https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
397class handle_deleter {
398public:
399 typedef HANDLE pointer;
400
401 void operator()(HANDLE h);
402};
403
404// Like std::unique_ptr, but for Windows HANDLE objects that should be
405// CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
406// but does not check if the handle != INVALID_HANDLE_VALUE.
407typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
408
Spencer Lowa30b79a2015-11-15 16:29:36 -0800409namespace internal {
410
411size_t ParseCompleteUTF8(const char* first, const char* last, std::vector<char>* remaining_bytes);
412
413}
414
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800415#else /* !_WIN32 a.k.a. Unix */
416
Spencer Low5200c662015-07-30 23:07:55 -0700417#include <cutils/sockets.h>
Spencer Low8d8126a2015-07-21 02:06:26 -0700418#include <cutils/threads.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800419#include <fcntl.h>
Josh Gao3777d2e2016-02-16 17:34:53 -0800420#include <poll.h>
421#include <signal.h>
422#include <sys/stat.h>
423#include <sys/wait.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424
425#include <pthread.h>
426#include <unistd.h>
427#include <fcntl.h>
428#include <stdarg.h>
Spencer Low5200c662015-07-30 23:07:55 -0700429#include <netdb.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800430#include <netinet/in.h>
431#include <netinet/tcp.h>
432#include <string.h>
Kenny Root73167412012-10-12 15:26:45 -0700433#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800434
Alex Vallée47d67c92015-05-06 16:26:00 -0400435#include <string>
436
Elliott Hughes5c742702015-07-30 17:42:01 -0700437#define OS_PATH_SEPARATORS "/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800438#define OS_PATH_SEPARATOR '/'
439#define OS_PATH_SEPARATOR_STR "/"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700440#define ENV_PATH_SEPARATOR_STR ":"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800441
Josh Gao07db1192015-11-07 15:38:19 -0800442static __inline__ bool adb_is_separator(char c) {
443 return c == '/';
444}
445
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446static __inline__ void close_on_exec(int fd)
447{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200448 fcntl( fd, F_SETFD, FD_CLOEXEC );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800449}
450
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700451// Open a file and return a file descriptor that may be used with unix_read(),
452// unix_write(), unix_close(), but not adb_read(), adb_write(), adb_close().
453//
454// On Unix, this is based on open(), so the file descriptor is a real OS file
455// descriptor, but the Windows implementation (in sysdeps_win32.cpp) returns a
456// file descriptor that can only be used with C Runtime APIs (which are wrapped
457// by unix_read(), unix_write(), unix_close()). Also, the C Runtime has
458// configurable CR/LF translation which defaults to text mode, but is settable
459// with _setmode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460static __inline__ int unix_open(const char* path, int options,...)
461{
462 if ((options & O_CREAT) == 0)
463 {
Kenny Root73167412012-10-12 15:26:45 -0700464 return TEMP_FAILURE_RETRY( open(path, options) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800465 }
466 else
467 {
468 int mode;
469 va_list args;
470 va_start( args, options );
471 mode = va_arg( args, int );
472 va_end( args );
Kenny Root73167412012-10-12 15:26:45 -0700473 return TEMP_FAILURE_RETRY( open( path, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800474 }
475}
476
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700477// Similar to the two-argument adb_open(), but takes a mode parameter for file
478// creation. See adb_open() for more info.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479static __inline__ int adb_open_mode( const char* pathname, int options, int mode )
480{
Kenny Root73167412012-10-12 15:26:45 -0700481 return TEMP_FAILURE_RETRY( open( pathname, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800482}
483
484
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700485// Open a file and return a file descriptor that may be used with adb_read(),
486// adb_write(), adb_close(), but not unix_read(), unix_write(), unix_close().
487//
488// On Unix, this is based on open(), but the Windows implementation (in
489// sysdeps_win32.cpp) uses Windows native file I/O and bypasses the C Runtime
490// and its CR/LF translation. The returned file descriptor should be used with
491// adb_read(), adb_write(), adb_close(), etc.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492static __inline__ int adb_open( const char* pathname, int options )
493{
Kenny Root73167412012-10-12 15:26:45 -0700494 int fd = TEMP_FAILURE_RETRY( open( pathname, options ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800495 if (fd < 0)
496 return -1;
497 close_on_exec( fd );
498 return fd;
499}
500#undef open
501#define open ___xxx_open
502
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400503static __inline__ int adb_shutdown(int fd)
504{
505 return shutdown(fd, SHUT_RDWR);
506}
David Pursell1ed57f02015-10-06 15:30:03 -0700507static __inline__ int adb_shutdown(int fd, int direction)
508{
509 return shutdown(fd, direction);
510}
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400511#undef shutdown
512#define shutdown ____xxx_shutdown
513
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700514// Closes a file descriptor that came from adb_open() or adb_open_mode(), but
515// not designed to take a file descriptor from unix_open(). See the comments
516// for adb_open() for more info.
Josh Gaof0d3b4f2016-03-04 15:15:56 -0800517__inline__ int adb_close(int fd) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800518 return close(fd);
519}
520#undef close
521#define close ____xxx_close
522
Casey Dahlin2fe9b602016-09-21 14:03:39 -0700523// On Windows, ADB has an indirection layer for file descriptors. If we get a
524// Win32 SOCKET object from an external library, we have to map it in to that
525// indirection layer, which this does.
526__inline__ int adb_register_socket(int s) {
527 return s;
528}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800529
530static __inline__ int adb_read(int fd, void* buf, size_t len)
531{
Kenny Root73167412012-10-12 15:26:45 -0700532 return TEMP_FAILURE_RETRY( read( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800533}
534
Spencer Low2e02dc62015-11-07 17:34:39 -0800535// Like unix_read(), but does not handle EINTR.
536static __inline__ int unix_read_interruptible(int fd, void* buf, size_t len) {
537 return read(fd, buf, len);
538}
539
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800540#undef read
541#define read ___xxx_read
542
543static __inline__ int adb_write(int fd, const void* buf, size_t len)
544{
Kenny Root73167412012-10-12 15:26:45 -0700545 return TEMP_FAILURE_RETRY( write( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800546}
547#undef write
548#define write ___xxx_write
549
550static __inline__ int adb_lseek(int fd, int pos, int where)
551{
552 return lseek(fd, pos, where);
553}
554#undef lseek
555#define lseek ___xxx_lseek
556
557static __inline__ int adb_unlink(const char* path)
558{
559 return unlink(path);
560}
561#undef unlink
562#define unlink ___xxx_unlink
563
564static __inline__ int adb_creat(const char* path, int mode)
565{
Kenny Root73167412012-10-12 15:26:45 -0700566 int fd = TEMP_FAILURE_RETRY( creat( path, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800567
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200568 if ( fd < 0 )
569 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800570
571 close_on_exec(fd);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200572 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800573}
574#undef creat
575#define creat ___xxx_creat
576
David Pursellc5b8ad82015-10-28 14:29:51 -0700577static __inline__ int unix_isatty(int fd) {
578 return isatty(fd);
579}
580#define isatty ___xxx_isatty
581
Spencer Low5200c662015-07-30 23:07:55 -0700582// Helper for network_* functions.
583inline int _fd_set_error_str(int fd, std::string* error) {
584 if (fd == -1) {
585 *error = strerror(errno);
586 }
587 return fd;
588}
589
590inline int network_loopback_client(int port, int type, std::string* error) {
Elliott Hughes139b3722016-10-11 13:45:03 -0700591 return _fd_set_error_str(socket_network_client("localhost", port, type), error);
Spencer Low5200c662015-07-30 23:07:55 -0700592}
593
594inline int network_loopback_server(int port, int type, std::string* error) {
Tao Wu7b700762016-09-19 16:50:10 -0700595 int fd = socket_loopback_server(port, type);
596 if (fd < 0 && errno == EAFNOSUPPORT)
597 return _fd_set_error_str(socket_loopback_server6(port, type), error);
598 return _fd_set_error_str(fd, error);
Spencer Low5200c662015-07-30 23:07:55 -0700599}
600
601inline int network_inaddr_any_server(int port, int type, std::string* error) {
602 return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
603}
604
Josh Gaocfb21412016-08-24 18:38:44 -0700605inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
606 return _fd_set_error_str(socket_local_client(name, namespace_id, type), error);
607}
608
609inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
610 return _fd_set_error_str(socket_local_server(name, namespace_id, type), error);
Spencer Low5200c662015-07-30 23:07:55 -0700611}
612
613inline int network_connect(const std::string& host, int port, int type,
614 int timeout, std::string* error) {
615 int getaddrinfo_error = 0;
616 int fd = socket_network_client_timeout(host.c_str(), port, type, timeout,
617 &getaddrinfo_error);
618 if (fd != -1) {
619 return fd;
620 }
621 if (getaddrinfo_error != 0) {
622 *error = gai_strerror(getaddrinfo_error);
623 } else {
624 *error = strerror(errno);
625 }
626 return -1;
627}
628
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800629static __inline__ int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
630{
Benoit Goby95ef8282011-02-01 18:57:41 -0800631 int fd;
632
Kenny Root73167412012-10-12 15:26:45 -0700633 fd = TEMP_FAILURE_RETRY( accept( serverfd, addr, addrlen ) );
Benoit Goby95ef8282011-02-01 18:57:41 -0800634 if (fd >= 0)
635 close_on_exec(fd);
636
637 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800638}
639
640#undef accept
641#define accept ___xxx_accept
642
David Purselleaae97e2016-04-07 11:25:48 -0700643inline int adb_socket_get_local_port(int fd) {
644 return socket_get_local_port(fd);
645}
646
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700647// Operate on a file descriptor returned from unix_open() or a well-known file
648// descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
649//
650// On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
651// adb_write(), adb_close() (which all map to Unix system calls), but the
652// Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
653// into the C Runtime and its configurable CR/LF translation (which is settable
654// via _setmode()).
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800655#define unix_read adb_read
656#define unix_write adb_write
657#define unix_close adb_close
658
Josh Gaob5fea142016-02-12 14:31:15 -0800659// Win32 is limited to DWORDs for thread return values; limit the POSIX systems to this as well to
660// ensure compatibility.
661typedef void (*adb_thread_func_t)(void* arg);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800662typedef pthread_t adb_thread_t;
663
Josh Gaob5fea142016-02-12 14:31:15 -0800664struct adb_pthread_args {
665 adb_thread_func_t func;
666 void* arg;
667};
668
669static void* adb_pthread_wrapper(void* heap_args) {
670 // Move the arguments from the heap onto the thread's stack.
671 adb_pthread_args thread_args = *reinterpret_cast<adb_pthread_args*>(heap_args);
672 delete static_cast<adb_pthread_args*>(heap_args);
673 thread_args.func(thread_args.arg);
674 return nullptr;
675}
676
Josh Gao3b3e10d2016-02-09 14:59:09 -0800677static __inline__ bool adb_thread_create(adb_thread_func_t start, void* arg,
678 adb_thread_t* thread = nullptr) {
679 pthread_t temp;
Elliott Hughes9b0f3542015-05-05 13:41:21 -0700680 pthread_attr_t attr;
681 pthread_attr_init(&attr);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800682 pthread_attr_setdetachstate(&attr, thread ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
Josh Gaob5fea142016-02-12 14:31:15 -0800683 auto* pthread_args = new adb_pthread_args{.func = start, .arg = arg};
684 errno = pthread_create(&temp, &attr, adb_pthread_wrapper, pthread_args);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800685 if (errno == 0) {
686 if (thread) {
687 *thread = temp;
688 }
689 return true;
690 }
691 return false;
692}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800693
Josh Gao3b3e10d2016-02-09 14:59:09 -0800694static __inline__ bool adb_thread_join(adb_thread_t thread) {
695 errno = pthread_join(thread, nullptr);
696 return errno == 0;
697}
698
699static __inline__ bool adb_thread_detach(adb_thread_t thread) {
700 errno = pthread_detach(thread);
701 return errno == 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800702}
703
Josh Gaob5fea142016-02-12 14:31:15 -0800704static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
705 pthread_exit(nullptr);
706}
707
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700708static __inline__ int adb_thread_setname(const std::string& name) {
709#ifdef __APPLE__
710 return pthread_setname_np(name.c_str());
711#else
712 const char *s = name.c_str();
713
714 // pthread_setname_np fails rather than truncating long strings.
715 const int max_task_comm_len = 16; // including the null terminator
716 if (name.length() > (max_task_comm_len - 1)) {
717 char buf[max_task_comm_len];
718 strncpy(buf, name.c_str(), sizeof(buf) - 1);
719 buf[sizeof(buf) - 1] = '\0';
720 s = buf;
721 }
722
723 return pthread_setname_np(pthread_self(), s) ;
724#endif
725}
726
Spencer Lowf055c192015-01-25 14:40:16 -0800727static __inline__ int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
728{
729 return setsockopt( fd, level, optname, optval, optlen );
730}
731
732#undef setsockopt
733#define setsockopt ___xxx_setsockopt
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800734
735static __inline__ int unix_socketpair( int d, int type, int protocol, int sv[2] )
736{
737 return socketpair( d, type, protocol, sv );
738}
739
740static __inline__ int adb_socketpair( int sv[2] )
741{
742 int rc;
743
744 rc = unix_socketpair( AF_UNIX, SOCK_STREAM, 0, sv );
745 if (rc < 0)
746 return -1;
747
748 close_on_exec( sv[0] );
749 close_on_exec( sv[1] );
750 return 0;
751}
752
753#undef socketpair
754#define socketpair ___xxx_socketpair
755
Josh Gao3777d2e2016-02-16 17:34:53 -0800756typedef struct pollfd adb_pollfd;
757static __inline__ int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
758 return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
759}
760
761#define poll ___xxx_poll
762
Alex Vallée47d67c92015-05-06 16:26:00 -0400763static __inline__ int adb_mkdir(const std::string& path, int mode)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800764{
Alex Vallée47d67c92015-05-06 16:26:00 -0400765 return mkdir(path.c_str(), mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800766}
Alex Vallée47d67c92015-05-06 16:26:00 -0400767
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800768#undef mkdir
769#define mkdir ___xxx_mkdir
770
Alex Vallée47d67c92015-05-06 16:26:00 -0400771static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800772 return path[0] == '/';
773}
774
leozwangcbf02672014-08-15 09:51:27 -0700775static __inline__ unsigned long adb_thread_id()
776{
Spencer Low8d8126a2015-07-21 02:06:26 -0700777 return (unsigned long)gettid();
leozwangcbf02672014-08-15 09:51:27 -0700778}
779
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800780#endif /* !_WIN32 */
781
Elliott Hughescc65c3b2015-11-20 22:01:06 -0800782static inline void disable_tcp_nagle(int fd) {
783 int off = 1;
784 adb_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
785}
786
David Pursellbfd95032016-02-22 14:27:23 -0800787// Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
788// |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
789// configured to drop after 10 missed keepalives. Returns true on success.
790bool set_tcp_keepalive(int fd, int interval_sec);
791
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700792#if defined(_WIN32)
793// Win32 defines ERROR, which we don't need, but which conflicts with google3 logging.
794#undef ERROR
795#endif
796
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800797#endif /* _ADB_SYSDEPS_H */