blob: 639f8eb22e60a62fddc543717775d7aaba5991c8 [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
Dan Albertcc731cc2015-02-24 21:26:58 -080037/*
38 * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
39 * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
40 * not already defined, then define it here.
41 */
42#ifndef TEMP_FAILURE_RETRY
43/* Used to retry syscalls that can return EINTR. */
44#define TEMP_FAILURE_RETRY(exp) ({ \
45 typeof (exp) _rc; \
46 do { \
47 _rc = (exp); \
48 } while (_rc == -1 && errno == EINTR); \
49 _rc; })
50#endif
51
Spencer Lowcf4ff642015-05-11 01:08:48 -070052// Some printf-like functions are implemented in terms of
53// android::base::StringAppendV, so they should use the same attribute for
54// compile-time format string checking. On Windows, if the mingw version of
55// vsnprintf is used in StringAppendV, use `gnu_printf' which allows z in %zd
56// and PRIu64 (and related) to be recognized by the compile-time checking.
57#define ADB_FORMAT_ARCHETYPE __printf__
58#ifdef __USE_MINGW_ANSI_STDIO
59#if __USE_MINGW_ANSI_STDIO
60#undef ADB_FORMAT_ARCHETYPE
61#define ADB_FORMAT_ARCHETYPE gnu_printf
62#endif
63#endif
64
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080065#ifdef _WIN32
66
Josh Gaoa166e712016-01-29 12:08:34 -080067// Clang-only nullability specifiers
68#define _Nonnull
69#define _Nullable
70
Dan Albert630b9af2014-11-24 23:34:35 -080071#include <ctype.h>
72#include <direct.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070073#include <dirent.h>
Dan Albert630b9af2014-11-24 23:34:35 -080074#include <errno.h>
75#include <fcntl.h>
76#include <io.h>
77#include <process.h>
78#include <sys/stat.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070079#include <utime.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080080#include <winsock2.h>
Stephen Hines2f431a82014-10-01 17:37:06 -070081#include <windows.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080082#include <ws2tcpip.h>
Dan Albert630b9af2014-11-24 23:34:35 -080083
Spencer Low2122c7a2015-08-26 18:46:09 -070084#include <memory> // unique_ptr
Spencer Lowd21dc822015-11-12 15:20:15 -080085#include <string>
Alex Vallée47d67c92015-05-06 16:26:00 -040086
Dan Albert630b9af2014-11-24 23:34:35 -080087#include "fdevent.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080088
Elliott Hughes5c742702015-07-30 17:42:01 -070089#define OS_PATH_SEPARATORS "\\/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080090#define OS_PATH_SEPARATOR '\\'
91#define OS_PATH_SEPARATOR_STR "\\"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070092#define ENV_PATH_SEPARATOR_STR ";"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080093
Josh Gao07db1192015-11-07 15:38:19 -080094static __inline__ bool adb_is_separator(char c) {
95 return c == '\\' || c == '/';
96}
97
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080098typedef CRITICAL_SECTION adb_mutex_t;
99
100#define ADB_MUTEX_DEFINE(x) adb_mutex_t x
101
102/* declare all mutexes */
JP Abgrall408fa572011-03-16 15:57:42 -0700103/* For win32, adb_sysdeps_init() will do the mutex runtime initialization. */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800104#define ADB_MUTEX(x) extern adb_mutex_t x;
105#include "mutex_list.h"
106
107extern void adb_sysdeps_init(void);
108
109static __inline__ void adb_mutex_lock( adb_mutex_t* lock )
110{
111 EnterCriticalSection( lock );
112}
113
114static __inline__ void adb_mutex_unlock( adb_mutex_t* lock )
115{
116 LeaveCriticalSection( lock );
117}
118
Josh Gaob5fea142016-02-12 14:31:15 -0800119typedef void (*adb_thread_func_t)(void* arg);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800120typedef HANDLE adb_thread_t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800121
Josh Gaob5fea142016-02-12 14:31:15 -0800122struct adb_winthread_args {
Josh Gao3b3e10d2016-02-09 14:59:09 -0800123 adb_thread_func_t func;
124 void* arg;
125};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800126
Josh Gaob5fea142016-02-12 14:31:15 -0800127static unsigned __stdcall adb_winthread_wrapper(void* heap_args) {
128 // Move the arguments from the heap onto the thread's stack.
129 adb_winthread_args thread_args = *static_cast<adb_winthread_args*>(heap_args);
130 delete static_cast<adb_winthread_args*>(heap_args);
131 thread_args.func(thread_args.arg);
132 return 0;
Josh Gao3b3e10d2016-02-09 14:59:09 -0800133}
134
135static __inline__ bool adb_thread_create(adb_thread_func_t func, void* arg,
136 adb_thread_t* thread = nullptr) {
Josh Gaob5fea142016-02-12 14:31:15 -0800137 adb_winthread_args* args = new adb_winthread_args{.func = func, .arg = arg};
138 uintptr_t handle = _beginthreadex(nullptr, 0, adb_winthread_wrapper, args, 0, nullptr);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800139 if (handle != static_cast<uintptr_t>(0)) {
140 if (thread) {
141 *thread = reinterpret_cast<HANDLE>(handle);
142 } else {
143 CloseHandle(thread);
144 }
145 return true;
146 }
147 return false;
148}
149
150static __inline__ bool adb_thread_join(adb_thread_t thread) {
151 switch (WaitForSingleObject(thread, INFINITE)) {
152 case WAIT_OBJECT_0:
153 CloseHandle(thread);
154 return true;
155
156 case WAIT_FAILED:
157 fprintf(stderr, "adb_thread_join failed: %s\n",
158 android::base::SystemErrorCodeToString(GetLastError()).c_str());
159 break;
160
161 default:
162 abort();
163 }
164
165 return false;
166}
167
168static __inline__ bool adb_thread_detach(adb_thread_t thread) {
169 CloseHandle(thread);
170 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800171}
172
Josh Gaob5fea142016-02-12 14:31:15 -0800173static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
Josh Gaod7b37492016-02-12 15:45:04 -0800174 _endthreadex(0);
Josh Gaob5fea142016-02-12 14:31:15 -0800175}
176
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700177static __inline__ int adb_thread_setname(const std::string& name) {
178 // TODO: See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx for how to set
179 // the thread name in Windows. Unfortunately, it only works during debugging, but
180 // our build process doesn't generate PDB files needed for debugging.
181 return 0;
182}
183
Josh Gao3777d2e2016-02-16 17:34:53 -0800184static __inline__ adb_thread_t adb_thread_self() {
185 return GetCurrentThread();
186}
187
188static __inline__ bool adb_thread_equal(adb_thread_t lhs, adb_thread_t rhs) {
189 return GetThreadId(lhs) == GetThreadId(rhs);
190}
191
leozwangcbf02672014-08-15 09:51:27 -0700192static __inline__ unsigned long adb_thread_id()
193{
194 return GetCurrentThreadId();
195}
196
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800197static __inline__ void close_on_exec(int fd)
198{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200199 /* nothing really */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800200}
201
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800202#define lstat stat /* no symlinks on Win32 */
203
204#define S_ISLNK(m) 0 /* no symlinks on Win32 */
205
Spencer Lowcf4ff642015-05-11 01:08:48 -0700206extern int adb_unlink(const char* path);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800207#undef unlink
208#define unlink ___xxx_unlink
209
Spencer Lowcf4ff642015-05-11 01:08:48 -0700210extern int adb_mkdir(const std::string& path, int mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800211#undef mkdir
212#define mkdir ___xxx_mkdir
213
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700214// See the comments for the !defined(_WIN32) versions of adb_*().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800215extern int adb_open(const char* path, int options);
216extern int adb_creat(const char* path, int mode);
217extern int adb_read(int fd, void* buf, int len);
218extern int adb_write(int fd, const void* buf, int len);
219extern int adb_lseek(int fd, int pos, int where);
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400220extern int adb_shutdown(int fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800221extern int adb_close(int fd);
222
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700223// See the comments for the !defined(_WIN32) version of unix_close().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800224static __inline__ int unix_close(int fd)
225{
226 return close(fd);
227}
228#undef close
229#define close ____xxx_close
230
Spencer Low2e02dc62015-11-07 17:34:39 -0800231// Like unix_read(), but may return EINTR.
232extern int unix_read_interruptible(int fd, void* buf, size_t len);
233
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700234// See the comments for the !defined(_WIN32) version of unix_read().
Spencer Low2e02dc62015-11-07 17:34:39 -0800235static __inline__ int unix_read(int fd, void* buf, size_t len) {
236 return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
237}
Spencer Low50184062015-03-01 15:06:21 -0800238
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800239#undef read
240#define read ___xxx_read
241
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700242// See the comments for the !defined(_WIN32) version of unix_write().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800243static __inline__ int unix_write(int fd, const void* buf, size_t len)
244{
245 return write(fd, buf, len);
246}
247#undef write
248#define write ___xxx_write
249
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700250// See the comments for the !defined(_WIN32) version of adb_open_mode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800251static __inline__ int adb_open_mode(const char* path, int options, int mode)
252{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200253 return adb_open(path, options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800254}
255
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700256// See the comments for the !defined(_WIN32) version of unix_open().
Spencer Lowcf4ff642015-05-11 01:08:48 -0700257extern int unix_open(const char* path, int options, ...);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258#define open ___xxx_unix_open
259
David Pursellc5b8ad82015-10-28 14:29:51 -0700260// Checks if |fd| corresponds to a console.
261// Standard Windows isatty() returns 1 for both console FDs and character
262// devices like NUL. unix_isatty() performs some extra checking to only match
263// console FDs.
264// |fd| must be a real file descriptor, meaning STDxx_FILENO or unix_open() FDs
265// will work but adb_open() FDs will not. Additionally the OS handle associated
266// with |fd| must have GENERIC_READ access (which console FDs have by default).
267// Returns 1 if |fd| is a console FD, 0 otherwise. The value of errno after
268// calling this function is unreliable and should not be used.
269int unix_isatty(int fd);
270#define isatty ___xxx_isatty
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800271
272/* normally provided by <cutils/misc.h> */
273extern void* load_file(const char* pathname, unsigned* psize);
274
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800275static __inline__ void adb_sleep_ms( int mseconds )
276{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200277 Sleep( mseconds );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800278}
279
Spencer Low5200c662015-07-30 23:07:55 -0700280int network_loopback_client(int port, int type, std::string* error);
281int network_loopback_server(int port, int type, std::string* error);
282int network_inaddr_any_server(int port, int type, std::string* error);
283int network_connect(const std::string& host, int port, int type, int timeout,
284 std::string* error);
285
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800286extern int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen);
287
288#undef accept
289#define accept ___xxx_accept
290
David Purselleaae97e2016-04-07 11:25:48 -0700291// Returns the local port number of a bound socket, or -1 on failure.
292int adb_socket_get_local_port(int fd);
293
Spencer Lowf055c192015-01-25 14:40:16 -0800294extern int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen);
295
296#undef setsockopt
297#define setsockopt ___xxx_setsockopt
298
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800299extern int adb_socketpair( int sv[2] );
300
Josh Gao3777d2e2016-02-16 17:34:53 -0800301struct adb_pollfd {
302 int fd;
303 short events;
304 short revents;
305};
306extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout);
307#define poll ___xxx_poll
308
Elliott Hughes5c742702015-07-30 17:42:01 -0700309static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800310 return isalpha(path[0]) && path[1] == ':' && path[2] == '\\';
311}
312
Spencer Lowcf4ff642015-05-11 01:08:48 -0700313// We later define a macro mapping 'stat' to 'adb_stat'. This causes:
314// struct stat s;
315// stat(filename, &s);
316// To turn into the following:
317// struct adb_stat s;
318// adb_stat(filename, &s);
319// To get this to work, we need to make 'struct adb_stat' the same as
320// 'struct stat'. Note that this definition of 'struct adb_stat' uses the
321// *current* macro definition of stat, so it may actually be inheriting from
322// struct _stat32i64 (or some other remapping).
323struct adb_stat : public stat {};
324
325static_assert(sizeof(struct adb_stat) == sizeof(struct stat),
326 "structures should be the same");
327
328extern int adb_stat(const char* f, struct adb_stat* s);
329
330// stat is already a macro, undefine it so we can redefine it.
331#undef stat
332#define stat adb_stat
333
334// UTF-8 versions of POSIX APIs.
335extern DIR* adb_opendir(const char* dirname);
336extern struct dirent* adb_readdir(DIR* dir);
337extern int adb_closedir(DIR* dir);
338
339extern int adb_utime(const char *, struct utimbuf *);
340extern int adb_chmod(const char *, int);
341
342extern int adb_vfprintf(FILE *stream, const char *format, va_list ap)
343 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 0)));
Spencer Lowa30b79a2015-11-15 16:29:36 -0800344extern int adb_vprintf(const char *format, va_list ap)
345 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -0700346extern int adb_fprintf(FILE *stream, const char *format, ...)
347 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3)));
348extern int adb_printf(const char *format, ...)
349 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
350
351extern int adb_fputs(const char* buf, FILE* stream);
352extern int adb_fputc(int ch, FILE* stream);
Spencer Lowa30b79a2015-11-15 16:29:36 -0800353extern int adb_putchar(int ch);
354extern int adb_puts(const char* buf);
Spencer Lowcf4ff642015-05-11 01:08:48 -0700355extern size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb,
356 FILE* stream);
357
358extern FILE* adb_fopen(const char* f, const char* m);
359
360extern char* adb_getenv(const char* name);
361
362extern char* adb_getcwd(char* buf, int size);
363
364// Remap calls to POSIX APIs to our UTF-8 versions.
365#define opendir adb_opendir
366#define readdir adb_readdir
367#define closedir adb_closedir
368#define rewinddir rewinddir_utf8_not_yet_implemented
369#define telldir telldir_utf8_not_yet_implemented
Spencer Low363af562015-11-07 18:51:54 -0800370// Some compiler's C++ headers have members named seekdir, so we can't do the
371// macro technique and instead cause a link error if seekdir is called.
372inline void seekdir(DIR*, long) {
373 extern int seekdir_utf8_not_yet_implemented;
374 seekdir_utf8_not_yet_implemented = 1;
375}
Spencer Lowcf4ff642015-05-11 01:08:48 -0700376
377#define utime adb_utime
378#define chmod adb_chmod
379
380#define vfprintf adb_vfprintf
Spencer Lowa30b79a2015-11-15 16:29:36 -0800381#define vprintf adb_vprintf
Spencer Lowcf4ff642015-05-11 01:08:48 -0700382#define fprintf adb_fprintf
383#define printf adb_printf
384#define fputs adb_fputs
385#define fputc adb_fputc
Spencer Lowa30b79a2015-11-15 16:29:36 -0800386// putc may be a macro, so if so, undefine it, so that we can redefine it.
387#undef putc
388#define putc(c, s) adb_fputc(c, s)
389#define putchar adb_putchar
390#define puts adb_puts
Spencer Lowcf4ff642015-05-11 01:08:48 -0700391#define fwrite adb_fwrite
392
393#define fopen adb_fopen
Spencer Lowa30b79a2015-11-15 16:29:36 -0800394#define freopen freopen_utf8_not_yet_implemented
Spencer Lowcf4ff642015-05-11 01:08:48 -0700395
396#define getenv adb_getenv
397#define putenv putenv_utf8_not_yet_implemented
398#define setenv setenv_utf8_not_yet_implemented
399#define unsetenv unsetenv_utf8_not_yet_implemented
400
401#define getcwd adb_getcwd
402
Spencer Low0a796002015-10-18 16:45:09 -0700403char* adb_strerror(int err);
404#define strerror adb_strerror
405
Spencer Lowcf4ff642015-05-11 01:08:48 -0700406// Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
407// passed to main().
408class NarrowArgs {
409public:
410 NarrowArgs(int argc, wchar_t** argv);
411 ~NarrowArgs();
412
413 inline char** data() {
414 return narrow_args;
415 }
416
417private:
418 char** narrow_args;
419};
420
Spencer Low5c398d22015-08-08 15:07:07 -0700421// Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
422// so they can fit in an int. To convert back, we just need to sign-extend.
423// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
424// Note that this does not make a HANDLE value work with APIs like open(), nor
425// does this make a value from open() passable to APIs taking a HANDLE. This
426// just lets you take a HANDLE, pass it around as an int, and then use it again
427// as a HANDLE.
428inline int cast_handle_to_int(const HANDLE h) {
429 // truncate
430 return static_cast<int>(reinterpret_cast<INT_PTR>(h));
431}
432
433inline HANDLE cast_int_to_handle(const int fd) {
434 // sign-extend
435 return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
436}
437
Spencer Low2122c7a2015-08-26 18:46:09 -0700438// Deleter for unique_handle. Adapted from many sources, including:
439// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
440// https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
441class handle_deleter {
442public:
443 typedef HANDLE pointer;
444
445 void operator()(HANDLE h);
446};
447
448// Like std::unique_ptr, but for Windows HANDLE objects that should be
449// CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
450// but does not check if the handle != INVALID_HANDLE_VALUE.
451typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
452
Spencer Lowa30b79a2015-11-15 16:29:36 -0800453namespace internal {
454
455size_t ParseCompleteUTF8(const char* first, const char* last, std::vector<char>* remaining_bytes);
456
457}
458
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800459#else /* !_WIN32 a.k.a. Unix */
460
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800461#include <cutils/misc.h>
Spencer Low5200c662015-07-30 23:07:55 -0700462#include <cutils/sockets.h>
Spencer Low8d8126a2015-07-21 02:06:26 -0700463#include <cutils/threads.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464#include <fcntl.h>
Josh Gao3777d2e2016-02-16 17:34:53 -0800465#include <poll.h>
466#include <signal.h>
467#include <sys/stat.h>
468#include <sys/wait.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800469
470#include <pthread.h>
471#include <unistd.h>
472#include <fcntl.h>
473#include <stdarg.h>
Spencer Low5200c662015-07-30 23:07:55 -0700474#include <netdb.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475#include <netinet/in.h>
476#include <netinet/tcp.h>
477#include <string.h>
Kenny Root73167412012-10-12 15:26:45 -0700478#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479
Alex Vallée47d67c92015-05-06 16:26:00 -0400480#include <string>
481
Elliott Hughes5c742702015-07-30 17:42:01 -0700482#define OS_PATH_SEPARATORS "/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800483#define OS_PATH_SEPARATOR '/'
484#define OS_PATH_SEPARATOR_STR "/"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700485#define ENV_PATH_SEPARATOR_STR ":"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800486
Josh Gao07db1192015-11-07 15:38:19 -0800487static __inline__ bool adb_is_separator(char c) {
488 return c == '/';
489}
490
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800491typedef pthread_mutex_t adb_mutex_t;
JP Abgrall408fa572011-03-16 15:57:42 -0700492
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800493#define ADB_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
494#define adb_mutex_init pthread_mutex_init
495#define adb_mutex_lock pthread_mutex_lock
496#define adb_mutex_unlock pthread_mutex_unlock
497#define adb_mutex_destroy pthread_mutex_destroy
498
JP Abgrall408fa572011-03-16 15:57:42 -0700499#define ADB_MUTEX_DEFINE(m) adb_mutex_t m = PTHREAD_MUTEX_INITIALIZER
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500
501#define adb_cond_t pthread_cond_t
502#define adb_cond_init pthread_cond_init
503#define adb_cond_wait pthread_cond_wait
504#define adb_cond_broadcast pthread_cond_broadcast
505#define adb_cond_signal pthread_cond_signal
506#define adb_cond_destroy pthread_cond_destroy
507
JP Abgrall408fa572011-03-16 15:57:42 -0700508/* declare all mutexes */
509#define ADB_MUTEX(x) extern adb_mutex_t x;
510#include "mutex_list.h"
511
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800512static __inline__ void close_on_exec(int fd)
513{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200514 fcntl( fd, F_SETFD, FD_CLOEXEC );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800515}
516
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700517// Open a file and return a file descriptor that may be used with unix_read(),
518// unix_write(), unix_close(), but not adb_read(), adb_write(), adb_close().
519//
520// On Unix, this is based on open(), so the file descriptor is a real OS file
521// descriptor, but the Windows implementation (in sysdeps_win32.cpp) returns a
522// file descriptor that can only be used with C Runtime APIs (which are wrapped
523// by unix_read(), unix_write(), unix_close()). Also, the C Runtime has
524// configurable CR/LF translation which defaults to text mode, but is settable
525// with _setmode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526static __inline__ int unix_open(const char* path, int options,...)
527{
528 if ((options & O_CREAT) == 0)
529 {
Kenny Root73167412012-10-12 15:26:45 -0700530 return TEMP_FAILURE_RETRY( open(path, options) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800531 }
532 else
533 {
534 int mode;
535 va_list args;
536 va_start( args, options );
537 mode = va_arg( args, int );
538 va_end( args );
Kenny Root73167412012-10-12 15:26:45 -0700539 return TEMP_FAILURE_RETRY( open( path, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800540 }
541}
542
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700543// Similar to the two-argument adb_open(), but takes a mode parameter for file
544// creation. See adb_open() for more info.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800545static __inline__ int adb_open_mode( const char* pathname, int options, int mode )
546{
Kenny Root73167412012-10-12 15:26:45 -0700547 return TEMP_FAILURE_RETRY( open( pathname, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800548}
549
550
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700551// Open a file and return a file descriptor that may be used with adb_read(),
552// adb_write(), adb_close(), but not unix_read(), unix_write(), unix_close().
553//
554// On Unix, this is based on open(), but the Windows implementation (in
555// sysdeps_win32.cpp) uses Windows native file I/O and bypasses the C Runtime
556// and its CR/LF translation. The returned file descriptor should be used with
557// adb_read(), adb_write(), adb_close(), etc.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800558static __inline__ int adb_open( const char* pathname, int options )
559{
Kenny Root73167412012-10-12 15:26:45 -0700560 int fd = TEMP_FAILURE_RETRY( open( pathname, options ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561 if (fd < 0)
562 return -1;
563 close_on_exec( fd );
564 return fd;
565}
566#undef open
567#define open ___xxx_open
568
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400569static __inline__ int adb_shutdown(int fd)
570{
571 return shutdown(fd, SHUT_RDWR);
572}
David Pursell1ed57f02015-10-06 15:30:03 -0700573static __inline__ int adb_shutdown(int fd, int direction)
574{
575 return shutdown(fd, direction);
576}
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400577#undef shutdown
578#define shutdown ____xxx_shutdown
579
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700580// Closes a file descriptor that came from adb_open() or adb_open_mode(), but
581// not designed to take a file descriptor from unix_open(). See the comments
582// for adb_open() for more info.
Josh Gaof0d3b4f2016-03-04 15:15:56 -0800583__inline__ int adb_close(int fd) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800584 return close(fd);
585}
586#undef close
587#define close ____xxx_close
588
589
590static __inline__ int adb_read(int fd, void* buf, size_t len)
591{
Kenny Root73167412012-10-12 15:26:45 -0700592 return TEMP_FAILURE_RETRY( read( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800593}
594
Spencer Low2e02dc62015-11-07 17:34:39 -0800595// Like unix_read(), but does not handle EINTR.
596static __inline__ int unix_read_interruptible(int fd, void* buf, size_t len) {
597 return read(fd, buf, len);
598}
599
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800600#undef read
601#define read ___xxx_read
602
603static __inline__ int adb_write(int fd, const void* buf, size_t len)
604{
Kenny Root73167412012-10-12 15:26:45 -0700605 return TEMP_FAILURE_RETRY( write( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800606}
607#undef write
608#define write ___xxx_write
609
610static __inline__ int adb_lseek(int fd, int pos, int where)
611{
612 return lseek(fd, pos, where);
613}
614#undef lseek
615#define lseek ___xxx_lseek
616
617static __inline__ int adb_unlink(const char* path)
618{
619 return unlink(path);
620}
621#undef unlink
622#define unlink ___xxx_unlink
623
624static __inline__ int adb_creat(const char* path, int mode)
625{
Kenny Root73167412012-10-12 15:26:45 -0700626 int fd = TEMP_FAILURE_RETRY( creat( path, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800627
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200628 if ( fd < 0 )
629 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800630
631 close_on_exec(fd);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200632 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800633}
634#undef creat
635#define creat ___xxx_creat
636
David Pursellc5b8ad82015-10-28 14:29:51 -0700637static __inline__ int unix_isatty(int fd) {
638 return isatty(fd);
639}
640#define isatty ___xxx_isatty
641
Spencer Low5200c662015-07-30 23:07:55 -0700642// Helper for network_* functions.
643inline int _fd_set_error_str(int fd, std::string* error) {
644 if (fd == -1) {
645 *error = strerror(errno);
646 }
647 return fd;
648}
649
650inline int network_loopback_client(int port, int type, std::string* error) {
651 return _fd_set_error_str(socket_loopback_client(port, type), error);
652}
653
654inline int network_loopback_server(int port, int type, std::string* error) {
655 return _fd_set_error_str(socket_loopback_server(port, type), error);
656}
657
658inline int network_inaddr_any_server(int port, int type, std::string* error) {
659 return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
660}
661
662inline int network_local_server(const char *name, int namespace_id, int type,
663 std::string* error) {
664 return _fd_set_error_str(socket_local_server(name, namespace_id, type),
665 error);
666}
667
668inline int network_connect(const std::string& host, int port, int type,
669 int timeout, std::string* error) {
670 int getaddrinfo_error = 0;
671 int fd = socket_network_client_timeout(host.c_str(), port, type, timeout,
672 &getaddrinfo_error);
673 if (fd != -1) {
674 return fd;
675 }
676 if (getaddrinfo_error != 0) {
677 *error = gai_strerror(getaddrinfo_error);
678 } else {
679 *error = strerror(errno);
680 }
681 return -1;
682}
683
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800684static __inline__ int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
685{
Benoit Goby95ef8282011-02-01 18:57:41 -0800686 int fd;
687
Kenny Root73167412012-10-12 15:26:45 -0700688 fd = TEMP_FAILURE_RETRY( accept( serverfd, addr, addrlen ) );
Benoit Goby95ef8282011-02-01 18:57:41 -0800689 if (fd >= 0)
690 close_on_exec(fd);
691
692 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800693}
694
695#undef accept
696#define accept ___xxx_accept
697
David Purselleaae97e2016-04-07 11:25:48 -0700698inline int adb_socket_get_local_port(int fd) {
699 return socket_get_local_port(fd);
700}
701
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700702// Operate on a file descriptor returned from unix_open() or a well-known file
703// descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
704//
705// On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
706// adb_write(), adb_close() (which all map to Unix system calls), but the
707// Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
708// into the C Runtime and its configurable CR/LF translation (which is settable
709// via _setmode()).
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800710#define unix_read adb_read
711#define unix_write adb_write
712#define unix_close adb_close
713
Josh Gaob5fea142016-02-12 14:31:15 -0800714// Win32 is limited to DWORDs for thread return values; limit the POSIX systems to this as well to
715// ensure compatibility.
716typedef void (*adb_thread_func_t)(void* arg);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800717typedef pthread_t adb_thread_t;
718
Josh Gaob5fea142016-02-12 14:31:15 -0800719struct adb_pthread_args {
720 adb_thread_func_t func;
721 void* arg;
722};
723
724static void* adb_pthread_wrapper(void* heap_args) {
725 // Move the arguments from the heap onto the thread's stack.
726 adb_pthread_args thread_args = *reinterpret_cast<adb_pthread_args*>(heap_args);
727 delete static_cast<adb_pthread_args*>(heap_args);
728 thread_args.func(thread_args.arg);
729 return nullptr;
730}
731
Josh Gao3b3e10d2016-02-09 14:59:09 -0800732static __inline__ bool adb_thread_create(adb_thread_func_t start, void* arg,
733 adb_thread_t* thread = nullptr) {
734 pthread_t temp;
Elliott Hughes9b0f3542015-05-05 13:41:21 -0700735 pthread_attr_t attr;
736 pthread_attr_init(&attr);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800737 pthread_attr_setdetachstate(&attr, thread ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
Josh Gaob5fea142016-02-12 14:31:15 -0800738 auto* pthread_args = new adb_pthread_args{.func = start, .arg = arg};
739 errno = pthread_create(&temp, &attr, adb_pthread_wrapper, pthread_args);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800740 if (errno == 0) {
741 if (thread) {
742 *thread = temp;
743 }
744 return true;
745 }
746 return false;
747}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800748
Josh Gao3b3e10d2016-02-09 14:59:09 -0800749static __inline__ bool adb_thread_join(adb_thread_t thread) {
750 errno = pthread_join(thread, nullptr);
751 return errno == 0;
752}
753
754static __inline__ bool adb_thread_detach(adb_thread_t thread) {
755 errno = pthread_detach(thread);
756 return errno == 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800757}
758
Josh Gaob5fea142016-02-12 14:31:15 -0800759static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
760 pthread_exit(nullptr);
761}
762
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700763static __inline__ int adb_thread_setname(const std::string& name) {
764#ifdef __APPLE__
765 return pthread_setname_np(name.c_str());
766#else
767 const char *s = name.c_str();
768
769 // pthread_setname_np fails rather than truncating long strings.
770 const int max_task_comm_len = 16; // including the null terminator
771 if (name.length() > (max_task_comm_len - 1)) {
772 char buf[max_task_comm_len];
773 strncpy(buf, name.c_str(), sizeof(buf) - 1);
774 buf[sizeof(buf) - 1] = '\0';
775 s = buf;
776 }
777
778 return pthread_setname_np(pthread_self(), s) ;
779#endif
780}
781
Spencer Lowf055c192015-01-25 14:40:16 -0800782static __inline__ int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
783{
784 return setsockopt( fd, level, optname, optval, optlen );
785}
786
787#undef setsockopt
788#define setsockopt ___xxx_setsockopt
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800789
790static __inline__ int unix_socketpair( int d, int type, int protocol, int sv[2] )
791{
792 return socketpair( d, type, protocol, sv );
793}
794
795static __inline__ int adb_socketpair( int sv[2] )
796{
797 int rc;
798
799 rc = unix_socketpair( AF_UNIX, SOCK_STREAM, 0, sv );
800 if (rc < 0)
801 return -1;
802
803 close_on_exec( sv[0] );
804 close_on_exec( sv[1] );
805 return 0;
806}
807
808#undef socketpair
809#define socketpair ___xxx_socketpair
810
Josh Gao3777d2e2016-02-16 17:34:53 -0800811typedef struct pollfd adb_pollfd;
812static __inline__ int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
813 return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
814}
815
816#define poll ___xxx_poll
817
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800818static __inline__ void adb_sleep_ms( int mseconds )
819{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200820 usleep( mseconds*1000 );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800821}
822
Alex Vallée47d67c92015-05-06 16:26:00 -0400823static __inline__ int adb_mkdir(const std::string& path, int mode)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800824{
Alex Vallée47d67c92015-05-06 16:26:00 -0400825 return mkdir(path.c_str(), mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800826}
Alex Vallée47d67c92015-05-06 16:26:00 -0400827
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828#undef mkdir
829#define mkdir ___xxx_mkdir
830
831static __inline__ void adb_sysdeps_init(void)
832{
833}
834
Alex Vallée47d67c92015-05-06 16:26:00 -0400835static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800836 return path[0] == '/';
837}
838
leozwangcbf02672014-08-15 09:51:27 -0700839static __inline__ unsigned long adb_thread_id()
840{
Spencer Low8d8126a2015-07-21 02:06:26 -0700841 return (unsigned long)gettid();
leozwangcbf02672014-08-15 09:51:27 -0700842}
843
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800844#endif /* !_WIN32 */
845
Elliott Hughescc65c3b2015-11-20 22:01:06 -0800846static inline void disable_tcp_nagle(int fd) {
847 int off = 1;
848 adb_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
849}
850
David Pursellbfd95032016-02-22 14:27:23 -0800851// Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
852// |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
853// configured to drop after 10 missed keepalives. Returns true on success.
854bool set_tcp_keepalive(int fd, int interval_sec);
855
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800856#endif /* _ADB_SYSDEPS_H */