blob: 05d9fded1f615b6eb584c8e4ee1ee188b2f98133 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* this file contains system-dependent definitions used by ADB
18 * they're related to threads, sockets and file descriptors
19 */
20#ifndef _ADB_SYSDEPS_H
21#define _ADB_SYSDEPS_H
22
23#ifdef __CYGWIN__
24# undef _WIN32
25#endif
26
Elliott Hughes381cfa92015-07-23 17:12:58 -070027#include <errno.h>
28
Spencer Low5200c662015-07-30 23:07:55 -070029#include <string>
Spencer Lowa30b79a2015-11-15 16:29:36 -080030#include <vector>
Spencer Low5200c662015-07-30 23:07:55 -070031
Josh Gao13ea01d2016-05-13 14:52:06 -070032// Include this before open/close/unlink are defined as macros below.
Josh Gao3b3e10d2016-02-09 14:59:09 -080033#include <android-base/errors.h>
Josh Gao13ea01d2016-05-13 14:52:06 -070034#include <android-base/unique_fd.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080035#include <android-base/utf8.h>
Spencer Lowd21dc822015-11-12 15:20:15 -080036
Josh Gaof551ea02016-07-28 18:09:48 -070037#include "sysdeps/stat.h"
38
Dan Albertcc731cc2015-02-24 21:26:58 -080039/*
40 * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
41 * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
42 * not already defined, then define it here.
43 */
44#ifndef TEMP_FAILURE_RETRY
45/* Used to retry syscalls that can return EINTR. */
46#define TEMP_FAILURE_RETRY(exp) ({ \
47 typeof (exp) _rc; \
48 do { \
49 _rc = (exp); \
50 } while (_rc == -1 && errno == EINTR); \
51 _rc; })
52#endif
53
Spencer Lowcf4ff642015-05-11 01:08:48 -070054// Some printf-like functions are implemented in terms of
55// android::base::StringAppendV, so they should use the same attribute for
56// compile-time format string checking. On Windows, if the mingw version of
57// vsnprintf is used in StringAppendV, use `gnu_printf' which allows z in %zd
58// and PRIu64 (and related) to be recognized by the compile-time checking.
59#define ADB_FORMAT_ARCHETYPE __printf__
60#ifdef __USE_MINGW_ANSI_STDIO
61#if __USE_MINGW_ANSI_STDIO
62#undef ADB_FORMAT_ARCHETYPE
63#define ADB_FORMAT_ARCHETYPE gnu_printf
64#endif
65#endif
66
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080067#ifdef _WIN32
68
Josh Gaoa166e712016-01-29 12:08:34 -080069// Clang-only nullability specifiers
70#define _Nonnull
71#define _Nullable
72
Dan Albert630b9af2014-11-24 23:34:35 -080073#include <ctype.h>
74#include <direct.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070075#include <dirent.h>
Dan Albert630b9af2014-11-24 23:34:35 -080076#include <errno.h>
77#include <fcntl.h>
78#include <io.h>
79#include <process.h>
80#include <sys/stat.h>
Spencer Lowcf4ff642015-05-11 01:08:48 -070081#include <utime.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080082#include <winsock2.h>
Stephen Hines2f431a82014-10-01 17:37:06 -070083#include <windows.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080084#include <ws2tcpip.h>
Dan Albert630b9af2014-11-24 23:34:35 -080085
Spencer Low2122c7a2015-08-26 18:46:09 -070086#include <memory> // unique_ptr
Spencer Lowd21dc822015-11-12 15:20:15 -080087#include <string>
Alex Vallée47d67c92015-05-06 16:26:00 -040088
Dan Albert630b9af2014-11-24 23:34:35 -080089#include "fdevent.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080090
Elliott Hughes5c742702015-07-30 17:42:01 -070091#define OS_PATH_SEPARATORS "\\/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080092#define OS_PATH_SEPARATOR '\\'
93#define OS_PATH_SEPARATOR_STR "\\"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -070094#define ENV_PATH_SEPARATOR_STR ";"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080095
Josh Gao07db1192015-11-07 15:38:19 -080096static __inline__ bool adb_is_separator(char c) {
97 return c == '\\' || c == '/';
98}
99
Josh Gaob5fea142016-02-12 14:31:15 -0800100typedef void (*adb_thread_func_t)(void* arg);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800101typedef HANDLE adb_thread_t;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800102
Josh Gaob5fea142016-02-12 14:31:15 -0800103struct adb_winthread_args {
Josh Gao3b3e10d2016-02-09 14:59:09 -0800104 adb_thread_func_t func;
105 void* arg;
106};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800107
Josh Gaob5fea142016-02-12 14:31:15 -0800108static unsigned __stdcall adb_winthread_wrapper(void* heap_args) {
109 // Move the arguments from the heap onto the thread's stack.
110 adb_winthread_args thread_args = *static_cast<adb_winthread_args*>(heap_args);
111 delete static_cast<adb_winthread_args*>(heap_args);
112 thread_args.func(thread_args.arg);
113 return 0;
Josh Gao3b3e10d2016-02-09 14:59:09 -0800114}
115
116static __inline__ bool adb_thread_create(adb_thread_func_t func, void* arg,
117 adb_thread_t* thread = nullptr) {
Josh Gaob5fea142016-02-12 14:31:15 -0800118 adb_winthread_args* args = new adb_winthread_args{.func = func, .arg = arg};
119 uintptr_t handle = _beginthreadex(nullptr, 0, adb_winthread_wrapper, args, 0, nullptr);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800120 if (handle != static_cast<uintptr_t>(0)) {
121 if (thread) {
122 *thread = reinterpret_cast<HANDLE>(handle);
123 } else {
124 CloseHandle(thread);
125 }
126 return true;
127 }
128 return false;
129}
130
131static __inline__ bool adb_thread_join(adb_thread_t thread) {
132 switch (WaitForSingleObject(thread, INFINITE)) {
133 case WAIT_OBJECT_0:
134 CloseHandle(thread);
135 return true;
136
137 case WAIT_FAILED:
138 fprintf(stderr, "adb_thread_join failed: %s\n",
139 android::base::SystemErrorCodeToString(GetLastError()).c_str());
140 break;
141
142 default:
143 abort();
144 }
145
146 return false;
147}
148
149static __inline__ bool adb_thread_detach(adb_thread_t thread) {
150 CloseHandle(thread);
151 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800152}
153
Josh Gaob5fea142016-02-12 14:31:15 -0800154static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
Josh Gaod7b37492016-02-12 15:45:04 -0800155 _endthreadex(0);
Josh Gaob5fea142016-02-12 14:31:15 -0800156}
157
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700158static __inline__ int adb_thread_setname(const std::string& name) {
159 // TODO: See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx for how to set
160 // the thread name in Windows. Unfortunately, it only works during debugging, but
161 // our build process doesn't generate PDB files needed for debugging.
162 return 0;
163}
164
Josh Gao3777d2e2016-02-16 17:34:53 -0800165static __inline__ adb_thread_t adb_thread_self() {
166 return GetCurrentThread();
167}
168
169static __inline__ bool adb_thread_equal(adb_thread_t lhs, adb_thread_t rhs) {
170 return GetThreadId(lhs) == GetThreadId(rhs);
171}
172
leozwangcbf02672014-08-15 09:51:27 -0700173static __inline__ unsigned long adb_thread_id()
174{
175 return GetCurrentThreadId();
176}
177
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800178static __inline__ void close_on_exec(int fd)
179{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200180 /* nothing really */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800181}
182
Spencer Lowcf4ff642015-05-11 01:08:48 -0700183extern int adb_unlink(const char* path);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800184#undef unlink
185#define unlink ___xxx_unlink
186
Spencer Lowcf4ff642015-05-11 01:08:48 -0700187extern int adb_mkdir(const std::string& path, int mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188#undef mkdir
189#define mkdir ___xxx_mkdir
190
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700191// See the comments for the !defined(_WIN32) versions of adb_*().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192extern int adb_open(const char* path, int options);
193extern int adb_creat(const char* path, int mode);
194extern int adb_read(int fd, void* buf, int len);
195extern int adb_write(int fd, const void* buf, int len);
196extern int adb_lseek(int fd, int pos, int where);
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400197extern int adb_shutdown(int fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800198extern int adb_close(int fd);
199
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700200// See the comments for the !defined(_WIN32) version of unix_close().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201static __inline__ int unix_close(int fd)
202{
203 return close(fd);
204}
205#undef close
206#define close ____xxx_close
207
Spencer Low2e02dc62015-11-07 17:34:39 -0800208// Like unix_read(), but may return EINTR.
209extern int unix_read_interruptible(int fd, void* buf, size_t len);
210
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700211// See the comments for the !defined(_WIN32) version of unix_read().
Spencer Low2e02dc62015-11-07 17:34:39 -0800212static __inline__ int unix_read(int fd, void* buf, size_t len) {
213 return TEMP_FAILURE_RETRY(unix_read_interruptible(fd, buf, len));
214}
Spencer Low50184062015-03-01 15:06:21 -0800215
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800216#undef read
217#define read ___xxx_read
218
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700219// See the comments for the !defined(_WIN32) version of unix_write().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800220static __inline__ int unix_write(int fd, const void* buf, size_t len)
221{
222 return write(fd, buf, len);
223}
224#undef write
225#define write ___xxx_write
226
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700227// See the comments for the !defined(_WIN32) version of adb_open_mode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800228static __inline__ int adb_open_mode(const char* path, int options, int mode)
229{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200230 return adb_open(path, options);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800231}
232
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700233// See the comments for the !defined(_WIN32) version of unix_open().
Spencer Lowcf4ff642015-05-11 01:08:48 -0700234extern int unix_open(const char* path, int options, ...);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800235#define open ___xxx_unix_open
236
David Pursellc5b8ad82015-10-28 14:29:51 -0700237// Checks if |fd| corresponds to a console.
238// Standard Windows isatty() returns 1 for both console FDs and character
239// devices like NUL. unix_isatty() performs some extra checking to only match
240// console FDs.
241// |fd| must be a real file descriptor, meaning STDxx_FILENO or unix_open() FDs
242// will work but adb_open() FDs will not. Additionally the OS handle associated
243// with |fd| must have GENERIC_READ access (which console FDs have by default).
244// Returns 1 if |fd| is a console FD, 0 otherwise. The value of errno after
245// calling this function is unreliable and should not be used.
246int unix_isatty(int fd);
247#define isatty ___xxx_isatty
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800248
Spencer Low5200c662015-07-30 23:07:55 -0700249int network_loopback_client(int port, int type, std::string* error);
250int network_loopback_server(int port, int type, std::string* error);
251int network_inaddr_any_server(int port, int type, std::string* error);
Josh Gaocfb21412016-08-24 18:38:44 -0700252
253inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
254 abort();
255}
256
257inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
258 abort();
259}
260
Spencer Low5200c662015-07-30 23:07:55 -0700261int network_connect(const std::string& host, int port, int type, int timeout,
262 std::string* error);
263
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800264extern int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen);
265
266#undef accept
267#define accept ___xxx_accept
268
Josh Gao59901912016-08-23 15:28:43 -0700269int adb_getsockname(int fd, struct sockaddr* sockaddr, socklen_t* optlen);
270#undef getsockname
271#define getsockname(...) ___xxx_getsockname(__VA__ARGS__)
272
David Purselleaae97e2016-04-07 11:25:48 -0700273// Returns the local port number of a bound socket, or -1 on failure.
274int adb_socket_get_local_port(int fd);
275
Spencer Lowf055c192015-01-25 14:40:16 -0800276extern int adb_setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen);
277
278#undef setsockopt
279#define setsockopt ___xxx_setsockopt
280
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281extern int adb_socketpair( int sv[2] );
282
Josh Gao3777d2e2016-02-16 17:34:53 -0800283struct adb_pollfd {
284 int fd;
285 short events;
286 short revents;
287};
288extern int adb_poll(adb_pollfd* fds, size_t nfds, int timeout);
289#define poll ___xxx_poll
290
Elliott Hughes5c742702015-07-30 17:42:01 -0700291static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800292 return isalpha(path[0]) && path[1] == ':' && path[2] == '\\';
293}
294
Spencer Lowcf4ff642015-05-11 01:08:48 -0700295// UTF-8 versions of POSIX APIs.
296extern DIR* adb_opendir(const char* dirname);
297extern struct dirent* adb_readdir(DIR* dir);
298extern int adb_closedir(DIR* dir);
299
300extern int adb_utime(const char *, struct utimbuf *);
301extern int adb_chmod(const char *, int);
302
303extern int adb_vfprintf(FILE *stream, const char *format, va_list ap)
304 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 0)));
Spencer Lowa30b79a2015-11-15 16:29:36 -0800305extern int adb_vprintf(const char *format, va_list ap)
306 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 0)));
Spencer Lowcf4ff642015-05-11 01:08:48 -0700307extern int adb_fprintf(FILE *stream, const char *format, ...)
308 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 2, 3)));
309extern int adb_printf(const char *format, ...)
310 __attribute__((__format__(ADB_FORMAT_ARCHETYPE, 1, 2)));
311
312extern int adb_fputs(const char* buf, FILE* stream);
313extern int adb_fputc(int ch, FILE* stream);
Spencer Lowa30b79a2015-11-15 16:29:36 -0800314extern int adb_putchar(int ch);
315extern int adb_puts(const char* buf);
Spencer Lowcf4ff642015-05-11 01:08:48 -0700316extern size_t adb_fwrite(const void* ptr, size_t size, size_t nmemb,
317 FILE* stream);
318
319extern FILE* adb_fopen(const char* f, const char* m);
320
321extern char* adb_getenv(const char* name);
322
323extern char* adb_getcwd(char* buf, int size);
324
325// Remap calls to POSIX APIs to our UTF-8 versions.
326#define opendir adb_opendir
327#define readdir adb_readdir
328#define closedir adb_closedir
329#define rewinddir rewinddir_utf8_not_yet_implemented
330#define telldir telldir_utf8_not_yet_implemented
Spencer Low363af562015-11-07 18:51:54 -0800331// Some compiler's C++ headers have members named seekdir, so we can't do the
332// macro technique and instead cause a link error if seekdir is called.
333inline void seekdir(DIR*, long) {
334 extern int seekdir_utf8_not_yet_implemented;
335 seekdir_utf8_not_yet_implemented = 1;
336}
Spencer Lowcf4ff642015-05-11 01:08:48 -0700337
338#define utime adb_utime
339#define chmod adb_chmod
340
341#define vfprintf adb_vfprintf
Spencer Lowa30b79a2015-11-15 16:29:36 -0800342#define vprintf adb_vprintf
Spencer Lowcf4ff642015-05-11 01:08:48 -0700343#define fprintf adb_fprintf
344#define printf adb_printf
345#define fputs adb_fputs
346#define fputc adb_fputc
Spencer Lowa30b79a2015-11-15 16:29:36 -0800347// putc may be a macro, so if so, undefine it, so that we can redefine it.
348#undef putc
349#define putc(c, s) adb_fputc(c, s)
350#define putchar adb_putchar
351#define puts adb_puts
Spencer Lowcf4ff642015-05-11 01:08:48 -0700352#define fwrite adb_fwrite
353
354#define fopen adb_fopen
Spencer Lowa30b79a2015-11-15 16:29:36 -0800355#define freopen freopen_utf8_not_yet_implemented
Spencer Lowcf4ff642015-05-11 01:08:48 -0700356
357#define getenv adb_getenv
358#define putenv putenv_utf8_not_yet_implemented
359#define setenv setenv_utf8_not_yet_implemented
360#define unsetenv unsetenv_utf8_not_yet_implemented
361
362#define getcwd adb_getcwd
363
Josh Gao43c02b22016-12-05 13:15:55 -0800364char* adb_strerror(int err);
365#define strerror adb_strerror
366
Spencer Lowcf4ff642015-05-11 01:08:48 -0700367// Helper class to convert UTF-16 argv from wmain() to UTF-8 args that can be
368// passed to main().
369class NarrowArgs {
370public:
371 NarrowArgs(int argc, wchar_t** argv);
372 ~NarrowArgs();
373
374 inline char** data() {
375 return narrow_args;
376 }
377
378private:
379 char** narrow_args;
380};
381
Spencer Low5c398d22015-08-08 15:07:07 -0700382// Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
383// so they can fit in an int. To convert back, we just need to sign-extend.
384// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
385// Note that this does not make a HANDLE value work with APIs like open(), nor
386// does this make a value from open() passable to APIs taking a HANDLE. This
387// just lets you take a HANDLE, pass it around as an int, and then use it again
388// as a HANDLE.
389inline int cast_handle_to_int(const HANDLE h) {
390 // truncate
391 return static_cast<int>(reinterpret_cast<INT_PTR>(h));
392}
393
394inline HANDLE cast_int_to_handle(const int fd) {
395 // sign-extend
396 return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
397}
398
Spencer Low2122c7a2015-08-26 18:46:09 -0700399// Deleter for unique_handle. Adapted from many sources, including:
400// http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api
401// https://visualstudiomagazine.com/articles/2013/09/01/get-a-handle-on-the-windows-api.aspx
402class handle_deleter {
403public:
404 typedef HANDLE pointer;
405
406 void operator()(HANDLE h);
407};
408
409// Like std::unique_ptr, but for Windows HANDLE objects that should be
410// CloseHandle()'d. Operator bool() only checks if the handle != nullptr,
411// but does not check if the handle != INVALID_HANDLE_VALUE.
412typedef std::unique_ptr<HANDLE, handle_deleter> unique_handle;
413
Spencer Lowa30b79a2015-11-15 16:29:36 -0800414namespace internal {
415
416size_t ParseCompleteUTF8(const char* first, const char* last, std::vector<char>* remaining_bytes);
417
418}
419
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800420#else /* !_WIN32 a.k.a. Unix */
421
Spencer Low5200c662015-07-30 23:07:55 -0700422#include <cutils/sockets.h>
Spencer Low8d8126a2015-07-21 02:06:26 -0700423#include <cutils/threads.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800424#include <fcntl.h>
Josh Gao3777d2e2016-02-16 17:34:53 -0800425#include <poll.h>
426#include <signal.h>
427#include <sys/stat.h>
428#include <sys/wait.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800429
430#include <pthread.h>
431#include <unistd.h>
432#include <fcntl.h>
433#include <stdarg.h>
Spencer Low5200c662015-07-30 23:07:55 -0700434#include <netdb.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800435#include <netinet/in.h>
436#include <netinet/tcp.h>
437#include <string.h>
Kenny Root73167412012-10-12 15:26:45 -0700438#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800439
Alex Vallée47d67c92015-05-06 16:26:00 -0400440#include <string>
441
Elliott Hughes5c742702015-07-30 17:42:01 -0700442#define OS_PATH_SEPARATORS "/"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800443#define OS_PATH_SEPARATOR '/'
444#define OS_PATH_SEPARATOR_STR "/"
Benoit Gobyd5fcafa2012-04-12 12:23:49 -0700445#define ENV_PATH_SEPARATOR_STR ":"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800446
Josh Gao07db1192015-11-07 15:38:19 -0800447static __inline__ bool adb_is_separator(char c) {
448 return c == '/';
449}
450
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800451static __inline__ void close_on_exec(int fd)
452{
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200453 fcntl( fd, F_SETFD, FD_CLOEXEC );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800454}
455
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700456// Open a file and return a file descriptor that may be used with unix_read(),
457// unix_write(), unix_close(), but not adb_read(), adb_write(), adb_close().
458//
459// On Unix, this is based on open(), so the file descriptor is a real OS file
460// descriptor, but the Windows implementation (in sysdeps_win32.cpp) returns a
461// file descriptor that can only be used with C Runtime APIs (which are wrapped
462// by unix_read(), unix_write(), unix_close()). Also, the C Runtime has
463// configurable CR/LF translation which defaults to text mode, but is settable
464// with _setmode().
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800465static __inline__ int unix_open(const char* path, int options,...)
466{
467 if ((options & O_CREAT) == 0)
468 {
Kenny Root73167412012-10-12 15:26:45 -0700469 return TEMP_FAILURE_RETRY( open(path, options) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800470 }
471 else
472 {
473 int mode;
474 va_list args;
475 va_start( args, options );
476 mode = va_arg( args, int );
477 va_end( args );
Kenny Root73167412012-10-12 15:26:45 -0700478 return TEMP_FAILURE_RETRY( open( path, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800479 }
480}
481
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700482// Similar to the two-argument adb_open(), but takes a mode parameter for file
483// creation. See adb_open() for more info.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800484static __inline__ int adb_open_mode( const char* pathname, int options, int mode )
485{
Kenny Root73167412012-10-12 15:26:45 -0700486 return TEMP_FAILURE_RETRY( open( pathname, options, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800487}
488
489
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700490// Open a file and return a file descriptor that may be used with adb_read(),
491// adb_write(), adb_close(), but not unix_read(), unix_write(), unix_close().
492//
493// On Unix, this is based on open(), but the Windows implementation (in
494// sysdeps_win32.cpp) uses Windows native file I/O and bypasses the C Runtime
495// and its CR/LF translation. The returned file descriptor should be used with
496// adb_read(), adb_write(), adb_close(), etc.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800497static __inline__ int adb_open( const char* pathname, int options )
498{
Kenny Root73167412012-10-12 15:26:45 -0700499 int fd = TEMP_FAILURE_RETRY( open( pathname, options ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800500 if (fd < 0)
501 return -1;
502 close_on_exec( fd );
503 return fd;
504}
505#undef open
506#define open ___xxx_open
507
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400508static __inline__ int adb_shutdown(int fd)
509{
510 return shutdown(fd, SHUT_RDWR);
511}
David Pursell1ed57f02015-10-06 15:30:03 -0700512static __inline__ int adb_shutdown(int fd, int direction)
513{
514 return shutdown(fd, direction);
515}
Mike Lockwood8cf0d592009-10-11 23:04:18 -0400516#undef shutdown
517#define shutdown ____xxx_shutdown
518
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700519// Closes a file descriptor that came from adb_open() or adb_open_mode(), but
520// not designed to take a file descriptor from unix_open(). See the comments
521// for adb_open() for more info.
Josh Gaof0d3b4f2016-03-04 15:15:56 -0800522__inline__ int adb_close(int fd) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800523 return close(fd);
524}
525#undef close
526#define close ____xxx_close
527
528
529static __inline__ int adb_read(int fd, void* buf, size_t len)
530{
Kenny Root73167412012-10-12 15:26:45 -0700531 return TEMP_FAILURE_RETRY( read( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800532}
533
Spencer Low2e02dc62015-11-07 17:34:39 -0800534// Like unix_read(), but does not handle EINTR.
535static __inline__ int unix_read_interruptible(int fd, void* buf, size_t len) {
536 return read(fd, buf, len);
537}
538
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800539#undef read
540#define read ___xxx_read
541
542static __inline__ int adb_write(int fd, const void* buf, size_t len)
543{
Kenny Root73167412012-10-12 15:26:45 -0700544 return TEMP_FAILURE_RETRY( write( fd, buf, len ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800545}
546#undef write
547#define write ___xxx_write
548
549static __inline__ int adb_lseek(int fd, int pos, int where)
550{
551 return lseek(fd, pos, where);
552}
553#undef lseek
554#define lseek ___xxx_lseek
555
556static __inline__ int adb_unlink(const char* path)
557{
558 return unlink(path);
559}
560#undef unlink
561#define unlink ___xxx_unlink
562
563static __inline__ int adb_creat(const char* path, int mode)
564{
Kenny Root73167412012-10-12 15:26:45 -0700565 int fd = TEMP_FAILURE_RETRY( creat( path, mode ) );
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800566
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200567 if ( fd < 0 )
568 return -1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800569
570 close_on_exec(fd);
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200571 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800572}
573#undef creat
574#define creat ___xxx_creat
575
David Pursellc5b8ad82015-10-28 14:29:51 -0700576static __inline__ int unix_isatty(int fd) {
577 return isatty(fd);
578}
579#define isatty ___xxx_isatty
580
Spencer Low5200c662015-07-30 23:07:55 -0700581// Helper for network_* functions.
582inline int _fd_set_error_str(int fd, std::string* error) {
583 if (fd == -1) {
584 *error = strerror(errno);
585 }
586 return fd;
587}
588
589inline int network_loopback_client(int port, int type, std::string* error) {
Elliott Hughes139b3722016-10-11 13:45:03 -0700590 return _fd_set_error_str(socket_network_client("localhost", port, type), error);
Spencer Low5200c662015-07-30 23:07:55 -0700591}
592
593inline int network_loopback_server(int port, int type, std::string* error) {
Tao Wu7b700762016-09-19 16:50:10 -0700594 int fd = socket_loopback_server(port, type);
595 if (fd < 0 && errno == EAFNOSUPPORT)
596 return _fd_set_error_str(socket_loopback_server6(port, type), error);
597 return _fd_set_error_str(fd, error);
Spencer Low5200c662015-07-30 23:07:55 -0700598}
599
600inline int network_inaddr_any_server(int port, int type, std::string* error) {
601 return _fd_set_error_str(socket_inaddr_any_server(port, type), error);
602}
603
Josh Gaocfb21412016-08-24 18:38:44 -0700604inline int network_local_client(const char* name, int namespace_id, int type, std::string* error) {
605 return _fd_set_error_str(socket_local_client(name, namespace_id, type), error);
606}
607
608inline int network_local_server(const char* name, int namespace_id, int type, std::string* error) {
609 return _fd_set_error_str(socket_local_server(name, namespace_id, type), error);
Spencer Low5200c662015-07-30 23:07:55 -0700610}
611
612inline int network_connect(const std::string& host, int port, int type,
613 int timeout, std::string* error) {
614 int getaddrinfo_error = 0;
615 int fd = socket_network_client_timeout(host.c_str(), port, type, timeout,
616 &getaddrinfo_error);
617 if (fd != -1) {
618 return fd;
619 }
620 if (getaddrinfo_error != 0) {
621 *error = gai_strerror(getaddrinfo_error);
622 } else {
623 *error = strerror(errno);
624 }
625 return -1;
626}
627
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800628static __inline__ int adb_socket_accept(int serverfd, struct sockaddr* addr, socklen_t *addrlen)
629{
Benoit Goby95ef8282011-02-01 18:57:41 -0800630 int fd;
631
Kenny Root73167412012-10-12 15:26:45 -0700632 fd = TEMP_FAILURE_RETRY( accept( serverfd, addr, addrlen ) );
Benoit Goby95ef8282011-02-01 18:57:41 -0800633 if (fd >= 0)
634 close_on_exec(fd);
635
636 return fd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800637}
638
639#undef accept
640#define accept ___xxx_accept
641
David Purselleaae97e2016-04-07 11:25:48 -0700642inline int adb_socket_get_local_port(int fd) {
643 return socket_get_local_port(fd);
644}
645
Spencer Low6ac5d7d2015-05-22 20:09:06 -0700646// Operate on a file descriptor returned from unix_open() or a well-known file
647// descriptor such as STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
648//
649// On Unix, unix_read(), unix_write(), unix_close() map to adb_read(),
650// adb_write(), adb_close() (which all map to Unix system calls), but the
651// Windows implementations (in the ifdef above and in sysdeps_win32.cpp) call
652// into the C Runtime and its configurable CR/LF translation (which is settable
653// via _setmode()).
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800654#define unix_read adb_read
655#define unix_write adb_write
656#define unix_close adb_close
657
Josh Gaob5fea142016-02-12 14:31:15 -0800658// Win32 is limited to DWORDs for thread return values; limit the POSIX systems to this as well to
659// ensure compatibility.
660typedef void (*adb_thread_func_t)(void* arg);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800661typedef pthread_t adb_thread_t;
662
Josh Gaob5fea142016-02-12 14:31:15 -0800663struct adb_pthread_args {
664 adb_thread_func_t func;
665 void* arg;
666};
667
668static void* adb_pthread_wrapper(void* heap_args) {
669 // Move the arguments from the heap onto the thread's stack.
670 adb_pthread_args thread_args = *reinterpret_cast<adb_pthread_args*>(heap_args);
671 delete static_cast<adb_pthread_args*>(heap_args);
672 thread_args.func(thread_args.arg);
673 return nullptr;
674}
675
Josh Gao3b3e10d2016-02-09 14:59:09 -0800676static __inline__ bool adb_thread_create(adb_thread_func_t start, void* arg,
677 adb_thread_t* thread = nullptr) {
678 pthread_t temp;
Elliott Hughes9b0f3542015-05-05 13:41:21 -0700679 pthread_attr_t attr;
680 pthread_attr_init(&attr);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800681 pthread_attr_setdetachstate(&attr, thread ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED);
Josh Gaob5fea142016-02-12 14:31:15 -0800682 auto* pthread_args = new adb_pthread_args{.func = start, .arg = arg};
683 errno = pthread_create(&temp, &attr, adb_pthread_wrapper, pthread_args);
Josh Gao3b3e10d2016-02-09 14:59:09 -0800684 if (errno == 0) {
685 if (thread) {
686 *thread = temp;
687 }
688 return true;
689 }
690 return false;
691}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800692
Josh Gao3b3e10d2016-02-09 14:59:09 -0800693static __inline__ bool adb_thread_join(adb_thread_t thread) {
694 errno = pthread_join(thread, nullptr);
695 return errno == 0;
696}
697
698static __inline__ bool adb_thread_detach(adb_thread_t thread) {
699 errno = pthread_detach(thread);
700 return errno == 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800701}
702
Josh Gaob5fea142016-02-12 14:31:15 -0800703static __inline__ void __attribute__((noreturn)) adb_thread_exit() {
704 pthread_exit(nullptr);
705}
706
Siva Velusamy49ee7cf2015-08-28 16:37:29 -0700707static __inline__ int adb_thread_setname(const std::string& name) {
708#ifdef __APPLE__
709 return pthread_setname_np(name.c_str());
710#else
711 const char *s = name.c_str();
712
713 // pthread_setname_np fails rather than truncating long strings.
714 const int max_task_comm_len = 16; // including the null terminator
715 if (name.length() > (max_task_comm_len - 1)) {
716 char buf[max_task_comm_len];
717 strncpy(buf, name.c_str(), sizeof(buf) - 1);
718 buf[sizeof(buf) - 1] = '\0';
719 s = buf;
720 }
721
722 return pthread_setname_np(pthread_self(), s) ;
723#endif
724}
725
Spencer Lowf055c192015-01-25 14:40:16 -0800726static __inline__ int adb_setsockopt( int fd, int level, int optname, const void* optval, socklen_t optlen )
727{
728 return setsockopt( fd, level, optname, optval, optlen );
729}
730
731#undef setsockopt
732#define setsockopt ___xxx_setsockopt
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733
734static __inline__ int unix_socketpair( int d, int type, int protocol, int sv[2] )
735{
736 return socketpair( d, type, protocol, sv );
737}
738
739static __inline__ int adb_socketpair( int sv[2] )
740{
741 int rc;
742
743 rc = unix_socketpair( AF_UNIX, SOCK_STREAM, 0, sv );
744 if (rc < 0)
745 return -1;
746
747 close_on_exec( sv[0] );
748 close_on_exec( sv[1] );
749 return 0;
750}
751
752#undef socketpair
753#define socketpair ___xxx_socketpair
754
Josh Gao3777d2e2016-02-16 17:34:53 -0800755typedef struct pollfd adb_pollfd;
756static __inline__ int adb_poll(adb_pollfd* fds, size_t nfds, int timeout) {
757 return TEMP_FAILURE_RETRY(poll(fds, nfds, timeout));
758}
759
760#define poll ___xxx_poll
761
Alex Vallée47d67c92015-05-06 16:26:00 -0400762static __inline__ int adb_mkdir(const std::string& path, int mode)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800763{
Alex Vallée47d67c92015-05-06 16:26:00 -0400764 return mkdir(path.c_str(), mode);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800765}
Alex Vallée47d67c92015-05-06 16:26:00 -0400766
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800767#undef mkdir
768#define mkdir ___xxx_mkdir
769
Alex Vallée47d67c92015-05-06 16:26:00 -0400770static __inline__ int adb_is_absolute_host_path(const char* path) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800771 return path[0] == '/';
772}
773
leozwangcbf02672014-08-15 09:51:27 -0700774static __inline__ unsigned long adb_thread_id()
775{
Spencer Low8d8126a2015-07-21 02:06:26 -0700776 return (unsigned long)gettid();
leozwangcbf02672014-08-15 09:51:27 -0700777}
778
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800779#endif /* !_WIN32 */
780
Elliott Hughescc65c3b2015-11-20 22:01:06 -0800781static inline void disable_tcp_nagle(int fd) {
782 int off = 1;
783 adb_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &off, sizeof(off));
784}
785
David Pursellbfd95032016-02-22 14:27:23 -0800786// Sets TCP socket |fd| to send a keepalive TCP message every |interval_sec| seconds. Set
787// |interval_sec| to 0 to disable keepalives. If keepalives are enabled, the connection will be
788// configured to drop after 10 missed keepalives. Returns true on success.
789bool set_tcp_keepalive(int fd, int interval_sec);
790
Elliott Hughes0aeb5052016-06-29 17:42:01 -0700791#if defined(_WIN32)
792// Win32 defines ERROR, which we don't need, but which conflicts with google3 logging.
793#undef ERROR
794#endif
795
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800796#endif /* _ADB_SYSDEPS_H */