blob: 81d201e6591cd3562607351469719f0ca33bbf22 [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
Spencer Lowd21dc822015-11-12 15:20:15 -080032// Include this before open/unlink are defined as macros below.
Josh Gaod302a152016-02-09 14:59:09 -080033#include <android-base/errors.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080034#include <android-base/utf8.h>
Spencer Lowd21dc822015-11-12 15:20:15 -080035
Dan Albertcc731cc2015-02-24 21:26:58 -080036/*
37 * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
38 * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
39 * not already defined, then define it here.
40 */
41#ifndef TEMP_FAILURE_RETRY
42/* Used to retry syscalls that can return EINTR. */
43#define TEMP_FAILURE_RETRY(exp) ({ \
44 typeof (exp) _rc; \
45 do { \
46 _rc = (exp); \
47 } while (_rc == -1 && errno == EINTR); \
48 _rc; })
49#endif
50
Spencer Lowcf4ff642015-05-11 01:08:48 -070051// Some printf-like functions are implemented in terms of
52// android::base::StringAppendV, so they should use the same attribute for
53// compile-time format string checking. On Windows, if the mingw version of
54// vsnprintf is used in StringAppendV, use `gnu_printf' which allows z in %zd
55// and PRIu64 (and related) to be recognized by the compile-time checking.
56#define ADB_FORMAT_ARCHETYPE __printf__
57#ifdef __USE_MINGW_ANSI_STDIO
58#if __USE_MINGW_ANSI_STDIO
59#undef ADB_FORMAT_ARCHETYPE
60#define ADB_FORMAT_ARCHETYPE gnu_printf
61#endif
62#endif
63
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080064#ifdef _WIN32
65
Josh Gaoa166e712016-01-29 12:08:34 -080066// Clang-only nullability specifiers
67#define _Nonnull
68#define _Nullable
69
Dan Albert630b9af2014-11-24 23:34:35 -080070#include <ctype.h>
71#include <direct.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070072#include <dirent.h>
Dan Albert630b9af2014-11-24 23:34:35 -080073#include <errno.h>
74#include <fcntl.h>
75#include <io.h>
76#include <process.h>
77#include <sys/stat.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070078#include <utime.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080079#include <winsock2.h>
Stephen Hines2f431a82014-10-01 17:37:06 -070080#include <windows.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080081#include <ws2tcpip.h>
Dan Albert630b9af2014-11-24 23:34:35 -080082
Spencer Low2122c7a2015-08-26 18:46:09 -070083#include <memory> // unique_ptr
Spencer Lowd21dc822015-11-12 15:20:15 -080084#include <string>
Alex Vallée47d67c92015-05-06 16:26:00 -040085
Dan Albert630b9af2014-11-24 23:34:35 -080086#include "fdevent.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080087
Elliott Hughes5c742702015-07-30 17:42:01 -070088#define OS_PATH_SEPARATORS "\\/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080089#define OS_PATH_SEPARATOR '\\'
90#define OS_PATH_SEPARATOR_STR "\\"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070091#define ENV_PATH_SEPARATOR_STR ";"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080092
Josh Gao07db1192015-11-07 15:38:19 -080093static __inline__ bool adb_is_separator(char c) {
94 return c == '\\' || c == '/';
95}
96
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080097typedef CRITICAL_SECTION adb_mutex_t;
98
99#define ADB_MUTEX_DEFINE(x) adb_mutex_t x
100
101/* declare all mutexes */
JP Abgrall408fa572011-03-16 15:57:42 -0700102/* For win32, adb_sysdeps_init() will do the mutex runtime initialization. */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800103#define ADB_MUTEX(x) extern adb_mutex_t x;
104#include "mutex_list.h"
105
106extern void adb_sysdeps_init(void);
107
108static __inline__ void adb_mutex_lock( adb_mutex_t* lock )
109{
110 EnterCriticalSection( lock );
111}
112
113static __inline__ void adb_mutex_unlock( adb_mutex_t* lock )
114{
115 LeaveCriticalSection( lock );
116}
117
Josh Gaod9db09c2016-02-12 14:31:15 -0800118typedef void (*adb_thread_func_t)(void* arg);
Josh Gaod302a152016-02-09 14:59:09 -0800119typedef HANDLE adb_thread_t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800120
Josh Gaod9db09c2016-02-12 14:31:15 -0800121struct adb_winthread_args {
Josh Gaod302a152016-02-09 14:59:09 -0800122 adb_thread_func_t func;
123 void* arg;
124};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800125
Josh Gaod9db09c2016-02-12 14:31:15 -0800126static unsigned __stdcall adb_winthread_wrapper(void* heap_args) {
127 // Move the arguments from the heap onto the thread's stack.
128 adb_winthread_args thread_args = *static_cast<adb_winthread_args*>(heap_args);
129 delete static_cast<adb_winthread_args*>(heap_args);
130 thread_args.func(thread_args.arg);
131 return 0;
Josh Gaod302a152016-02-09 14:59:09 -0800132}
133
134static __inline__ bool adb_thread_create(adb_thread_func_t func, void* arg,
135 adb_thread_t* thread = nullptr) {
Josh Gaod9db09c2016-02-12 14:31:15 -0800136 adb_winthread_args* args = new adb_winthread_args{.func = func, .arg = arg};
137 uintptr_t handle = _beginthreadex(nullptr, 0, adb_winthread_wrapper, args, 0, nullptr);
Josh Gaod302a152016-02-09 14:59:09 -0800138 if (handle != static_cast<uintptr_t>(0)) {
139 if (thread) {
140 *thread = reinterpret_cast<HANDLE>(handle);
141 } else {
142 CloseHandle(thread);
143 }
144 return true;
145 }
146 return false;
147}
148
149static __inline__ bool adb_thread_join(adb_thread_t thread) {
150 switch (WaitForSingleObject(thread, INFINITE)) {
151 case WAIT_OBJECT_0:
152 CloseHandle(thread);
153 return true;
154
155 case WAIT_FAILED:
156 fprintf(stderr, "adb_thread_join failed: %s\n",
157 android::base::SystemErrorCodeToString(GetLastError()).c_str());
158 break;
159
160 default:
161 abort();
162 }
163
164 return false;
165}
166
167static __inline__ bool adb_thread_detach(adb_thread_t thread) {
168 CloseHandle(thread);
169 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800170}
171
Josh Gaod9db09c2016-02-12 14:31:15 -0800172static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
Josh Gao2674cd922016-02-12 15:45:04 -0800173 _endthreadex(0);
Josh Gaod9db09c2016-02-12 14:31:15 -0800174}
175
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700176static __inline__ int adb_thread_setname(const std::string& name) {
177 // TODO: See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx for how to set
178 // the thread name in Windows. Unfortunately, it only works during debugging, but
179 // our build process doesn't generate PDB files needed for debugging.
180 return 0;
181}
182
Josh Gaoaddab3d2016-02-16 17:34:53 -0800183static __inline__ adb_thread_t adb_thread_self() {
184 return GetCurrentThread();
185}
186
187static __inline__ bool adb_thread_equal(adb_thread_t lhs, adb_thread_t rhs) {
188 return GetThreadId(lhs) == GetThreadId(rhs);
189}
190
leozwangcbf02672014-08-15 09:51:27 -0700191static __inline__ unsigned long adb_thread_id()
192{
193 return GetCurrentThreadId();
194}
195
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800196static __inline__ void close_on_exec(int fd)
197{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200198 /* nothing really */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800199}
200
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201#define lstat stat /* no symlinks on Win32 */
202
203#define S_ISLNK(m) 0 /* no symlinks on Win32 */
204
Spencer Lowcf4ff642015-05-11 01:08:48 -0700205extern int adb_unlink(const char* path);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800206#undef unlink
207#define unlink ___xxx_unlink
208
Spencer Lowcf4ff642015-05-11 01:08:48 -0700209extern int adb_mkdir(const std::string& path, int mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800210#undef mkdir
211#define mkdir ___xxx_mkdir
212
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700213// See the comments for the !defined(_WIN32) versions of adb_*().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800214extern int adb_open(const char* path, int options);
215extern int adb_creat(const char* path, int mode);
216extern int adb_read(int fd, void* buf, int len);
217extern int adb_write(int fd, const void* buf, int len);
218extern int adb_lseek(int fd, int pos, int where);
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400219extern int adb_shutdown(int fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800220extern int adb_close(int fd);
221
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700222// See the comments for the !defined(_WIN32) version of unix_close().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800223static __inline__ int unix_close(int fd)
224{
225 return close(fd);
226}
227#undef close
228#define close ____xxx_close
229
Spencer Low2e02dc62015-11-07 17:34:39 -0800230// Like unix_read(), but may return EINTR.
231extern int unix_read_interruptible(int fd, void* buf, size_t len);
232
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700233// See the comments for the !defined(_WIN32) version of unix_read().
Spencer Low2e02dc62015-11-07 17:34:39 -0800234static __inline__ int unix_read(int fd, void* buf, size_t len) {
235 return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
236}
Spencer Low50184062015-03-01 15:06:21 -0800237
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800238#undef read
239#define read ___xxx_read
240
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700241// See the comments for the !defined(_WIN32) version of unix_write().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242static __inline__ int unix_write(int fd, const void* buf, size_t len)
243{
244 return write(fd, buf, len);
245}
246#undef write
247#define write ___xxx_write
248
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700249// See the comments for the !defined(_WIN32) version of adb_open_mode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800250static __inline__ int adb_open_mode(const char* path, int options, int mode)
251{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200252 return adb_open(path, options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800253}
254
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700255// See the comments for the !defined(_WIN32) version of unix_open().
Spencer Lowcf4ff642015-05-11 01:08:48 -0700256extern int unix_open(const char* path, int options, ...);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800257#define open ___xxx_unix_open
258
David Pursellc5b8ad82015-10-28 14:29:51 -0700259// Checks if |fd| corresponds to a console.
260// Standard Windows isatty() returns 1 for both console FDs and character
261// devices like NUL. unix_isatty() performs some extra checking to only match
262// console FDs.
263// |fd| must be a real file descriptor, meaning STDxx_FILENO or unix_open() FDs
264// will work but adb_open() FDs will not. Additionally the OS handle associated
265// with |fd| must have GENERIC_READ access (which console FDs have by default).
266// Returns 1 if |fd| is a console FD, 0 otherwise. The value of errno after
267// calling this function is unreliable and should not be used.
268int unix_isatty(int fd);
269#define isatty ___xxx_isatty
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800270
271/* normally provided by <cutils/misc.h> */
272extern void* load_file(const char* pathname, unsigned* psize);
273
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800274static __inline__ void adb_sleep_ms( int mseconds )
275{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200276 Sleep( mseconds );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800277}
278
Spencer Low5200c662015-07-30 23:07:55 -0700279int network_loopback_client(int port, int type, std::string* error);
280int network_loopback_server(int port, int type, std::string* error);
281int network_inaddr_any_server(int port, int type, std::string* error);
282int network_connect(const std::string& host, int port, int type, int timeout,
283 std::string* error);
284
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800285extern int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen);
286
287#undef accept
288#define accept ___xxx_accept
289
Spencer Lowf055c192015-01-25 14:40:16 -0800290extern int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen);
291
292#undef setsockopt
293#define setsockopt ___xxx_setsockopt
294
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800295extern int adb_socketpair( int sv[2] );
296
Josh Gaoaddab3d2016-02-16 17:34:53 -0800297struct adb_pollfd {
298 int fd;
299 short events;
300 short revents;
301};
302extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout);
303#define poll ___xxx_poll
304
Elliott Hughes5c742702015-07-30 17:42:01 -0700305static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800306 return isalpha(path[0]) && path[1] == ':' && path[2] == '\\';
307}
308
Spencer Lowcf4ff642015-05-11 01:08:48 -0700309// We later define a macro mapping 'stat' to 'adb_stat'. This causes:
310// struct stat s;
311// stat(filename, &s);
312// To turn into the following:
313// struct adb_stat s;
314// adb_stat(filename, &s);
315// To get this to work, we need to make 'struct adb_stat' the same as
316// 'struct stat'. Note that this definition of 'struct adb_stat' uses the
317// *current* macro definition of stat, so it may actually be inheriting from
318// struct _stat32i64 (or some other remapping).
319struct adb_stat : public stat {};
320
321static_assert(sizeof(struct adb_stat) == sizeof(struct stat),
322 "structures should be the same");
323
324extern int adb_stat(const char* f, struct adb_stat* s);
325
326// stat is already a macro, undefine it so we can redefine it.
327#undef stat
328#define stat adb_stat
329
330// UTF-8 versions of POSIX APIs.
331extern DIR* adb_opendir(const char* dirname);
332extern struct dirent* adb_readdir(DIR* dir);
333extern int adb_closedir(DIR* dir);
334
335extern int adb_utime(const char *, struct utimbuf *);
336extern int adb_chmod(const char *, int);
337
338extern int adb_vfprintf(FILE *stream, const char *format, va_list ap)
339 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 0)));
Spencer Lowa30b79a2015-11-15 16:29:36 -0800340extern int adb_vprintf(const char *format, va_list ap)
341 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -0700342extern int adb_fprintf(FILE *stream, const char *format, ...)
343 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3)));
344extern int adb_printf(const char *format, ...)
345 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
346
347extern int adb_fputs(const char* buf, FILE* stream);
348extern int adb_fputc(int ch, FILE* stream);
Spencer Lowa30b79a2015-11-15 16:29:36 -0800349extern int adb_putchar(int ch);
350extern int adb_puts(const char* buf);
Spencer Lowcf4ff642015-05-11 01:08:48 -0700351extern size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb,
352 FILE* stream);
353
354extern FILE* adb_fopen(const char* f, const char* m);
355
356extern char* adb_getenv(const char* name);
357
358extern char* adb_getcwd(char* buf, int size);
359
360// Remap calls to POSIX APIs to our UTF-8 versions.
361#define opendir adb_opendir
362#define readdir adb_readdir
363#define closedir adb_closedir
364#define rewinddir rewinddir_utf8_not_yet_implemented
365#define telldir telldir_utf8_not_yet_implemented
Spencer Low363af562015-11-07 18:51:54 -0800366// Some compiler's C++ headers have members named seekdir, so we can't do the
367// macro technique and instead cause a link error if seekdir is called.
368inline void seekdir(DIR*, long) {
369 extern int seekdir_utf8_not_yet_implemented;
370 seekdir_utf8_not_yet_implemented = 1;
371}
Spencer Lowcf4ff642015-05-11 01:08:48 -0700372
373#define utime adb_utime
374#define chmod adb_chmod
375
376#define vfprintf adb_vfprintf
Spencer Lowa30b79a2015-11-15 16:29:36 -0800377#define vprintf adb_vprintf
Spencer Lowcf4ff642015-05-11 01:08:48 -0700378#define fprintf adb_fprintf
379#define printf adb_printf
380#define fputs adb_fputs
381#define fputc adb_fputc
Spencer Lowa30b79a2015-11-15 16:29:36 -0800382// putc may be a macro, so if so, undefine it, so that we can redefine it.
383#undef putc
384#define putc(c, s) adb_fputc(c, s)
385#define putchar adb_putchar
386#define puts adb_puts
Spencer Lowcf4ff642015-05-11 01:08:48 -0700387#define fwrite adb_fwrite
388
389#define fopen adb_fopen
Spencer Lowa30b79a2015-11-15 16:29:36 -0800390#define freopen freopen_utf8_not_yet_implemented
Spencer Lowcf4ff642015-05-11 01:08:48 -0700391
392#define getenv adb_getenv
393#define putenv putenv_utf8_not_yet_implemented
394#define setenv setenv_utf8_not_yet_implemented
395#define unsetenv unsetenv_utf8_not_yet_implemented
396
397#define getcwd adb_getcwd
398
Spencer Low0a796002015-10-18 16:45:09 -0700399char* adb_strerror(int err);
400#define strerror adb_strerror
401
Spencer Lowcf4ff642015-05-11 01:08:48 -0700402// Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
403// passed to main().
404class NarrowArgs {
405public:
406 NarrowArgs(int argc, wchar_t** argv);
407 ~NarrowArgs();
408
409 inline char** data() {
410 return narrow_args;
411 }
412
413private:
414 char** narrow_args;
415};
416
Spencer Low5c398d22015-08-08 15:07:07 -0700417// Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
418// so they can fit in an int. To convert back, we just need to sign-extend.
419// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
420// Note that this does not make a HANDLE value work with APIs like open(), nor
421// does this make a value from open() passable to APIs taking a HANDLE. This
422// just lets you take a HANDLE, pass it around as an int, and then use it again
423// as a HANDLE.
424inline int cast_handle_to_int(const HANDLE h) {
425 // truncate
426 return static_cast<int>(reinterpret_cast<INT_PTR>(h));
427}
428
429inline HANDLE cast_int_to_handle(const int fd) {
430 // sign-extend
431 return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
432}
433
Spencer Low2122c7a2015-08-26 18:46:09 -0700434// Deleter for unique_handle. Adapted from many sources, including:
435// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
436// https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
437class handle_deleter {
438public:
439 typedef HANDLE pointer;
440
441 void operator()(HANDLE h);
442};
443
444// Like std::unique_ptr, but for Windows HANDLE objects that should be
445// CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
446// but does not check if the handle != INVALID_HANDLE_VALUE.
447typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
448
Spencer Lowa30b79a2015-11-15 16:29:36 -0800449namespace internal {
450
451size_t ParseCompleteUTF8(const char* first, const char* last, std::vector<char>* remaining_bytes);
452
453}
454
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800455#else /* !_WIN32 a.k.a. Unix */
456
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800457#include <cutils/misc.h>
Spencer Low5200c662015-07-30 23:07:55 -0700458#include <cutils/sockets.h>
Spencer Low8d8126a2015-07-21 02:06:26 -0700459#include <cutils/threads.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800460#include <fcntl.h>
Josh Gaoaddab3d2016-02-16 17:34:53 -0800461#include <poll.h>
462#include <signal.h>
463#include <sys/stat.h>
464#include <sys/wait.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800465
466#include <pthread.h>
467#include <unistd.h>
468#include <fcntl.h>
469#include <stdarg.h>
Spencer Low5200c662015-07-30 23:07:55 -0700470#include <netdb.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800471#include <netinet/in.h>
472#include <netinet/tcp.h>
473#include <string.h>
Kenny Root73167412012-10-12 15:26:45 -0700474#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800475
Alex Vallée47d67c92015-05-06 16:26:00 -0400476#include <string>
477
Elliott Hughes5c742702015-07-30 17:42:01 -0700478#define OS_PATH_SEPARATORS "/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479#define OS_PATH_SEPARATOR '/'
480#define OS_PATH_SEPARATOR_STR "/"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700481#define ENV_PATH_SEPARATOR_STR ":"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800482
Josh Gao07db1192015-11-07 15:38:19 -0800483static __inline__ bool adb_is_separator(char c) {
484 return c == '/';
485}
486
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487typedef pthread_mutex_t adb_mutex_t;
JP Abgrall408fa572011-03-16 15:57:42 -0700488
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800489#define ADB_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
490#define adb_mutex_init pthread_mutex_init
491#define adb_mutex_lock pthread_mutex_lock
492#define adb_mutex_unlock pthread_mutex_unlock
493#define adb_mutex_destroy pthread_mutex_destroy
494
JP Abgrall408fa572011-03-16 15:57:42 -0700495#define ADB_MUTEX_DEFINE(m) adb_mutex_t m = PTHREAD_MUTEX_INITIALIZER
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800496
497#define adb_cond_t pthread_cond_t
498#define adb_cond_init pthread_cond_init
499#define adb_cond_wait pthread_cond_wait
500#define adb_cond_broadcast pthread_cond_broadcast
501#define adb_cond_signal pthread_cond_signal
502#define adb_cond_destroy pthread_cond_destroy
503
JP Abgrall408fa572011-03-16 15:57:42 -0700504/* declare all mutexes */
505#define ADB_MUTEX(x) extern adb_mutex_t x;
506#include "mutex_list.h"
507
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800508static __inline__ void close_on_exec(int fd)
509{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200510 fcntl( fd, F_SETFD, FD_CLOEXEC );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800511}
512
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700513// Open a file and return a file descriptor that may be used with unix_read(),
514// unix_write(), unix_close(), but not adb_read(), adb_write(), adb_close().
515//
516// On Unix, this is based on open(), so the file descriptor is a real OS file
517// descriptor, but the Windows implementation (in sysdeps_win32.cpp) returns a
518// file descriptor that can only be used with C Runtime APIs (which are wrapped
519// by unix_read(), unix_write(), unix_close()). Also, the C Runtime has
520// configurable CR/LF translation which defaults to text mode, but is settable
521// with _setmode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800522static __inline__ int unix_open(const char* path, int options,...)
523{
524 if ((options & O_CREAT) == 0)
525 {
Kenny Root73167412012-10-12 15:26:45 -0700526 return TEMP_FAILURE_RETRY( open(path, options) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800527 }
528 else
529 {
530 int mode;
531 va_list args;
532 va_start( args, options );
533 mode = va_arg( args, int );
534 va_end( args );
Kenny Root73167412012-10-12 15:26:45 -0700535 return TEMP_FAILURE_RETRY( open( path, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800536 }
537}
538
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700539// Similar to the two-argument adb_open(), but takes a mode parameter for file
540// creation. See adb_open() for more info.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800541static __inline__ int adb_open_mode( const char* pathname, int options, int mode )
542{
Kenny Root73167412012-10-12 15:26:45 -0700543 return TEMP_FAILURE_RETRY( open( pathname, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800544}
545
546
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700547// Open a file and return a file descriptor that may be used with adb_read(),
548// adb_write(), adb_close(), but not unix_read(), unix_write(), unix_close().
549//
550// On Unix, this is based on open(), but the Windows implementation (in
551// sysdeps_win32.cpp) uses Windows native file I/O and bypasses the C Runtime
552// and its CR/LF translation. The returned file descriptor should be used with
553// adb_read(), adb_write(), adb_close(), etc.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800554static __inline__ int adb_open( const char* pathname, int options )
555{
Kenny Root73167412012-10-12 15:26:45 -0700556 int fd = TEMP_FAILURE_RETRY( open( pathname, options ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800557 if (fd < 0)
558 return -1;
559 close_on_exec( fd );
560 return fd;
561}
562#undef open
563#define open ___xxx_open
564
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400565static __inline__ int adb_shutdown(int fd)
566{
567 return shutdown(fd, SHUT_RDWR);
568}
David Pursell1ed57f02015-10-06 15:30:03 -0700569static __inline__ int adb_shutdown(int fd, int direction)
570{
571 return shutdown(fd, direction);
572}
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400573#undef shutdown
574#define shutdown ____xxx_shutdown
575
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700576// Closes a file descriptor that came from adb_open() or adb_open_mode(), but
577// not designed to take a file descriptor from unix_open(). See the comments
578// for adb_open() for more info.
Josh Gaoa9eb38d2016-03-04 15:15:56 -0800579__inline__ int adb_close(int fd) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800580 return close(fd);
581}
582#undef close
583#define close ____xxx_close
584
585
586static __inline__ int adb_read(int fd, void* buf, size_t len)
587{
Kenny Root73167412012-10-12 15:26:45 -0700588 return TEMP_FAILURE_RETRY( read( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800589}
590
Spencer Low2e02dc62015-11-07 17:34:39 -0800591// Like unix_read(), but does not handle EINTR.
592static __inline__ int unix_read_interruptible(int fd, void* buf, size_t len) {
593 return read(fd, buf, len);
594}
595
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800596#undef read
597#define read ___xxx_read
598
599static __inline__ int adb_write(int fd, const void* buf, size_t len)
600{
Kenny Root73167412012-10-12 15:26:45 -0700601 return TEMP_FAILURE_RETRY( write( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602}
603#undef write
604#define write ___xxx_write
605
606static __inline__ int adb_lseek(int fd, int pos, int where)
607{
608 return lseek(fd, pos, where);
609}
610#undef lseek
611#define lseek ___xxx_lseek
612
613static __inline__ int adb_unlink(const char* path)
614{
615 return unlink(path);
616}
617#undef unlink
618#define unlink ___xxx_unlink
619
620static __inline__ int adb_creat(const char* path, int mode)
621{
Kenny Root73167412012-10-12 15:26:45 -0700622 int fd = TEMP_FAILURE_RETRY( creat( path, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800623
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200624 if ( fd < 0 )
625 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800626
627 close_on_exec(fd);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200628 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800629}
630#undef creat
631#define creat ___xxx_creat
632
David Pursellc5b8ad82015-10-28 14:29:51 -0700633static __inline__ int unix_isatty(int fd) {
634 return isatty(fd);
635}
636#define isatty ___xxx_isatty
637
Spencer Low5200c662015-07-30 23:07:55 -0700638// Helper for network_* functions.
639inline int _fd_set_error_str(int fd, std::string* error) {
640 if (fd == -1) {
641 *error = strerror(errno);
642 }
643 return fd;
644}
645
646inline int network_loopback_client(int port, int type, std::string* error) {
647 return _fd_set_error_str(socket_loopback_client(port, type), error);
648}
649
650inline int network_loopback_server(int port, int type, std::string* error) {
651 return _fd_set_error_str(socket_loopback_server(port, type), error);
652}
653
654inline int network_inaddr_any_server(int port, int type, std::string* error) {
655 return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
656}
657
658inline int network_local_server(const char *name, int namespace_id, int type,
659 std::string* error) {
660 return _fd_set_error_str(socket_local_server(name, namespace_id, type),
661 error);
662}
663
664inline int network_connect(const std::string& host, int port, int type,
665 int timeout, std::string* error) {
666 int getaddrinfo_error = 0;
667 int fd = socket_network_client_timeout(host.c_str(), port, type, timeout,
668 &getaddrinfo_error);
669 if (fd != -1) {
670 return fd;
671 }
672 if (getaddrinfo_error != 0) {
673 *error = gai_strerror(getaddrinfo_error);
674 } else {
675 *error = strerror(errno);
676 }
677 return -1;
678}
679
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800680static __inline__ int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
681{
Benoit Goby95ef8282011-02-01 18:57:41 -0800682 int fd;
683
Kenny Root73167412012-10-12 15:26:45 -0700684 fd = TEMP_FAILURE_RETRY( accept( serverfd, addr, addrlen ) );
Benoit Goby95ef8282011-02-01 18:57:41 -0800685 if (fd >= 0)
686 close_on_exec(fd);
687
688 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800689}
690
691#undef accept
692#define accept ___xxx_accept
693
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700694// Operate on a file descriptor returned from unix_open() or a well-known file
695// descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
696//
697// On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
698// adb_write(), adb_close() (which all map to Unix system calls), but the
699// Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
700// into the C Runtime and its configurable CR/LF translation (which is settable
701// via _setmode()).
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800702#define unix_read adb_read
703#define unix_write adb_write
704#define unix_close adb_close
705
Josh Gaod9db09c2016-02-12 14:31:15 -0800706// Win32 is limited to DWORDs for thread return values; limit the POSIX systems to this as well to
707// ensure compatibility.
708typedef void (*adb_thread_func_t)(void* arg);
Josh Gaod302a152016-02-09 14:59:09 -0800709typedef pthread_t adb_thread_t;
710
Josh Gaod9db09c2016-02-12 14:31:15 -0800711struct adb_pthread_args {
712 adb_thread_func_t func;
713 void* arg;
714};
715
716static void* adb_pthread_wrapper(void* heap_args) {
717 // Move the arguments from the heap onto the thread's stack.
718 adb_pthread_args thread_args = *reinterpret_cast<adb_pthread_args*>(heap_args);
719 delete static_cast<adb_pthread_args*>(heap_args);
720 thread_args.func(thread_args.arg);
721 return nullptr;
722}
723
Josh Gaod302a152016-02-09 14:59:09 -0800724static __inline__ bool adb_thread_create(adb_thread_func_t start, void* arg,
725 adb_thread_t* thread = nullptr) {
726 pthread_t temp;
Elliott Hughes9b0f3542015-05-05 13:41:21 -0700727 pthread_attr_t attr;
728 pthread_attr_init(&attr);
Josh Gaod302a152016-02-09 14:59:09 -0800729 pthread_attr_setdetachstate(&attr, thread ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
Josh Gaod9db09c2016-02-12 14:31:15 -0800730 auto* pthread_args = new adb_pthread_args{.func = start, .arg = arg};
731 errno = pthread_create(&temp, &attr, adb_pthread_wrapper, pthread_args);
Josh Gaod302a152016-02-09 14:59:09 -0800732 if (errno == 0) {
733 if (thread) {
734 *thread = temp;
735 }
736 return true;
737 }
738 return false;
739}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800740
Josh Gaod302a152016-02-09 14:59:09 -0800741static __inline__ bool adb_thread_join(adb_thread_t thread) {
742 errno = pthread_join(thread, nullptr);
743 return errno == 0;
744}
745
746static __inline__ bool adb_thread_detach(adb_thread_t thread) {
747 errno = pthread_detach(thread);
748 return errno == 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800749}
750
Josh Gaod9db09c2016-02-12 14:31:15 -0800751static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
752 pthread_exit(nullptr);
753}
754
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700755static __inline__ int adb_thread_setname(const std::string& name) {
756#ifdef __APPLE__
757 return pthread_setname_np(name.c_str());
758#else
759 const char *s = name.c_str();
760
761 // pthread_setname_np fails rather than truncating long strings.
762 const int max_task_comm_len = 16; // including the null terminator
763 if (name.length() > (max_task_comm_len - 1)) {
764 char buf[max_task_comm_len];
765 strncpy(buf, name.c_str(), sizeof(buf) - 1);
766 buf[sizeof(buf) - 1] = '\0';
767 s = buf;
768 }
769
770 return pthread_setname_np(pthread_self(), s) ;
771#endif
772}
773
Spencer Lowf055c192015-01-25 14:40:16 -0800774static __inline__ int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
775{
776 return setsockopt( fd, level, optname, optval, optlen );
777}
778
779#undef setsockopt
780#define setsockopt ___xxx_setsockopt
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800781
782static __inline__ int unix_socketpair( int d, int type, int protocol, int sv[2] )
783{
784 return socketpair( d, type, protocol, sv );
785}
786
787static __inline__ int adb_socketpair( int sv[2] )
788{
789 int rc;
790
791 rc = unix_socketpair( AF_UNIX, SOCK_STREAM, 0, sv );
792 if (rc < 0)
793 return -1;
794
795 close_on_exec( sv[0] );
796 close_on_exec( sv[1] );
797 return 0;
798}
799
800#undef socketpair
801#define socketpair ___xxx_socketpair
802
Josh Gaoaddab3d2016-02-16 17:34:53 -0800803typedef struct pollfd adb_pollfd;
804static __inline__ int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
805 return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
806}
807
808#define poll ___xxx_poll
809
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800810static __inline__ void adb_sleep_ms( int mseconds )
811{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200812 usleep( mseconds*1000 );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800813}
814
Alex Vallée47d67c92015-05-06 16:26:00 -0400815static __inline__ int adb_mkdir(const std::string& path, int mode)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800816{
Alex Vallée47d67c92015-05-06 16:26:00 -0400817 return mkdir(path.c_str(), mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800818}
Alex Vallée47d67c92015-05-06 16:26:00 -0400819
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800820#undef mkdir
821#define mkdir ___xxx_mkdir
822
823static __inline__ void adb_sysdeps_init(void)
824{
825}
826
Alex Vallée47d67c92015-05-06 16:26:00 -0400827static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800828 return path[0] == '/';
829}
830
leozwangcbf02672014-08-15 09:51:27 -0700831static __inline__ unsigned long adb_thread_id()
832{
Spencer Low8d8126a2015-07-21 02:06:26 -0700833 return (unsigned long)gettid();
leozwangcbf02672014-08-15 09:51:27 -0700834}
835
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800836#endif /* !_WIN32 */
837
Elliott Hughescc65c3b2015-11-20 22:01:06 -0800838static inline void disable_tcp_nagle(int fd) {
839 int off = 1;
840 adb_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
841}
842
David Pursella76e5f02016-02-22 14:27:23 -0800843// Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
844// |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
845// configured to drop after 10 missed keepalives. Returns true on success.
846bool set_tcp_keepalive(int fd, int interval_sec);
847
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800848#endif /* _ADB_SYSDEPS_H */