blob: f195b4eb496234befee9c349ecb6b3385a3c5bf2 [file] [log] [blame]
The Android Open Source Project9ca14dc2009-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 Hughes43df1092015-07-23 17:12:58 -070027#include <errno.h>
28
Spencer Low753d4852015-07-30 23:07:55 -070029#include <string>
Spencer Lowf373c352015-11-15 16:29:36 -080030#include <vector>
Spencer Low753d4852015-07-30 23:07:55 -070031
Josh Gaod91139c2016-05-13 14:52:06 -070032// Include this before open/close/unlink are defined as macros below.
Josh Gaoa4f5e032016-02-09 14:59:09 -080033#include <android-base/errors.h>
Josh Gaod91139c2016-05-13 14:52:06 -070034#include <android-base/unique_fd.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080035#include <android-base/utf8.h>
Spencer Low50f5bf12015-11-12 15:20:15 -080036
Josh Gao75e96bb2016-12-05 13:24:48 -080037#include "sysdeps/errno.h"
Josh Gaoa4f9c172016-07-28 18:09:48 -070038#include "sysdeps/stat.h"
39
Dan Albert66a91b02015-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 Low6815c072015-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 Project9ca14dc2009-03-03 19:32:55 -080068#ifdef _WIN32
69
Josh Gao23f6f2b2016-01-29 12:08:34 -080070// Clang-only nullability specifiers
71#define _Nonnull
72#define _Nullable
73
Dan Albertbbbbea62014-11-24 23:34:35 -080074#include <ctype.h>
75#include <direct.h>
Spencer Low6815c072015-05-11 01:08:48 -070076#include <dirent.h>
Dan Albertbbbbea62014-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 Low6815c072015-05-11 01:08:48 -070082#include <utime.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080083#include <winsock2.h>
Stephen Hinesb1170852014-10-01 17:37:06 -070084#include <windows.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080085#include <ws2tcpip.h>
Dan Albertbbbbea62014-11-24 23:34:35 -080086
Spencer Low2bbb3a92015-08-26 18:46:09 -070087#include <memory> // unique_ptr
Spencer Low50f5bf12015-11-12 15:20:15 -080088#include <string>
Alex Vallée28d1f8d2015-05-06 16:26:00 -040089
Dan Albertbbbbea62014-11-24 23:34:35 -080090#include "fdevent.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080091
Elliott Hughesd189cfb2015-07-30 17:42:01 -070092#define OS_PATH_SEPARATORS "\\/"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080093#define OS_PATH_SEPARATOR '\\'
94#define OS_PATH_SEPARATOR_STR "\\"
Benoit Goby2cc19e42012-04-12 12:23:49 -070095#define ENV_PATH_SEPARATOR_STR ";"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080096
Josh Gao8acf06c2015-11-07 15:38:19 -080097static __inline__ bool adb_is_separator(char c) {
98 return c == '\\' || c == '/';
99}
100
Josh Gao7d405252016-02-12 14:31:15 -0800101typedef void (*adb_thread_func_t)(void* arg);
Josh Gaoa4f5e032016-02-09 14:59:09 -0800102typedef HANDLE adb_thread_t;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800103
Josh Gao7d405252016-02-12 14:31:15 -0800104struct adb_winthread_args {
Josh Gaoa4f5e032016-02-09 14:59:09 -0800105 adb_thread_func_t func;
106 void* arg;
107};
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800108
Josh Gao7d405252016-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 Gaoa4f5e032016-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 Gao7d405252016-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 Gaoa4f5e032016-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 Project9ca14dc2009-03-03 19:32:55 -0800153}
154
Josh Gao7d405252016-02-12 14:31:15 -0800155static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
Josh Gao50493b22016-02-12 15:45:04 -0800156 _endthreadex(0);
Josh Gao7d405252016-02-12 14:31:15 -0800157}
158
Siva Velusamy2669cf92015-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 Gaoe7388122016-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
leozwang1be54622014-08-15 09:51:27 -0700174static __inline__ unsigned long adb_thread_id()
175{
176 return GetCurrentThreadId();
177}
178
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800179static __inline__ void close_on_exec(int fd)
180{
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200181 /* nothing really */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800182}
183
Spencer Low6815c072015-05-11 01:08:48 -0700184extern int adb_unlink(const char* path);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800185#undef unlink
186#define unlink ___xxx_unlink
187
Spencer Low6815c072015-05-11 01:08:48 -0700188extern int adb_mkdir(const std::string& path, int mode);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800189#undef mkdir
190#define mkdir ___xxx_mkdir
191
Spencer Low3a2421b2015-05-22 20:09:06 -0700192// See the comments for the !defined(_WIN32) versions of adb_*().
The Android Open Source Project9ca14dc2009-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 Lockwood81ffe172009-10-11 23:04:18 -0400198extern int adb_shutdown(int fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800199extern int adb_close(int fd);
Casey Dahlin20238f22016-09-21 14:03:39 -0700200extern int adb_register_socket(SOCKET s);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800201
Spencer Low3a2421b2015-05-22 20:09:06 -0700202// See the comments for the !defined(_WIN32) version of unix_close().
The Android Open Source Project9ca14dc2009-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 Low55441402015-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 Low3a2421b2015-05-22 20:09:06 -0700213// See the comments for the !defined(_WIN32) version of unix_read().
Spencer Low55441402015-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 Lowbeb61982015-03-01 15:06:21 -0800217
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800218#undef read
219#define read ___xxx_read
220
Spencer Low3a2421b2015-05-22 20:09:06 -0700221// See the comments for the !defined(_WIN32) version of unix_write().
The Android Open Source Project9ca14dc2009-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 Low3a2421b2015-05-22 20:09:06 -0700229// See the comments for the !defined(_WIN32) version of adb_open_mode().
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800230static __inline__ int adb_open_mode(const char* path, int options, int mode)
231{
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200232 return adb_open(path, options);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800233}
234
Spencer Low3a2421b2015-05-22 20:09:06 -0700235// See the comments for the !defined(_WIN32) version of unix_open().
Spencer Low6815c072015-05-11 01:08:48 -0700236extern int unix_open(const char* path, int options, ...);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800237#define open ___xxx_unix_open
238
David Pursell58805362015-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 Project9ca14dc2009-03-03 19:32:55 -0800250
Spencer Low753d4852015-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 Gao4a5a95d2016-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 Low753d4852015-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 Project9ca14dc2009-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
Josh Gaod6001b52016-08-23 15:28:43 -0700271int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen);
272#undef getsockname
273#define getsockname(...) ___xxx_getsockname(__VA__ARGS__)
274
David Pursell19d0c232016-04-07 11:25:48 -0700275// Returns the local port number of a bound socket, or -1 on failure.
276int adb_socket_get_local_port(int fd);
277
Spencer Low31aafa62015-01-25 14:40:16 -0800278extern int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen);
279
280#undef setsockopt
281#define setsockopt ___xxx_setsockopt
282
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800283extern int adb_socketpair( int sv[2] );
284
Josh Gaoe7388122016-02-16 17:34:53 -0800285struct adb_pollfd {
286 int fd;
287 short events;
288 short revents;
289};
290extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout);
291#define poll ___xxx_poll
292
Elliott Hughesd189cfb2015-07-30 17:42:01 -0700293static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800294 return isalpha(path[0]) && path[1] == ':' && path[2] == '\\';
295}
296
Spencer Low6815c072015-05-11 01:08:48 -0700297// UTF-8 versions of POSIX APIs.
298extern DIR* adb_opendir(const char* dirname);
299extern struct dirent* adb_readdir(DIR* dir);
300extern int adb_closedir(DIR* dir);
301
302extern int adb_utime(const char *, struct utimbuf *);
303extern int adb_chmod(const char *, int);
304
305extern int adb_vfprintf(FILE *stream, const char *format, va_list ap)
306 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 0)));
Spencer Lowf373c352015-11-15 16:29:36 -0800307extern int adb_vprintf(const char *format, va_list ap)
308 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 0)));
Spencer Low6815c072015-05-11 01:08:48 -0700309extern int adb_fprintf(FILE *stream, const char *format, ...)
310 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3)));
311extern int adb_printf(const char *format, ...)
312 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
313
314extern int adb_fputs(const char* buf, FILE* stream);
315extern int adb_fputc(int ch, FILE* stream);
Spencer Lowf373c352015-11-15 16:29:36 -0800316extern int adb_putchar(int ch);
317extern int adb_puts(const char* buf);
Spencer Low6815c072015-05-11 01:08:48 -0700318extern size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb,
319 FILE* stream);
320
321extern FILE* adb_fopen(const char* f, const char* m);
322
323extern char* adb_getenv(const char* name);
324
325extern char* adb_getcwd(char* buf, int size);
326
327// Remap calls to POSIX APIs to our UTF-8 versions.
328#define opendir adb_opendir
329#define readdir adb_readdir
330#define closedir adb_closedir
331#define rewinddir rewinddir_utf8_not_yet_implemented
332#define telldir telldir_utf8_not_yet_implemented
Spencer Low28bc2cb2015-11-07 18:51:54 -0800333// Some compiler's C++ headers have members named seekdir, so we can't do the
334// macro technique and instead cause a link error if seekdir is called.
335inline void seekdir(DIR*, long) {
336 extern int seekdir_utf8_not_yet_implemented;
337 seekdir_utf8_not_yet_implemented = 1;
338}
Spencer Low6815c072015-05-11 01:08:48 -0700339
340#define utime adb_utime
341#define chmod adb_chmod
342
343#define vfprintf adb_vfprintf
Spencer Lowf373c352015-11-15 16:29:36 -0800344#define vprintf adb_vprintf
Spencer Low6815c072015-05-11 01:08:48 -0700345#define fprintf adb_fprintf
346#define printf adb_printf
347#define fputs adb_fputs
348#define fputc adb_fputc
Spencer Lowf373c352015-11-15 16:29:36 -0800349// putc may be a macro, so if so, undefine it, so that we can redefine it.
350#undef putc
351#define putc(c, s) adb_fputc(c, s)
352#define putchar adb_putchar
353#define puts adb_puts
Spencer Low6815c072015-05-11 01:08:48 -0700354#define fwrite adb_fwrite
355
356#define fopen adb_fopen
Spencer Lowf373c352015-11-15 16:29:36 -0800357#define freopen freopen_utf8_not_yet_implemented
Spencer Low6815c072015-05-11 01:08:48 -0700358
359#define getenv adb_getenv
360#define putenv putenv_utf8_not_yet_implemented
361#define setenv setenv_utf8_not_yet_implemented
362#define unsetenv unsetenv_utf8_not_yet_implemented
363
364#define getcwd adb_getcwd
365
Spencer Low6815c072015-05-11 01:08:48 -0700366// Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
367// passed to main().
368class NarrowArgs {
369public:
370 NarrowArgs(int argc, wchar_t** argv);
371 ~NarrowArgs();
372
373 inline char** data() {
374 return narrow_args;
375 }
376
377private:
378 char** narrow_args;
379};
380
Spencer Lowb28812f2015-08-08 15:07:07 -0700381// Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
382// so they can fit in an int. To convert back, we just need to sign-extend.
383// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
384// Note that this does not make a HANDLE value work with APIs like open(), nor
385// does this make a value from open() passable to APIs taking a HANDLE. This
386// just lets you take a HANDLE, pass it around as an int, and then use it again
387// as a HANDLE.
388inline int cast_handle_to_int(const HANDLE h) {
389 // truncate
390 return static_cast<int>(reinterpret_cast<INT_PTR>(h));
391}
392
393inline HANDLE cast_int_to_handle(const int fd) {
394 // sign-extend
395 return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
396}
397
Spencer Low2bbb3a92015-08-26 18:46:09 -0700398// Deleter for unique_handle. Adapted from many sources, including:
399// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
400// https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
401class handle_deleter {
402public:
403 typedef HANDLE pointer;
404
405 void operator()(HANDLE h);
406};
407
408// Like std::unique_ptr, but for Windows HANDLE objects that should be
409// CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
410// but does not check if the handle != INVALID_HANDLE_VALUE.
411typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
412
Spencer Lowf373c352015-11-15 16:29:36 -0800413namespace internal {
414
415size_t ParseCompleteUTF8(const char* first, const char* last, std::vector<char>* remaining_bytes);
416
417}
418
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800419#else /* !_WIN32 a.k.a. Unix */
420
Spencer Low753d4852015-07-30 23:07:55 -0700421#include <cutils/sockets.h>
Spencer Low5c761bd2015-07-21 02:06:26 -0700422#include <cutils/threads.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800423#include <fcntl.h>
Josh Gaoe7388122016-02-16 17:34:53 -0800424#include <poll.h>
425#include <signal.h>
426#include <sys/stat.h>
427#include <sys/wait.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800428
429#include <pthread.h>
430#include <unistd.h>
431#include <fcntl.h>
432#include <stdarg.h>
Spencer Low753d4852015-07-30 23:07:55 -0700433#include <netdb.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800434#include <netinet/in.h>
435#include <netinet/tcp.h>
436#include <string.h>
Kenny Rooteac025c2012-10-12 15:26:45 -0700437#include <unistd.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800438
Alex Vallée28d1f8d2015-05-06 16:26:00 -0400439#include <string>
440
Elliott Hughesd189cfb2015-07-30 17:42:01 -0700441#define OS_PATH_SEPARATORS "/"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800442#define OS_PATH_SEPARATOR '/'
443#define OS_PATH_SEPARATOR_STR "/"
Benoit Goby2cc19e42012-04-12 12:23:49 -0700444#define ENV_PATH_SEPARATOR_STR ":"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800445
Josh Gao8acf06c2015-11-07 15:38:19 -0800446static __inline__ bool adb_is_separator(char c) {
447 return c == '/';
448}
449
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800450static __inline__ void close_on_exec(int fd)
451{
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200452 fcntl( fd, F_SETFD, FD_CLOEXEC );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800453}
454
Spencer Low3a2421b2015-05-22 20:09:06 -0700455// Open a file and return a file descriptor that may be used with unix_read(),
456// unix_write(), unix_close(), but not adb_read(), adb_write(), adb_close().
457//
458// On Unix, this is based on open(), so the file descriptor is a real OS file
459// descriptor, but the Windows implementation (in sysdeps_win32.cpp) returns a
460// file descriptor that can only be used with C Runtime APIs (which are wrapped
461// by unix_read(), unix_write(), unix_close()). Also, the C Runtime has
462// configurable CR/LF translation which defaults to text mode, but is settable
463// with _setmode().
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800464static __inline__ int unix_open(const char* path, int options,...)
465{
466 if ((options & O_CREAT) == 0)
467 {
Kenny Rooteac025c2012-10-12 15:26:45 -0700468 return TEMP_FAILURE_RETRY( open(path, options) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800469 }
470 else
471 {
472 int mode;
473 va_list args;
474 va_start( args, options );
475 mode = va_arg( args, int );
476 va_end( args );
Kenny Rooteac025c2012-10-12 15:26:45 -0700477 return TEMP_FAILURE_RETRY( open( path, options, mode ) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800478 }
479}
480
Spencer Low3a2421b2015-05-22 20:09:06 -0700481// Similar to the two-argument adb_open(), but takes a mode parameter for file
482// creation. See adb_open() for more info.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483static __inline__ int adb_open_mode( const char* pathname, int options, int mode )
484{
Kenny Rooteac025c2012-10-12 15:26:45 -0700485 return TEMP_FAILURE_RETRY( open( pathname, options, mode ) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800486}
487
488
Spencer Low3a2421b2015-05-22 20:09:06 -0700489// Open a file and return a file descriptor that may be used with adb_read(),
490// adb_write(), adb_close(), but not unix_read(), unix_write(), unix_close().
491//
492// On Unix, this is based on open(), but the Windows implementation (in
493// sysdeps_win32.cpp) uses Windows native file I/O and bypasses the C Runtime
494// and its CR/LF translation. The returned file descriptor should be used with
495// adb_read(), adb_write(), adb_close(), etc.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800496static __inline__ int adb_open( const char* pathname, int options )
497{
Kenny Rooteac025c2012-10-12 15:26:45 -0700498 int fd = TEMP_FAILURE_RETRY( open( pathname, options ) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800499 if (fd < 0)
500 return -1;
501 close_on_exec( fd );
502 return fd;
503}
504#undef open
505#define open ___xxx_open
506
Mike Lockwood81ffe172009-10-11 23:04:18 -0400507static __inline__ int adb_shutdown(int fd)
508{
509 return shutdown(fd, SHUT_RDWR);
510}
David Pursell3fe11f62015-10-06 15:30:03 -0700511static __inline__ int adb_shutdown(int fd, int direction)
512{
513 return shutdown(fd, direction);
514}
Mike Lockwood81ffe172009-10-11 23:04:18 -0400515#undef shutdown
516#define shutdown ____xxx_shutdown
517
Spencer Low3a2421b2015-05-22 20:09:06 -0700518// Closes a file descriptor that came from adb_open() or adb_open_mode(), but
519// not designed to take a file descriptor from unix_open(). See the comments
520// for adb_open() for more info.
Josh Gao1b533c82016-03-04 15:15:56 -0800521__inline__ int adb_close(int fd) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800522 return close(fd);
523}
524#undef close
525#define close ____xxx_close
526
Casey Dahlin20238f22016-09-21 14:03:39 -0700527// On Windows, ADB has an indirection layer for file descriptors. If we get a
528// Win32 SOCKET object from an external library, we have to map it in to that
529// indirection layer, which this does.
530__inline__ int adb_register_socket(int s) {
531 return s;
532}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800533
534static __inline__ int adb_read(int fd, void* buf, size_t len)
535{
Kenny Rooteac025c2012-10-12 15:26:45 -0700536 return TEMP_FAILURE_RETRY( read( fd, buf, len ) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800537}
538
Spencer Low55441402015-11-07 17:34:39 -0800539// Like unix_read(), but does not handle EINTR.
540static __inline__ int unix_read_interruptible(int fd, void* buf, size_t len) {
541 return read(fd, buf, len);
542}
543
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800544#undef read
545#define read ___xxx_read
546
547static __inline__ int adb_write(int fd, const void* buf, size_t len)
548{
Kenny Rooteac025c2012-10-12 15:26:45 -0700549 return TEMP_FAILURE_RETRY( write( fd, buf, len ) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800550}
551#undef write
552#define write ___xxx_write
553
554static __inline__ int adb_lseek(int fd, int pos, int where)
555{
556 return lseek(fd, pos, where);
557}
558#undef lseek
559#define lseek ___xxx_lseek
560
561static __inline__ int adb_unlink(const char* path)
562{
563 return unlink(path);
564}
565#undef unlink
566#define unlink ___xxx_unlink
567
568static __inline__ int adb_creat(const char* path, int mode)
569{
Kenny Rooteac025c2012-10-12 15:26:45 -0700570 int fd = TEMP_FAILURE_RETRY( creat( path, mode ) );
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800571
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200572 if ( fd < 0 )
573 return -1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800574
575 close_on_exec(fd);
David 'Digit' Turner1f1efb52009-05-18 17:36:28 +0200576 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800577}
578#undef creat
579#define creat ___xxx_creat
580
David Pursell58805362015-10-28 14:29:51 -0700581static __inline__ int unix_isatty(int fd) {
582 return isatty(fd);
583}
584#define isatty ___xxx_isatty
585
Spencer Low753d4852015-07-30 23:07:55 -0700586// Helper for network_* functions.
587inline int _fd_set_error_str(int fd, std::string* error) {
588 if (fd == -1) {
589 *error = strerror(errno);
590 }
591 return fd;
592}
593
594inline int network_loopback_client(int port, int type, std::string* error) {
Elliott Hughes4e94e592016-10-11 13:45:03 -0700595 return _fd_set_error_str(socket_network_client("localhost", port, type), error);
Spencer Low753d4852015-07-30 23:07:55 -0700596}
597
598inline int network_loopback_server(int port, int type, std::string* error) {
Tao Wud5c58652016-09-19 16:50:10 -0700599 int fd = socket_loopback_server(port, type);
600 if (fd < 0 && errno == EAFNOSUPPORT)
601 return _fd_set_error_str(socket_loopback_server6(port, type), error);
602 return _fd_set_error_str(fd, error);
Spencer Low753d4852015-07-30 23:07:55 -0700603}
604
605inline int network_inaddr_any_server(int port, int type, std::string* error) {
606 return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
607}
608
Josh Gao4a5a95d2016-08-24 18:38:44 -0700609inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
610 return _fd_set_error_str(socket_local_client(name, namespace_id, type), error);
611}
612
613inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
614 return _fd_set_error_str(socket_local_server(name, namespace_id, type), error);
Spencer Low753d4852015-07-30 23:07:55 -0700615}
616
617inline int network_connect(const std::string& host, int port, int type,
618 int timeout, std::string* error) {
619 int getaddrinfo_error = 0;
620 int fd = socket_network_client_timeout(host.c_str(), port, type, timeout,
621 &getaddrinfo_error);
622 if (fd != -1) {
623 return fd;
624 }
625 if (getaddrinfo_error != 0) {
626 *error = gai_strerror(getaddrinfo_error);
627 } else {
628 *error = strerror(errno);
629 }
630 return -1;
631}
632
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800633static __inline__ int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
634{
Benoit Gobyf4ded742011-02-01 18:57:41 -0800635 int fd;
636
Kenny Rooteac025c2012-10-12 15:26:45 -0700637 fd = TEMP_FAILURE_RETRY( accept( serverfd, addr, addrlen ) );
Benoit Gobyf4ded742011-02-01 18:57:41 -0800638 if (fd >= 0)
639 close_on_exec(fd);
640
641 return fd;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800642}
643
644#undef accept
645#define accept ___xxx_accept
646
David Pursell19d0c232016-04-07 11:25:48 -0700647inline int adb_socket_get_local_port(int fd) {
648 return socket_get_local_port(fd);
649}
650
Spencer Low3a2421b2015-05-22 20:09:06 -0700651// Operate on a file descriptor returned from unix_open() or a well-known file
652// descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
653//
654// On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
655// adb_write(), adb_close() (which all map to Unix system calls), but the
656// Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
657// into the C Runtime and its configurable CR/LF translation (which is settable
658// via _setmode()).
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800659#define unix_read adb_read
660#define unix_write adb_write
661#define unix_close adb_close
662
Josh Gao7d405252016-02-12 14:31:15 -0800663// Win32 is limited to DWORDs for thread return values; limit the POSIX systems to this as well to
664// ensure compatibility.
665typedef void (*adb_thread_func_t)(void* arg);
Josh Gaoa4f5e032016-02-09 14:59:09 -0800666typedef pthread_t adb_thread_t;
667
Josh Gao7d405252016-02-12 14:31:15 -0800668struct adb_pthread_args {
669 adb_thread_func_t func;
670 void* arg;
671};
672
673static void* adb_pthread_wrapper(void* heap_args) {
674 // Move the arguments from the heap onto the thread's stack.
675 adb_pthread_args thread_args = *reinterpret_cast<adb_pthread_args*>(heap_args);
676 delete static_cast<adb_pthread_args*>(heap_args);
677 thread_args.func(thread_args.arg);
678 return nullptr;
679}
680
Josh Gaoa4f5e032016-02-09 14:59:09 -0800681static __inline__ bool adb_thread_create(adb_thread_func_t start, void* arg,
682 adb_thread_t* thread = nullptr) {
683 pthread_t temp;
Elliott Hughesf2517142015-05-05 13:41:21 -0700684 pthread_attr_t attr;
685 pthread_attr_init(&attr);
Josh Gaoa4f5e032016-02-09 14:59:09 -0800686 pthread_attr_setdetachstate(&attr, thread ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
Josh Gao7d405252016-02-12 14:31:15 -0800687 auto* pthread_args = new adb_pthread_args{.func = start, .arg = arg};
688 errno = pthread_create(&temp, &attr, adb_pthread_wrapper, pthread_args);
Josh Gaoa4f5e032016-02-09 14:59:09 -0800689 if (errno == 0) {
690 if (thread) {
691 *thread = temp;
692 }
693 return true;
694 }
695 return false;
696}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800697
Josh Gaoa4f5e032016-02-09 14:59:09 -0800698static __inline__ bool adb_thread_join(adb_thread_t thread) {
699 errno = pthread_join(thread, nullptr);
700 return errno == 0;
701}
702
703static __inline__ bool adb_thread_detach(adb_thread_t thread) {
704 errno = pthread_detach(thread);
705 return errno == 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800706}
707
Josh Gao7d405252016-02-12 14:31:15 -0800708static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
709 pthread_exit(nullptr);
710}
711
Siva Velusamy2669cf92015-08-28 16:37:29 -0700712static __inline__ int adb_thread_setname(const std::string& name) {
713#ifdef __APPLE__
714 return pthread_setname_np(name.c_str());
715#else
716 const char *s = name.c_str();
717
718 // pthread_setname_np fails rather than truncating long strings.
719 const int max_task_comm_len = 16; // including the null terminator
720 if (name.length() > (max_task_comm_len - 1)) {
721 char buf[max_task_comm_len];
722 strncpy(buf, name.c_str(), sizeof(buf) - 1);
723 buf[sizeof(buf) - 1] = '\0';
724 s = buf;
725 }
726
727 return pthread_setname_np(pthread_self(), s) ;
728#endif
729}
730
Spencer Low31aafa62015-01-25 14:40:16 -0800731static __inline__ int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
732{
733 return setsockopt( fd, level, optname, optval, optlen );
734}
735
736#undef setsockopt
737#define setsockopt ___xxx_setsockopt
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800738
739static __inline__ int unix_socketpair( int d, int type, int protocol, int sv[2] )
740{
741 return socketpair( d, type, protocol, sv );
742}
743
744static __inline__ int adb_socketpair( int sv[2] )
745{
746 int rc;
747
748 rc = unix_socketpair( AF_UNIX, SOCK_STREAM, 0, sv );
749 if (rc < 0)
750 return -1;
751
752 close_on_exec( sv[0] );
753 close_on_exec( sv[1] );
754 return 0;
755}
756
757#undef socketpair
758#define socketpair ___xxx_socketpair
759
Josh Gaoe7388122016-02-16 17:34:53 -0800760typedef struct pollfd adb_pollfd;
761static __inline__ int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
762 return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
763}
764
765#define poll ___xxx_poll
766
Alex Vallée28d1f8d2015-05-06 16:26:00 -0400767static __inline__ int adb_mkdir(const std::string& path, int mode)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800768{
Alex Vallée28d1f8d2015-05-06 16:26:00 -0400769 return mkdir(path.c_str(), mode);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800770}
Alex Vallée28d1f8d2015-05-06 16:26:00 -0400771
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800772#undef mkdir
773#define mkdir ___xxx_mkdir
774
Alex Vallée28d1f8d2015-05-06 16:26:00 -0400775static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800776 return path[0] == '/';
777}
778
leozwang1be54622014-08-15 09:51:27 -0700779static __inline__ unsigned long adb_thread_id()
780{
Spencer Low5c761bd2015-07-21 02:06:26 -0700781 return (unsigned long)gettid();
leozwang1be54622014-08-15 09:51:27 -0700782}
783
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800784#endif /* !_WIN32 */
785
Elliott Hughes54e3efe2015-11-20 22:01:06 -0800786static inline void disable_tcp_nagle(int fd) {
787 int off = 1;
788 adb_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
789}
790
David Pursellc25a34e2016-02-22 14:27:23 -0800791// Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
792// |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
793// configured to drop after 10 missed keepalives. Returns true on success.
794bool set_tcp_keepalive(int fd, int interval_sec);
795
Elliott Hughes801066a2016-06-29 17:42:01 -0700796#if defined(_WIN32)
797// Win32 defines ERROR, which we don't need, but which conflicts with google3 logging.
798#undef ERROR
799#endif
800
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800801#endif /* _ADB_SYSDEPS_H */