1 /*
2 * Copyright (C) 2011 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 #define LOG_TAG "Linux"
18
19 #include <arpa/inet.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <ifaddrs.h>
23 #include <linux/rtnetlink.h>
24 #include <net/if.h>
25 #include <netdb.h>
26 #include <netinet/in.h>
27 #include <netpacket/packet.h>
28 #include <poll.h>
29 #include <pwd.h>
30 #include <signal.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/capability.h>
34 #include <sys/ioctl.h>
35 #include <sys/mman.h>
36 #include <sys/prctl.h>
37 #include <sys/resource.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 #include <sys/syscall.h>
41 #include <sys/time.h>
42 #include <sys/types.h>
43 #include <sys/uio.h>
44 #include <sys/un.h>
45 #include <sys/utsname.h>
46 #include <sys/wait.h>
47 #include <sys/xattr.h>
48 #include <termios.h>
49 #include <unistd.h>
50
51 #include <memory>
52
53 #if defined(__BIONIC__)
54 #include <android/fdsan.h>
55 #endif
56
57 #include <android-base/file.h>
58 #include <android-base/logging.h>
59 #include <android-base/macros.h>
60 #include <android-base/stringprintf.h>
61 #include <android-base/strings.h>
62 #include <log/log.h>
63 #include <nativehelper/JNIPlatformHelp.h>
64 #include <nativehelper/ScopedLocalRef.h>
65 #include <nativehelper/ScopedPrimitiveArray.h>
66 #include <nativehelper/ScopedUtfChars.h>
67 #include <nativehelper/jni_macros.h>
68 #include <nativehelper/toStringArray.h>
69
70 #include "AsynchronousCloseMonitor.h"
71 #include "ExecStrings.h"
72 #include "JniConstants.h"
73 #include "JniException.h"
74 #include "NetworkUtilities.h"
75 #include "Portability.h"
76 #include "ScopedBytes.h"
77 #include "ScopedByteBufferArray.h"
78 #include "ScopedMsghdr.h"
79
80
81 #ifndef __unused
82 #define __unused __attribute__((__unused__))
83 #endif
84
85 #define TO_JAVA_STRING(NAME, EXP) \
86 jstring NAME = env->NewStringUTF(EXP); \
87 if ((NAME) == NULL) return NULL;
88
89 namespace {
90
91 jfieldID int32RefValueFid;
92 jfieldID int64RefValueFid;
93
94 } // namespace
95
96 struct addrinfo_deleter {
operator ()addrinfo_deleter97 void operator()(addrinfo* p) const {
98 if (p != NULL) { // bionic's freeaddrinfo(3) crashes when passed NULL.
99 freeaddrinfo(p);
100 }
101 }
102 };
103
104 struct c_deleter {
operator ()c_deleter105 void operator()(void* p) const {
106 free(p);
107 }
108 };
109
isIPv4MappedAddress(const sockaddr * sa)110 static bool isIPv4MappedAddress(const sockaddr *sa) {
111 const sockaddr_in6 *sin6 = reinterpret_cast<const sockaddr_in6*>(sa);
112 return sa != NULL && sa->sa_family == AF_INET6 &&
113 (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ||
114 IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)); // We map 0.0.0.0 to ::, so :: is mapped.
115 }
116
117 /**
118 * Perform a socket operation that specifies an IP address, possibly falling back from specifying
119 * the address as an IPv4-mapped IPv6 address in a struct sockaddr_in6 to specifying it as an IPv4
120 * address in a struct sockaddr_in.
121 *
122 * This is needed because all sockets created by the java.net APIs are IPv6 sockets, and on those
123 * sockets, IPv4 operations use IPv4-mapped addresses stored in a struct sockaddr_in6. But sockets
124 * created using Linux.socket(AF_INET, ...) are IPv4 sockets and only support operations using IPv4
125 * socket addresses structures.
126 */
127 #define NET_IPV4_FALLBACK(jni_env, return_type, syscall_name, java_fd, java_addr, port, null_addr_ok, args...) ({ \
128 return_type _rc = -1; \
129 do { \
130 sockaddr_storage _ss; \
131 socklen_t _salen; \
132 if ((java_addr) == NULL && (null_addr_ok)) { \
133 /* No IP address specified (e.g., sendto() on a connected socket). */ \
134 _salen = 0; \
135 } else if (!inetAddressToSockaddr(jni_env, java_addr, port, _ss, _salen)) { \
136 /* Invalid socket address, return -1. inetAddressToSockaddr has already thrown. */ \
137 break; \
138 } \
139 sockaddr* _sa = _salen ? reinterpret_cast<sockaddr*>(&_ss) : NULL; \
140 /* inetAddressToSockaddr always returns an IPv6 sockaddr. Assume that java_fd was created \
141 * by Java API calls, which always create IPv6 socket fds, and pass it in as is. */ \
142 _rc = NET_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ##args, _sa, _salen); \
143 if (_rc == -1 && errno == EAFNOSUPPORT && _salen && isIPv4MappedAddress(_sa)) { \
144 /* We passed in an IPv4 address in an IPv6 sockaddr and the kernel told us that we got \
145 * the address family wrong. Pass in the same address in an IPv4 sockaddr. */ \
146 (jni_env)->ExceptionClear(); \
147 if (!inetAddressToSockaddrVerbatim(jni_env, java_addr, port, _ss, _salen)) { \
148 break; \
149 } \
150 _sa = reinterpret_cast<sockaddr*>(&_ss); \
151 _rc = NET_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ##args, _sa, _salen); \
152 } \
153 } while (0); \
154 _rc; }) \
155
156 /**
157 * Used to retry networking system calls that can be interrupted with a signal. Unlike
158 * TEMP_FAILURE_RETRY, this also handles the case where
159 * AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal a close() or
160 * Thread.interrupt(). Other signals that result in an EINTR result are ignored and the system call
161 * is retried.
162 *
163 * Returns the result of the system call though a Java exception will be pending if the result is
164 * -1: a SocketException if signaled via AsynchronousCloseMonitor, or ErrnoException for other
165 * failures.
166 */
167 #define NET_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \
168 return_type _rc = -1; \
169 int _syscallErrno; \
170 do { \
171 bool _wasSignaled; \
172 { \
173 int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \
174 AsynchronousCloseMonitor _monitor(_fd); \
175 _rc = syscall_name(_fd, __VA_ARGS__); \
176 _syscallErrno = errno; \
177 _wasSignaled = _monitor.wasSignaled(); \
178 } \
179 if (_wasSignaled) { \
180 jniThrowException(jni_env, "java/net/SocketException", "Socket closed"); \
181 _rc = -1; \
182 break; \
183 } \
184 if (_rc == -1 && _syscallErrno != EINTR) { \
185 /* TODO: with a format string we could show the arguments too, like strace(1). */ \
186 throwErrnoException(jni_env, # syscall_name); \
187 break; \
188 } \
189 } while (_rc == -1); /* _syscallErrno == EINTR && !_wasSignaled */ \
190 if (_rc == -1) { \
191 /* If the syscall failed, re-set errno: throwing an exception might have modified it. */ \
192 errno = _syscallErrno; \
193 } \
194 _rc; })
195
196 /**
197 * Used to retry system calls that can be interrupted with a signal. Unlike TEMP_FAILURE_RETRY, this
198 * also handles the case where AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal
199 * a close() or Thread.interrupt(). Other signals that result in an EINTR result are ignored and the
200 * system call is retried.
201 *
202 * Returns the result of the system call though a Java exception will be pending if the result is
203 * -1: an IOException if the file descriptor is already closed, a InterruptedIOException if signaled
204 * via AsynchronousCloseMonitor, or ErrnoException for other failures.
205 */
206 #define IO_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \
207 return_type _rc = -1; \
208 int _syscallErrno; \
209 do { \
210 bool _wasSignaled; \
211 { \
212 int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \
213 AsynchronousCloseMonitor _monitor(_fd); \
214 _rc = syscall_name(_fd, __VA_ARGS__); \
215 _syscallErrno = errno; \
216 _wasSignaled = _monitor.wasSignaled(); \
217 } \
218 if (_wasSignaled) { \
219 jniThrowException(jni_env, "java/io/InterruptedIOException", \
220 # syscall_name " interrupted by close() on another thread"); \
221 _rc = -1; \
222 break; \
223 } \
224 if (_rc == -1 && _syscallErrno != EINTR) { \
225 /* TODO: with a format string we could show the arguments too, like strace(1). */ \
226 throwErrnoException(jni_env, # syscall_name); \
227 break; \
228 } \
229 } while (_rc == -1); /* && _syscallErrno == EINTR && !_wasSignaled */ \
230 if (_rc == -1) { \
231 /* If the syscall failed, re-set errno: throwing an exception might have modified it. */ \
232 errno = _syscallErrno; \
233 } \
234 _rc; })
235
236 #define NULL_ADDR_OK true
237 #define NULL_ADDR_FORBIDDEN false
238
throwException(JNIEnv * env,jclass exceptionClass,jmethodID ctor3,jmethodID ctor2,const char * functionName,int error)239 static void throwException(JNIEnv* env, jclass exceptionClass, jmethodID ctor3, jmethodID ctor2,
240 const char* functionName, int error) {
241 jthrowable cause = NULL;
242 if (env->ExceptionCheck()) {
243 cause = env->ExceptionOccurred();
244 env->ExceptionClear();
245 }
246
247 ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName));
248 if (detailMessage.get() == NULL) {
249 // Not really much we can do here. We're probably dead in the water,
250 // but let's try to stumble on...
251 env->ExceptionClear();
252 }
253
254 jobject exception;
255 if (cause != NULL) {
256 exception = env->NewObject(exceptionClass, ctor3, detailMessage.get(), error, cause);
257 } else {
258 exception = env->NewObject(exceptionClass, ctor2, detailMessage.get(), error);
259 }
260 env->Throw(reinterpret_cast<jthrowable>(exception));
261 }
262
throwErrnoException(JNIEnv * env,const char * functionName)263 static void throwErrnoException(JNIEnv* env, const char* functionName) {
264 int error = errno;
265 jniThrowErrnoException(env, functionName, error);
266 }
267
throwGaiException(JNIEnv * env,const char * functionName,int error)268 static void throwGaiException(JNIEnv* env, const char* functionName, int error) {
269 jclass gaiExceptionClass = JniConstants::GetGaiExceptionClass(env);
270 // Cache the methods ids before we throw, so we don't call GetMethodID with a pending exception.
271 static jmethodID ctor3 = env->GetMethodID(gaiExceptionClass, "<init>",
272 "(Ljava/lang/String;ILjava/lang/Throwable;)V");
273 static jmethodID ctor2 = env->GetMethodID(gaiExceptionClass, "<init>",
274 "(Ljava/lang/String;I)V");
275 if (errno != 0) {
276 // EAI_SYSTEM should mean "look at errno instead", but both glibc and bionic seem to
277 // mess this up. In particular, if you don't have INTERNET permission, errno will be EACCES
278 // but you'll get EAI_NONAME or EAI_NODATA. So we want our GaiException to have a
279 // potentially-relevant ErrnoException as its cause even if error != EAI_SYSTEM.
280 // http://code.google.com/p/android/issues/detail?id=15722
281 throwErrnoException(env, functionName);
282 // Deliberately fall through to throw another exception...
283 }
284 throwException(env, gaiExceptionClass, ctor3, ctor2, functionName, error);
285 }
286
287 template <typename rc_t>
throwIfMinusOne(JNIEnv * env,const char * name,rc_t rc)288 static rc_t throwIfMinusOne(JNIEnv* env, const char* name, rc_t rc) {
289 if (rc == rc_t(-1)) {
290 throwErrnoException(env, name);
291 }
292 return rc;
293 }
294
295 template <typename ScopedT>
296 class IoVec {
297 public:
IoVec(JNIEnv * env,size_t bufferCount)298 IoVec(JNIEnv* env, size_t bufferCount) : mEnv(env), mBufferCount(bufferCount) {
299 }
300
init(jobjectArray javaBuffers,jintArray javaOffsets,jintArray javaByteCounts)301 bool init(jobjectArray javaBuffers, jintArray javaOffsets, jintArray javaByteCounts) {
302 // We can't delete our local references until after the I/O, so make sure we have room.
303 if (mEnv->PushLocalFrame(mBufferCount + 16) < 0) {
304 return false;
305 }
306 ScopedIntArrayRO offsets(mEnv, javaOffsets);
307 if (offsets.get() == NULL) {
308 return false;
309 }
310 ScopedIntArrayRO byteCounts(mEnv, javaByteCounts);
311 if (byteCounts.get() == NULL) {
312 return false;
313 }
314 // TODO: Linux actually has a 1024 buffer limit. glibc works around this, and we should too.
315 // TODO: you can query the limit at runtime with sysconf(_SC_IOV_MAX).
316 for (size_t i = 0; i < mBufferCount; ++i) {
317 jobject buffer = mEnv->GetObjectArrayElement(javaBuffers, i); // We keep this local ref.
318 mScopedBuffers.push_back(new ScopedT(mEnv, buffer));
319 jbyte* ptr = const_cast<jbyte*>(mScopedBuffers.back()->get());
320 if (ptr == NULL) {
321 return false;
322 }
323 struct iovec iov;
324 iov.iov_base = reinterpret_cast<void*>(ptr + offsets[i]);
325 iov.iov_len = byteCounts[i];
326 mIoVec.push_back(iov);
327 }
328 return true;
329 }
330
~IoVec()331 ~IoVec() {
332 for (size_t i = 0; i < mScopedBuffers.size(); ++i) {
333 delete mScopedBuffers[i];
334 }
335 mEnv->PopLocalFrame(NULL);
336 }
337
get()338 iovec* get() {
339 return &mIoVec[0];
340 }
341
size()342 size_t size() {
343 return mBufferCount;
344 }
345
346 private:
347 JNIEnv* mEnv;
348 size_t mBufferCount;
349 std::vector<iovec> mIoVec;
350 std::vector<ScopedT*> mScopedBuffers;
351 };
352
createFileDescriptorIfOpen(JNIEnv * env,int fd)353 static jobject createFileDescriptorIfOpen(JNIEnv* env, int fd) {
354 if (fd == -1) {
355 return NULL;
356 }
357 jobject jifd = jniCreateFileDescriptor(env, fd);
358 if (jifd == NULL) {
359 // OOME prevented allocation of j.i.FileDescriptor instance, close fd to avoid leak.
360 close(fd);
361 }
362 return jifd;
363 }
364
365 /**
366 * Returns a jbyteArray containing the sockaddr_un.sun_path from ss. As per unix(7) sa_len should be
367 * the length of ss as returned by getsockname(2), getpeername(2), or accept(2).
368 * If the returned array is of length 0 the sockaddr_un refers to an unnamed socket.
369 * A null pointer is returned in the event of an error. See unix(7) for more information.
370 */
getUnixSocketPath(JNIEnv * env,const sockaddr_storage & ss,const socklen_t & sa_len)371 static jbyteArray getUnixSocketPath(JNIEnv* env, const sockaddr_storage& ss,
372 const socklen_t& sa_len) {
373 if (ss.ss_family != AF_UNIX) {
374 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
375 "getUnixSocketPath unsupported ss_family: %i", ss.ss_family);
376 return NULL;
377 }
378
379 const struct sockaddr_un* un_addr = reinterpret_cast<const struct sockaddr_un*>(&ss);
380 // The length of sun_path is sa_len minus the length of the overhead (ss_family).
381 // See unix(7) for details. This calculation must match that of socket_make_sockaddr_un() in
382 // socket_local_client.c and javaUnixSocketAddressToSockaddr() to interoperate.
383 size_t pathLength = sa_len - offsetof(struct sockaddr_un, sun_path);
384
385 jbyteArray javaSunPath = env->NewByteArray(pathLength);
386 if (javaSunPath == NULL) {
387 return NULL;
388 }
389
390 if (pathLength > 0) {
391 env->SetByteArrayRegion(javaSunPath, 0, pathLength,
392 reinterpret_cast<const jbyte*>(&un_addr->sun_path));
393 }
394 return javaSunPath;
395 }
396
makeSocketAddress(JNIEnv * env,const sockaddr_storage & ss,const socklen_t sa_len)397 static jobject makeSocketAddress(JNIEnv* env, const sockaddr_storage& ss, const socklen_t sa_len) {
398 if (ss.ss_family == AF_INET || ss.ss_family == AF_INET6) {
399 jint port;
400 jobject inetAddress = sockaddrToInetAddress(env, reinterpret_cast<const sockaddr*>(&ss), &port);
401 if (inetAddress == NULL) {
402 return NULL; // Exception already thrown.
403 }
404 static jmethodID ctor = env->GetMethodID(JniConstants::GetInetSocketAddressClass(env),
405 "<init>", "(Ljava/net/InetAddress;I)V");
406 if (ctor == NULL) {
407 return NULL;
408 }
409 return env->NewObject(JniConstants::GetInetSocketAddressClass(env), ctor, inetAddress, port);
410 } else if (ss.ss_family == AF_UNIX) {
411 static jmethodID ctor = env->GetMethodID(JniConstants::GetUnixSocketAddressClass(env),
412 "<init>", "([B)V");
413 if (ctor == NULL) {
414 return NULL;
415 }
416 jbyteArray javaSunPath = getUnixSocketPath(env, ss, sa_len);
417 if (!javaSunPath) {
418 return NULL;
419 }
420 return env->NewObject(JniConstants::GetUnixSocketAddressClass(env), ctor, javaSunPath);
421 } else if (ss.ss_family == AF_NETLINK) {
422 const struct sockaddr_nl* nl_addr = reinterpret_cast<const struct sockaddr_nl*>(&ss);
423 static jmethodID ctor = env->GetMethodID(JniConstants::GetNetlinkSocketAddressClass(env),
424 "<init>", "(II)V");
425 if (ctor == NULL) {
426 return NULL;
427 }
428 return env->NewObject(JniConstants::GetNetlinkSocketAddressClass(env), ctor,
429 static_cast<jint>(nl_addr->nl_pid),
430 static_cast<jint>(nl_addr->nl_groups));
431 } else if (ss.ss_family == AF_PACKET) {
432 const struct sockaddr_ll* sll = reinterpret_cast<const struct sockaddr_ll*>(&ss);
433 static jmethodID ctor = env->GetMethodID(JniConstants::GetPacketSocketAddressClass(env),
434 "<init>", "(IIII[B)V");
435 if (ctor == NULL) {
436 return NULL;
437 }
438 ScopedLocalRef<jbyteArray> byteArray(env, env->NewByteArray(sll->sll_halen));
439 if (byteArray.get() == NULL) {
440 return NULL;
441 }
442 env->SetByteArrayRegion(byteArray.get(), 0, sll->sll_halen,
443 reinterpret_cast<const jbyte*>(sll->sll_addr));
444 jobject packetSocketAddress = env->NewObject(JniConstants::GetPacketSocketAddressClass(env), ctor,
445 static_cast<jint>(ntohs(sll->sll_protocol)),
446 static_cast<jint>(sll->sll_ifindex),
447 static_cast<jint>(sll->sll_hatype),
448 static_cast<jint>(sll->sll_pkttype),
449 byteArray.get());
450 return packetSocketAddress;
451 }
452 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException", "unsupported ss_family: %d",
453 ss.ss_family);
454 return NULL;
455 }
456
makeStructPasswd(JNIEnv * env,const struct passwd & pw)457 static jobject makeStructPasswd(JNIEnv* env, const struct passwd& pw) {
458 TO_JAVA_STRING(pw_name, pw.pw_name);
459 TO_JAVA_STRING(pw_dir, pw.pw_dir);
460 TO_JAVA_STRING(pw_shell, pw.pw_shell);
461 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructPasswdClass(env), "<init>",
462 "(Ljava/lang/String;IILjava/lang/String;Ljava/lang/String;)V");
463 if (ctor == NULL) {
464 return NULL;
465 }
466 return env->NewObject(JniConstants::GetStructPasswdClass(env), ctor,
467 pw_name, static_cast<jint>(pw.pw_uid), static_cast<jint>(pw.pw_gid), pw_dir, pw_shell);
468 }
469
makeStructTimespec(JNIEnv * env,const struct timespec & ts)470 static jobject makeStructTimespec(JNIEnv* env, const struct timespec& ts) {
471 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructTimespecClass(env), "<init>",
472 "(JJ)V");
473 if (ctor == NULL) {
474 return NULL;
475 }
476 return env->NewObject(JniConstants::GetStructTimespecClass(env), ctor,
477 static_cast<jlong>(ts.tv_sec), static_cast<jlong>(ts.tv_nsec));
478 }
479
makeStructStat(JNIEnv * env,const struct stat64 & sb)480 static jobject makeStructStat(JNIEnv* env, const struct stat64& sb) {
481 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructStatClass(env), "<init>",
482 "(JJIJIIJJLandroid/system/StructTimespec;Landroid/system/StructTimespec;Landroid/system/StructTimespec;JJ)V");
483 if (ctor == NULL) {
484 return NULL;
485 }
486
487 jobject atim_timespec = makeStructTimespec(env, sb.st_atim);
488 if (atim_timespec == NULL) {
489 return NULL;
490 }
491 jobject mtim_timespec = makeStructTimespec(env, sb.st_mtim);
492 if (mtim_timespec == NULL) {
493 return NULL;
494 }
495 jobject ctim_timespec = makeStructTimespec(env, sb.st_ctim);
496 if (ctim_timespec == NULL) {
497 return NULL;
498 }
499
500 return env->NewObject(JniConstants::GetStructStatClass(env), ctor,
501 static_cast<jlong>(sb.st_dev), static_cast<jlong>(sb.st_ino),
502 static_cast<jint>(sb.st_mode), static_cast<jlong>(sb.st_nlink),
503 static_cast<jint>(sb.st_uid), static_cast<jint>(sb.st_gid),
504 static_cast<jlong>(sb.st_rdev), static_cast<jlong>(sb.st_size),
505 atim_timespec, mtim_timespec, ctim_timespec,
506 static_cast<jlong>(sb.st_blksize), static_cast<jlong>(sb.st_blocks));
507 }
508
makeStructStatVfs(JNIEnv * env,const struct statvfs & sb)509 static jobject makeStructStatVfs(JNIEnv* env, const struct statvfs& sb) {
510 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructStatVfsClass(env), "<init>",
511 "(JJJJJJJJJJJ)V");
512 if (ctor == NULL) {
513 return NULL;
514 }
515
516 return env->NewObject(JniConstants::GetStructStatVfsClass(env), ctor,
517 static_cast<jlong>(sb.f_bsize),
518 static_cast<jlong>(sb.f_frsize),
519 static_cast<jlong>(sb.f_blocks),
520 static_cast<jlong>(sb.f_bfree),
521 static_cast<jlong>(sb.f_bavail),
522 static_cast<jlong>(sb.f_files),
523 static_cast<jlong>(sb.f_ffree),
524 static_cast<jlong>(sb.f_favail),
525 static_cast<jlong>(sb.f_fsid),
526 static_cast<jlong>(sb.f_flag),
527 static_cast<jlong>(sb.f_namemax));
528 }
529
makeStructLinger(JNIEnv * env,const struct linger & l)530 static jobject makeStructLinger(JNIEnv* env, const struct linger& l) {
531 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructLingerClass(env), "<init>", "(II)V");
532 if (ctor == NULL) {
533 return NULL;
534 }
535 return env->NewObject(JniConstants::GetStructLingerClass(env), ctor, l.l_onoff, l.l_linger);
536 }
537
makeStructTimeval(JNIEnv * env,const struct timeval & tv)538 static jobject makeStructTimeval(JNIEnv* env, const struct timeval& tv) {
539 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructTimevalClass(env), "<init>", "(JJ)V");
540 if (ctor == NULL) {
541 return NULL;
542 }
543 return env->NewObject(JniConstants::GetStructTimevalClass(env), ctor,
544 static_cast<jlong>(tv.tv_sec), static_cast<jlong>(tv.tv_usec));
545 }
546
makeStructUcred(JNIEnv * env,const struct ucred & u __unused)547 static jobject makeStructUcred(JNIEnv* env, const struct ucred& u __unused) {
548 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructUcredClass(env), "<init>", "(III)V");
549 if (ctor == NULL) {
550 return NULL;
551 }
552 return env->NewObject(JniConstants::GetStructUcredClass(env), ctor, u.pid, u.uid, u.gid);
553 }
554
makeStructUtsname(JNIEnv * env,const struct utsname & buf)555 static jobject makeStructUtsname(JNIEnv* env, const struct utsname& buf) {
556 TO_JAVA_STRING(sysname, buf.sysname);
557 TO_JAVA_STRING(nodename, buf.nodename);
558 TO_JAVA_STRING(release, buf.release);
559 TO_JAVA_STRING(version, buf.version);
560 TO_JAVA_STRING(machine, buf.machine);
561 static jmethodID ctor = env->GetMethodID(JniConstants::GetStructUtsnameClass(env), "<init>",
562 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
563 if (ctor == NULL) {
564 return NULL;
565 }
566 return env->NewObject(JniConstants::GetStructUtsnameClass(env), ctor,
567 sysname, nodename, release, version, machine);
568 };
569
fillIfreq(JNIEnv * env,jstring javaInterfaceName,struct ifreq & req)570 static bool fillIfreq(JNIEnv* env, jstring javaInterfaceName, struct ifreq& req) {
571 ScopedUtfChars interfaceName(env, javaInterfaceName);
572 if (interfaceName.c_str() == NULL) {
573 return false;
574 }
575 memset(&req, 0, sizeof(req));
576 strncpy(req.ifr_name, interfaceName.c_str(), sizeof(req.ifr_name));
577 req.ifr_name[sizeof(req.ifr_name) - 1] = '\0';
578 return true;
579 }
580
fillUnixSocketAddress(JNIEnv * env,jobject javaUnixSocketAddress,const sockaddr_storage & ss,const socklen_t & sa_len)581 static bool fillUnixSocketAddress(JNIEnv* env, jobject javaUnixSocketAddress,
582 const sockaddr_storage& ss, const socklen_t& sa_len) {
583 if (javaUnixSocketAddress == NULL) {
584 return true;
585 }
586 jbyteArray javaSunPath = getUnixSocketPath(env, ss, sa_len);
587 if (!javaSunPath) {
588 return false;
589 }
590
591 static jfieldID sunPathFid =
592 env->GetFieldID(JniConstants::GetUnixSocketAddressClass(env), "sun_path", "[B");
593 env->SetObjectField(javaUnixSocketAddress, sunPathFid, javaSunPath);
594 return true;
595 }
596
fillInetSocketAddress(JNIEnv * env,jobject javaInetSocketAddress,const sockaddr_storage & ss)597 static bool fillInetSocketAddress(JNIEnv* env, jobject javaInetSocketAddress,
598 const sockaddr_storage& ss) {
599 if (javaInetSocketAddress == NULL) {
600 return true;
601 }
602 // Fill out the passed-in InetSocketAddress with the sender's IP address and port number.
603 jint port;
604 jobject sender = sockaddrToInetAddress(env, reinterpret_cast<const sockaddr*>(&ss), &port);
605 if (sender == NULL) {
606 return false;
607 }
608 static jfieldID holderFid = env->GetFieldID(JniConstants::GetInetSocketAddressClass(env), "holder",
609 "Ljava/net/InetSocketAddress$InetSocketAddressHolder;");
610 jobject holder = env->GetObjectField(javaInetSocketAddress, holderFid);
611
612 static jfieldID addressFid = env->GetFieldID(JniConstants::GetInetSocketAddressHolderClass(env),
613 "addr", "Ljava/net/InetAddress;");
614 static jfieldID portFid = env->GetFieldID(JniConstants::GetInetSocketAddressHolderClass(env), "port", "I");
615 env->SetObjectField(holder, addressFid, sender);
616 env->SetIntField(holder, portFid, port);
617 return true;
618 }
619
620 #if __has_include(<linux/vm_sockets.h>)
fillVmSocketAddress(JNIEnv * env,jobject javaVmSocketAddress,const sockaddr_storage & ss)621 static bool fillVmSocketAddress(JNIEnv* env, jobject javaVmSocketAddress,
622 const sockaddr_storage& ss) {
623 static jfieldID portFid = env->GetFieldID(
624 JniConstants::GetVmSocketAddressClass(env), "svmPort", "I");
625 static jfieldID cidFid = env->GetFieldID(
626 JniConstants::GetVmSocketAddressClass(env), "svmCid", "I");
627
628 if (javaVmSocketAddress == NULL) {
629 return true;
630 }
631
632 if (ss.ss_family != AF_VSOCK) {
633 return false;
634 }
635
636 const sockaddr_vm& svm = reinterpret_cast<const sockaddr_vm&>(ss);
637 env->SetIntField(javaVmSocketAddress, portFid, svm.svm_port);
638 env->SetIntField(javaVmSocketAddress, cidFid, svm.svm_cid);
639
640 return true;
641 }
642 #endif
643
fillSocketAddress(JNIEnv * env,jobject javaSocketAddress,const sockaddr_storage & ss,const socklen_t & sa_len)644 static bool fillSocketAddress(JNIEnv* env, jobject javaSocketAddress, const sockaddr_storage& ss,
645 const socklen_t& sa_len) {
646 if (javaSocketAddress == NULL) {
647 return true;
648 }
649
650 if (env->IsInstanceOf(javaSocketAddress, JniConstants::GetInetSocketAddressClass(env))) {
651 return fillInetSocketAddress(env, javaSocketAddress, ss);
652 } else if (env->IsInstanceOf(javaSocketAddress, JniConstants::GetUnixSocketAddressClass(env))) {
653 return fillUnixSocketAddress(env, javaSocketAddress, ss, sa_len);
654 #if __has_include(<linux/vm_sockets.h>)
655 } else if (env->IsInstanceOf(javaSocketAddress, JniConstants::GetVmSocketAddressClass(env))) {
656 return fillVmSocketAddress(env, javaSocketAddress, ss);
657 #endif
658 }
659 jniThrowException(env, "java/lang/UnsupportedOperationException",
660 "unsupported SocketAddress subclass");
661 return false;
662
663 }
664
javaInetSocketAddressToInetAddressAndPort(JNIEnv * env,jobject javaInetSocketAddress,jobject & javaInetAddress,jint & port)665 static void javaInetSocketAddressToInetAddressAndPort(
666 JNIEnv* env, jobject javaInetSocketAddress, jobject& javaInetAddress, jint& port) {
667 static jfieldID holderFid = env->GetFieldID(JniConstants::GetInetSocketAddressClass(env), "holder",
668 "Ljava/net/InetSocketAddress$InetSocketAddressHolder;");
669 jobject holder = env->GetObjectField(javaInetSocketAddress, holderFid);
670
671 static jfieldID addressFid = env->GetFieldID(
672 JniConstants::GetInetSocketAddressHolderClass(env), "addr", "Ljava/net/InetAddress;");
673 static jfieldID portFid = env->GetFieldID(JniConstants::GetInetSocketAddressHolderClass(env), "port", "I");
674
675 javaInetAddress = env->GetObjectField(holder, addressFid);
676 port = env->GetIntField(holder, portFid);
677 }
678
javaInetSocketAddressToSockaddr(JNIEnv * env,jobject javaSocketAddress,sockaddr_storage & ss,socklen_t & sa_len)679 static bool javaInetSocketAddressToSockaddr(
680 JNIEnv* env, jobject javaSocketAddress, sockaddr_storage& ss, socklen_t& sa_len) {
681 jobject javaInetAddress;
682 jint port;
683 javaInetSocketAddressToInetAddressAndPort(env, javaSocketAddress, javaInetAddress, port);
684 return inetAddressToSockaddr(env, javaInetAddress, port, ss, sa_len);
685 }
686
javaNetlinkSocketAddressToSockaddr(JNIEnv * env,jobject javaSocketAddress,sockaddr_storage & ss,socklen_t & sa_len)687 static bool javaNetlinkSocketAddressToSockaddr(
688 JNIEnv* env, jobject javaSocketAddress, sockaddr_storage& ss, socklen_t& sa_len) {
689 static jfieldID nlPidFid = env->GetFieldID(
690 JniConstants::GetNetlinkSocketAddressClass(env), "nlPortId", "I");
691 static jfieldID nlGroupsFid = env->GetFieldID(
692 JniConstants::GetNetlinkSocketAddressClass(env), "nlGroupsMask", "I");
693
694 sockaddr_nl *nlAddr = reinterpret_cast<sockaddr_nl *>(&ss);
695 nlAddr->nl_family = AF_NETLINK;
696 nlAddr->nl_pid = env->GetIntField(javaSocketAddress, nlPidFid);
697 nlAddr->nl_groups = env->GetIntField(javaSocketAddress, nlGroupsFid);
698 sa_len = sizeof(sockaddr_nl);
699 return true;
700 }
701
javaUnixSocketAddressToSockaddr(JNIEnv * env,jobject javaUnixSocketAddress,sockaddr_storage & ss,socklen_t & sa_len)702 static bool javaUnixSocketAddressToSockaddr(
703 JNIEnv* env, jobject javaUnixSocketAddress, sockaddr_storage& ss, socklen_t& sa_len) {
704 static jfieldID sunPathFid = env->GetFieldID(
705 JniConstants::GetUnixSocketAddressClass(env), "sun_path", "[B");
706
707 struct sockaddr_un* un_addr = reinterpret_cast<struct sockaddr_un*>(&ss);
708 memset (un_addr, 0, sizeof(sockaddr_un));
709 un_addr->sun_family = AF_UNIX;
710
711 jbyteArray javaSunPath = (jbyteArray) env->GetObjectField(javaUnixSocketAddress, sunPathFid);
712 jsize pathLength = env->GetArrayLength(javaSunPath);
713 if ((size_t) pathLength > sizeof(sockaddr_un::sun_path)) {
714 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
715 "sun_path too long: max=%i, is=%i",
716 sizeof(sockaddr_un::sun_path), pathLength);
717 return false;
718 }
719 env->GetByteArrayRegion(javaSunPath, 0, pathLength, (jbyte*) un_addr->sun_path);
720 // sa_len is sun_path plus the length of the overhead (ss_family_t). See unix(7) for
721 // details. This calculation must match that of socket_make_sockaddr_un() in
722 // socket_local_client.c and getUnixSocketPath() to interoperate.
723 sa_len = offsetof(struct sockaddr_un, sun_path) + pathLength;
724 return true;
725 }
726
javaPacketSocketAddressToSockaddr(JNIEnv * env,jobject javaSocketAddress,sockaddr_storage & ss,socklen_t & sa_len)727 static bool javaPacketSocketAddressToSockaddr(
728 JNIEnv* env, jobject javaSocketAddress, sockaddr_storage& ss, socklen_t& sa_len) {
729 static jfieldID protocolFid = env->GetFieldID(
730 JniConstants::GetPacketSocketAddressClass(env), "sll_protocol", "I");
731 static jfieldID ifindexFid = env->GetFieldID(
732 JniConstants::GetPacketSocketAddressClass(env), "sll_ifindex", "I");
733 static jfieldID hatypeFid = env->GetFieldID(
734 JniConstants::GetPacketSocketAddressClass(env), "sll_hatype", "I");
735 static jfieldID pkttypeFid = env->GetFieldID(
736 JniConstants::GetPacketSocketAddressClass(env), "sll_pkttype", "I");
737 static jfieldID addrFid = env->GetFieldID(
738 JniConstants::GetPacketSocketAddressClass(env), "sll_addr", "[B");
739
740 sockaddr_ll *sll = reinterpret_cast<sockaddr_ll *>(&ss);
741 sll->sll_family = AF_PACKET;
742 sll->sll_protocol = htons(env->GetIntField(javaSocketAddress, protocolFid));
743 sll->sll_ifindex = env->GetIntField(javaSocketAddress, ifindexFid);
744 sll->sll_hatype = env->GetIntField(javaSocketAddress, hatypeFid);
745 sll->sll_pkttype = env->GetIntField(javaSocketAddress, pkttypeFid);
746
747 jbyteArray sllAddr = (jbyteArray) env->GetObjectField(javaSocketAddress, addrFid);
748 if (sllAddr == NULL) {
749 sll->sll_halen = 0;
750 memset(&sll->sll_addr, 0, sizeof(sll->sll_addr));
751 } else {
752 jsize len = env->GetArrayLength(sllAddr);
753 if ((size_t) len > sizeof(sll->sll_addr)) {
754 len = sizeof(sll->sll_addr);
755 }
756 sll->sll_halen = len;
757 env->GetByteArrayRegion(sllAddr, 0, len, (jbyte*) sll->sll_addr);
758 }
759 sa_len = sizeof(sockaddr_ll);
760 return true;
761 }
762
763 #if __has_include(<linux/vm_sockets.h>)
javaVmSocketAddressToSockaddr(JNIEnv * env,jobject javaSocketAddress,sockaddr_storage & ss,socklen_t & sa_len)764 static bool javaVmSocketAddressToSockaddr(
765 JNIEnv* env, jobject javaSocketAddress, sockaddr_storage& ss, socklen_t& sa_len) {
766 static jfieldID portFid = env->GetFieldID(
767 JniConstants::GetVmSocketAddressClass(env), "svmPort", "I");
768 static jfieldID cidFid = env->GetFieldID(
769 JniConstants::GetVmSocketAddressClass(env), "svmCid", "I");
770
771 sockaddr_vm& svm = reinterpret_cast<sockaddr_vm&>(ss);
772 svm.svm_family = AF_VSOCK;
773 svm.svm_port = env->GetIntField(javaSocketAddress, portFid);
774 svm.svm_cid = env->GetIntField(javaSocketAddress, cidFid);
775
776 sa_len = sizeof(svm);
777 return true;
778 }
779 #endif
780
javaSocketAddressToSockaddr(JNIEnv * env,jobject javaSocketAddress,sockaddr_storage & ss,socklen_t & sa_len)781 static bool javaSocketAddressToSockaddr(
782 JNIEnv* env, jobject javaSocketAddress, sockaddr_storage& ss, socklen_t& sa_len) {
783 if (javaSocketAddress == NULL) {
784 jniThrowNullPointerException(env, NULL);
785 return false;
786 }
787
788 if (env->IsInstanceOf(javaSocketAddress, JniConstants::GetNetlinkSocketAddressClass(env))) {
789 return javaNetlinkSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len);
790 } else if (env->IsInstanceOf(javaSocketAddress, JniConstants::GetInetSocketAddressClass(env))) {
791 return javaInetSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len);
792 } else if (env->IsInstanceOf(javaSocketAddress, JniConstants::GetPacketSocketAddressClass(env))) {
793 return javaPacketSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len);
794 } else if (env->IsInstanceOf(javaSocketAddress, JniConstants::GetUnixSocketAddressClass(env))) {
795 return javaUnixSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len);
796 #if __has_include(<linux/vm_sockets.h>)
797 } else if (env->IsInstanceOf(javaSocketAddress,
798 JniConstants::GetVmSocketAddressClass(env))) {
799 return javaVmSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len);
800 #endif
801 }
802 jniThrowException(env, "java/lang/UnsupportedOperationException",
803 "unsupported SocketAddress subclass");
804 return false;
805 }
806
doStat(JNIEnv * env,jstring javaPath,bool isLstat)807 static jobject doStat(JNIEnv* env, jstring javaPath, bool isLstat) {
808 ScopedUtfChars path(env, javaPath);
809 if (path.c_str() == NULL) {
810 return NULL;
811 }
812 struct stat64 sb;
813 int rc = isLstat ? TEMP_FAILURE_RETRY(lstat64(path.c_str(), &sb))
814 : TEMP_FAILURE_RETRY(stat64(path.c_str(), &sb));
815 if (rc == -1) {
816 throwErrnoException(env, isLstat ? "lstat" : "stat");
817 return NULL;
818 }
819 return makeStructStat(env, sb);
820 }
821
doGetSockName(JNIEnv * env,jobject javaFd,bool is_sockname)822 static jobject doGetSockName(JNIEnv* env, jobject javaFd, bool is_sockname) {
823 int fd = jniGetFDFromFileDescriptor(env, javaFd);
824 sockaddr_storage ss;
825 sockaddr* sa = reinterpret_cast<sockaddr*>(&ss);
826 socklen_t byteCount = sizeof(ss);
827 memset(&ss, 0, byteCount);
828 int rc = is_sockname ? TEMP_FAILURE_RETRY(getsockname(fd, sa, &byteCount))
829 : TEMP_FAILURE_RETRY(getpeername(fd, sa, &byteCount));
830 if (rc == -1) {
831 throwErrnoException(env, is_sockname ? "getsockname" : "getpeername");
832 return NULL;
833 }
834 return makeSocketAddress(env, ss, byteCount);
835 }
836
837 class Passwd {
838 public:
Passwd(JNIEnv * env)839 explicit Passwd(JNIEnv* env) : mEnv(env), mResult(NULL) {
840 long bufferSize = sysconf(_SC_GETPW_R_SIZE_MAX);
841 if (bufferSize > 0) {
842 mBufferSize = bufferSize;
843 } else {
844 mBufferSize = 1024;
845 }
846 mBuffer.reset(new char[mBufferSize]);
847 }
848
getpwnam(const char * name)849 jobject getpwnam(const char* name) {
850 return process("getpwnam_r", getpwnam_r(name, &mPwd, mBuffer.get(), mBufferSize, &mResult));
851 }
852
getpwuid(uid_t uid)853 jobject getpwuid(uid_t uid) {
854 return process("getpwuid_r", getpwuid_r(uid, &mPwd, mBuffer.get(), mBufferSize, &mResult));
855 }
856
get()857 struct passwd* get() {
858 return mResult;
859 }
860
861 private:
process(const char * syscall,int error)862 jobject process(const char* syscall, int error) {
863 if (mResult == NULL) {
864 errno = error;
865 throwErrnoException(mEnv, syscall);
866 return NULL;
867 }
868 return makeStructPasswd(mEnv, *mResult);
869 }
870
871 JNIEnv* mEnv;
872 std::unique_ptr<char[]> mBuffer;
873 size_t mBufferSize;
874 struct passwd mPwd;
875 struct passwd* mResult;
876 };
877
AssertException(JNIEnv * env)878 static void AssertException(JNIEnv* env) {
879 if (env->ExceptionCheck() == JNI_FALSE) {
880 env->FatalError("Expected exception");
881 }
882 }
883
884 // Note for capabilities functions:
885 // We assume the calls are rare enough that it does not make sense to cache class objects. The
886 // advantage is lower maintenance burden.
887
ReadStructCapUserHeader(JNIEnv * env,jobject java_header,__user_cap_header_struct * c_header)888 static bool ReadStructCapUserHeader(
889 JNIEnv* env, jobject java_header, __user_cap_header_struct* c_header) {
890 if (java_header == nullptr) {
891 jniThrowNullPointerException(env, "header is null");
892 return false;
893 }
894
895 ScopedLocalRef<jclass> header_class(env, env->FindClass("android/system/StructCapUserHeader"));
896 if (header_class.get() == nullptr) {
897 return false;
898 }
899
900 {
901 static jfieldID version_fid = env->GetFieldID(header_class.get(), "version", "I");
902 if (version_fid == nullptr) {
903 return false;
904 }
905 c_header->version = env->GetIntField(java_header, version_fid);
906 }
907
908 {
909 static jfieldID pid_fid = env->GetFieldID(header_class.get(), "pid", "I");
910 if (pid_fid == nullptr) {
911 return false;
912 }
913 c_header->pid = env->GetIntField(java_header, pid_fid);
914 }
915
916 return true;
917 }
918
SetStructCapUserHeaderVersion(JNIEnv * env,jobject java_header,__user_cap_header_struct * c_header)919 static void SetStructCapUserHeaderVersion(
920 JNIEnv* env, jobject java_header, __user_cap_header_struct* c_header) {
921 ScopedLocalRef<jclass> header_class(env, env->FindClass("android/system/StructCapUserHeader"));
922 if (header_class.get() == nullptr) {
923 env->ExceptionClear();
924 return;
925 }
926
927 static jfieldID version_fid = env->GetFieldID(header_class.get(), "version", "I");
928 if (version_fid == nullptr) {
929 env->ExceptionClear();
930 return;
931 }
932 env->SetIntField(java_header, version_fid, c_header->version);
933 }
934
CreateStructCapUserData(JNIEnv * env,jclass data_class,__user_cap_data_struct * c_data)935 static jobject CreateStructCapUserData(
936 JNIEnv* env, jclass data_class, __user_cap_data_struct* c_data) {
937 if (c_data == nullptr) {
938 // Should not happen.
939 jniThrowNullPointerException(env, "data is null");
940 return nullptr;
941 }
942
943 static jmethodID data_cons = env->GetMethodID(data_class, "<init>", "(III)V");
944 if (data_cons == nullptr) {
945 return nullptr;
946 }
947
948 jint e = static_cast<jint>(c_data->effective);
949 jint p = static_cast<jint>(c_data->permitted);
950 jint i = static_cast<jint>(c_data->inheritable);
951 return env->NewObject(data_class, data_cons, e, p, i);
952 }
953
ReadStructCapUserData(JNIEnv * env,jobject java_data,__user_cap_data_struct * c_data)954 static bool ReadStructCapUserData(JNIEnv* env, jobject java_data, __user_cap_data_struct* c_data) {
955 if (java_data == nullptr) {
956 jniThrowNullPointerException(env, "data is null");
957 return false;
958 }
959
960 ScopedLocalRef<jclass> data_class(env, env->FindClass("android/system/StructCapUserData"));
961 if (data_class.get() == nullptr) {
962 return false;
963 }
964
965 {
966 static jfieldID effective_fid = env->GetFieldID(data_class.get(), "effective", "I");
967 if (effective_fid == nullptr) {
968 return false;
969 }
970 c_data->effective = env->GetIntField(java_data, effective_fid);
971 }
972
973 {
974 static jfieldID permitted_fid = env->GetFieldID(data_class.get(), "permitted", "I");
975 if (permitted_fid == nullptr) {
976 return false;
977 }
978 c_data->permitted = env->GetIntField(java_data, permitted_fid);
979 }
980
981
982 {
983 static jfieldID inheritable_fid = env->GetFieldID(data_class.get(), "inheritable", "I");
984 if (inheritable_fid == nullptr) {
985 return false;
986 }
987 c_data->inheritable = env->GetIntField(java_data, inheritable_fid);
988 }
989
990 return true;
991 }
992
993 static constexpr size_t kMaxCapUserDataLength = 2U;
994 #ifdef _LINUX_CAPABILITY_VERSION_1
995 static_assert(kMaxCapUserDataLength >= _LINUX_CAPABILITY_U32S_1, "Length too small.");
996 #endif
997 #ifdef _LINUX_CAPABILITY_VERSION_2
998 static_assert(kMaxCapUserDataLength >= _LINUX_CAPABILITY_U32S_2, "Length too small.");
999 #endif
1000 #ifdef _LINUX_CAPABILITY_VERSION_3
1001 static_assert(kMaxCapUserDataLength >= _LINUX_CAPABILITY_U32S_3, "Length too small.");
1002 #endif
1003 #ifdef _LINUX_CAPABILITY_VERSION_4
1004 static_assert(false, "Unsupported capability version, please update.");
1005 #endif
1006
GetCapUserDataLength(uint32_t version)1007 static size_t GetCapUserDataLength(uint32_t version) {
1008 #ifdef _LINUX_CAPABILITY_VERSION_1
1009 if (version == _LINUX_CAPABILITY_VERSION_1) {
1010 return _LINUX_CAPABILITY_U32S_1;
1011 }
1012 #endif
1013 #ifdef _LINUX_CAPABILITY_VERSION_2
1014 if (version == _LINUX_CAPABILITY_VERSION_2) {
1015 return _LINUX_CAPABILITY_U32S_2;
1016 }
1017 #endif
1018 #ifdef _LINUX_CAPABILITY_VERSION_3
1019 if (version == _LINUX_CAPABILITY_VERSION_3) {
1020 return _LINUX_CAPABILITY_U32S_3;
1021 }
1022 #endif
1023 return 0;
1024 }
1025
Linux_accept(JNIEnv * env,jobject,jobject javaFd,jobject javaSocketAddress)1026 static jobject Linux_accept(JNIEnv* env, jobject, jobject javaFd, jobject javaSocketAddress) {
1027 sockaddr_storage ss;
1028 socklen_t sl = sizeof(ss);
1029 memset(&ss, 0, sizeof(ss));
1030 sockaddr* peer = (javaSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL;
1031 socklen_t* peerLength = (javaSocketAddress != NULL) ? &sl : 0;
1032 jint clientFd = NET_FAILURE_RETRY(env, int, accept, javaFd, peer, peerLength);
1033 if (clientFd == -1 || !fillSocketAddress(env, javaSocketAddress, ss, *peerLength)) {
1034 close(clientFd);
1035 return NULL;
1036 }
1037 return createFileDescriptorIfOpen(env, clientFd);
1038 }
1039
Linux_access(JNIEnv * env,jobject,jstring javaPath,jint mode)1040 static jboolean Linux_access(JNIEnv* env, jobject, jstring javaPath, jint mode) {
1041 ScopedUtfChars path(env, javaPath);
1042 if (path.c_str() == NULL) {
1043 return JNI_FALSE;
1044 }
1045 int rc = TEMP_FAILURE_RETRY(access(path.c_str(), mode));
1046 if (rc == -1) {
1047 throwErrnoException(env, "access");
1048 }
1049 return (rc == 0);
1050 }
1051
Linux_bind(JNIEnv * env,jobject,jobject javaFd,jobject javaAddress,jint port)1052 static void Linux_bind(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) {
1053 // We don't need the return value because we'll already have thrown.
1054 (void) NET_IPV4_FALLBACK(env, int, bind, javaFd, javaAddress, port, NULL_ADDR_FORBIDDEN);
1055 }
1056
Linux_bindSocketAddress(JNIEnv * env,jobject thisObj,jobject javaFd,jobject javaSocketAddress)1057 static void Linux_bindSocketAddress(
1058 JNIEnv* env, jobject thisObj, jobject javaFd, jobject javaSocketAddress) {
1059 if (javaSocketAddress != NULL &&
1060 env->IsInstanceOf(javaSocketAddress, JniConstants::GetInetSocketAddressClass(env))) {
1061 // Use the InetAddress version so we get the benefit of NET_IPV4_FALLBACK.
1062 jobject javaInetAddress;
1063 jint port;
1064 javaInetSocketAddressToInetAddressAndPort(env, javaSocketAddress, javaInetAddress, port);
1065 Linux_bind(env, thisObj, javaFd, javaInetAddress, port);
1066 return;
1067 }
1068 sockaddr_storage ss;
1069 socklen_t sa_len;
1070 if (!javaSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len)) {
1071 return; // Exception already thrown.
1072 }
1073
1074 const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss);
1075 // We don't need the return value because we'll already have thrown.
1076 (void) NET_FAILURE_RETRY(env, int, bind, javaFd, sa, sa_len);
1077 }
1078
Linux_capget(JNIEnv * env,jobject,jobject header)1079 static jobjectArray Linux_capget(JNIEnv* env, jobject, jobject header) {
1080 // Convert Java header struct to kernel datastructure.
1081 __user_cap_header_struct cap_header;
1082 if (!ReadStructCapUserHeader(env, header, &cap_header)) {
1083 AssertException(env);
1084 return nullptr;
1085 }
1086
1087 // Call capget.
1088 __user_cap_data_struct cap_data[kMaxCapUserDataLength];
1089 if (capget(&cap_header, &cap_data[0]) == -1) {
1090 // Check for EINVAL. In that case, mutate the header.
1091 if (errno == EINVAL) {
1092 int saved_errno = errno;
1093 SetStructCapUserHeaderVersion(env, header, &cap_header);
1094 errno = saved_errno;
1095 }
1096 throwErrnoException(env, "capget");
1097 return nullptr;
1098 }
1099
1100 // Create the result array.
1101 ScopedLocalRef<jclass> data_class(env, env->FindClass("android/system/StructCapUserData"));
1102 if (data_class.get() == nullptr) {
1103 return nullptr;
1104 }
1105 size_t result_size = GetCapUserDataLength(cap_header.version);
1106 ScopedLocalRef<jobjectArray> result(
1107 env, env->NewObjectArray(result_size, data_class.get(), nullptr));
1108 if (result.get() == nullptr) {
1109 return nullptr;
1110 }
1111 // Translate the values we got.
1112 for (size_t i = 0; i < result_size; ++i) {
1113 ScopedLocalRef<jobject> value(
1114 env, CreateStructCapUserData(env, data_class.get(), &cap_data[i]));
1115 if (value.get() == nullptr) {
1116 AssertException(env);
1117 return nullptr;
1118 }
1119 env->SetObjectArrayElement(result.get(), i, value.get());
1120 }
1121 return result.release();
1122 }
1123
Linux_capset(JNIEnv * env,jobject,jobject header,jobjectArray data)1124 static void Linux_capset(
1125 JNIEnv* env, jobject, jobject header, jobjectArray data) {
1126 // Convert Java header struct to kernel datastructure.
1127 __user_cap_header_struct cap_header;
1128 if (!ReadStructCapUserHeader(env, header, &cap_header)) {
1129 AssertException(env);
1130 return;
1131 }
1132 size_t result_size = GetCapUserDataLength(cap_header.version);
1133 // Ensure that the array has the expected length.
1134 if (env->GetArrayLength(data) != static_cast<jint>(result_size)) {
1135 jniThrowExceptionFmt(env,
1136 "java/lang/IllegalArgumentException",
1137 "Unsupported input length %d (expected %zu)",
1138 env->GetArrayLength(data),
1139 result_size);
1140 return;
1141 }
1142
1143 __user_cap_data_struct cap_data[kMaxCapUserDataLength];
1144 // Translate the values we got.
1145 for (size_t i = 0; i < result_size; ++i) {
1146 ScopedLocalRef<jobject> value(env, env->GetObjectArrayElement(data, i));
1147 if (!ReadStructCapUserData(env, value.get(), &cap_data[i])) {
1148 AssertException(env);
1149 return;
1150 }
1151 }
1152
1153 throwIfMinusOne(env, "capset", capset(&cap_header, &cap_data[0]));
1154 }
1155
Linux_chmod(JNIEnv * env,jobject,jstring javaPath,jint mode)1156 static void Linux_chmod(JNIEnv* env, jobject, jstring javaPath, jint mode) {
1157 ScopedUtfChars path(env, javaPath);
1158 if (path.c_str() == NULL) {
1159 return;
1160 }
1161 throwIfMinusOne(env, "chmod", TEMP_FAILURE_RETRY(chmod(path.c_str(), mode)));
1162 }
1163
Linux_chown(JNIEnv * env,jobject,jstring javaPath,jint uid,jint gid)1164 static void Linux_chown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) {
1165 ScopedUtfChars path(env, javaPath);
1166 if (path.c_str() == NULL) {
1167 return;
1168 }
1169 throwIfMinusOne(env, "chown", TEMP_FAILURE_RETRY(chown(path.c_str(), uid, gid)));
1170 }
1171
Linux_close(JNIEnv * env,jobject,jobject javaFd)1172 static void Linux_close(JNIEnv* env, jobject, jobject javaFd) {
1173 // Get the FileDescriptor's 'fd' field and clear it.
1174 // We need to do this before we can throw an IOException (http://b/3222087).
1175 if (javaFd == nullptr) {
1176 jniThrowNullPointerException(env, "null fd");
1177 return;
1178 }
1179 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1180 jniSetFileDescriptorOfFD(env, javaFd, -1);
1181
1182 #if defined(__BIONIC__)
1183 static jmethodID getOwnerId = env->GetMethodID(JniConstants::GetFileDescriptorClass(env),
1184 "getOwnerId$", "()J");
1185 jlong ownerId = env->CallLongMethod(javaFd, getOwnerId);
1186
1187 // Close with bionic's fd ownership tracking (which returns 0 in the case of EINTR).
1188 throwIfMinusOne(env, "close", android_fdsan_close_with_tag(fd, ownerId));
1189 #else
1190 // Even if close(2) fails with EINTR, the fd will have been closed.
1191 // Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone else's fd.
1192 // http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
1193 throwIfMinusOne(env, "close", close(fd));
1194 #endif
1195 }
1196
Linux_android_fdsan_exchange_owner_tag(JNIEnv * env,jclass,jobject javaFd,jlong expectedOwnerId,jlong newOwnerId)1197 static void Linux_android_fdsan_exchange_owner_tag(JNIEnv* env, jclass,
1198 jobject javaFd,
1199 jlong expectedOwnerId,
1200 jlong newOwnerId) {
1201 #if defined(__BIONIC__)
1202 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1203 android_fdsan_exchange_owner_tag(fd, expectedOwnerId, newOwnerId);
1204 #else
1205 UNUSED(env, javaFd, expectedOwnerId, newOwnerId);
1206 #endif
1207 }
1208
Linux_android_fdsan_get_owner_tag(JNIEnv * env,jclass,jobject javaFd)1209 static jlong Linux_android_fdsan_get_owner_tag(JNIEnv* env, jclass, jobject javaFd) {
1210 #if defined(__BIONIC__)
1211 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1212 return android_fdsan_get_owner_tag(fd);
1213 #else
1214 UNUSED(env, javaFd);
1215 return 0;
1216 #endif
1217 }
1218
Linux_android_fdsan_get_tag_type(JNIEnv * env,jclass,jlong tag)1219 static jstring Linux_android_fdsan_get_tag_type(JNIEnv* env, jclass, jlong tag) {
1220 #if defined(__BIONIC__)
1221 return env->NewStringUTF(android_fdsan_get_tag_type(tag));
1222 #else
1223 UNUSED(tag);
1224 return env->NewStringUTF("unknown");
1225 #endif
1226 }
1227
Linux_android_fdsan_get_tag_value(JNIEnv * env,jclass,jlong tag)1228 static jlong Linux_android_fdsan_get_tag_value(JNIEnv* env, jclass, jlong tag) {
1229 #if defined(__BIONIC__)
1230 UNUSED(env);
1231 return android_fdsan_get_tag_value(tag);
1232 #else
1233 UNUSED(env, tag);
1234 return 0;
1235 #endif
1236 }
1237
Linux_connect(JNIEnv * env,jobject,jobject javaFd,jobject javaAddress,jint port)1238 static void Linux_connect(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) {
1239 (void) NET_IPV4_FALLBACK(env, int, connect, javaFd, javaAddress, port, NULL_ADDR_FORBIDDEN);
1240 }
1241
Linux_connectSocketAddress(JNIEnv * env,jobject thisObj,jobject javaFd,jobject javaSocketAddress)1242 static void Linux_connectSocketAddress(
1243 JNIEnv* env, jobject thisObj, jobject javaFd, jobject javaSocketAddress) {
1244 if (javaSocketAddress != NULL &&
1245 env->IsInstanceOf(javaSocketAddress, JniConstants::GetInetSocketAddressClass(env))) {
1246 // Use the InetAddress version so we get the benefit of NET_IPV4_FALLBACK.
1247 jobject javaInetAddress;
1248 jint port;
1249 javaInetSocketAddressToInetAddressAndPort(env, javaSocketAddress, javaInetAddress, port);
1250 Linux_connect(env, thisObj, javaFd, javaInetAddress, port);
1251 return;
1252 }
1253 sockaddr_storage ss;
1254 socklen_t sa_len;
1255 if (!javaSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len)) {
1256 return; // Exception already thrown.
1257 }
1258
1259 const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss);
1260 // We don't need the return value because we'll already have thrown.
1261 (void) NET_FAILURE_RETRY(env, int, connect, javaFd, sa, sa_len);
1262 }
1263
Linux_dup(JNIEnv * env,jobject,jobject javaOldFd)1264 static jobject Linux_dup(JNIEnv* env, jobject, jobject javaOldFd) {
1265 int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd);
1266 int newFd = throwIfMinusOne(env, "dup", TEMP_FAILURE_RETRY(dup(oldFd)));
1267 return createFileDescriptorIfOpen(env, newFd);
1268 }
1269
Linux_dup2(JNIEnv * env,jobject,jobject javaOldFd,jint newFd)1270 static jobject Linux_dup2(JNIEnv* env, jobject, jobject javaOldFd, jint newFd) {
1271 int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd);
1272 int fd = throwIfMinusOne(env, "dup2", TEMP_FAILURE_RETRY(dup2(oldFd, newFd)));
1273 return createFileDescriptorIfOpen(env, fd);
1274 }
1275
Linux_environ(JNIEnv * env,jobject)1276 static jobjectArray Linux_environ(JNIEnv* env, jobject) {
1277 extern char** environ; // Standard, but not in any header file.
1278 return toStringArray(env, environ);
1279 }
1280
Linux_execve(JNIEnv * env,jobject,jstring javaFilename,jobjectArray javaArgv,jobjectArray javaEnvp)1281 static void Linux_execve(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv, jobjectArray javaEnvp) {
1282 ScopedUtfChars path(env, javaFilename);
1283 if (path.c_str() == NULL) {
1284 return;
1285 }
1286
1287 ExecStrings argv(env, javaArgv);
1288 ExecStrings envp(env, javaEnvp);
1289 TEMP_FAILURE_RETRY(execve(path.c_str(), argv.get(), envp.get()));
1290
1291 throwErrnoException(env, "execve");
1292 }
1293
Linux_execv(JNIEnv * env,jobject,jstring javaFilename,jobjectArray javaArgv)1294 static void Linux_execv(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv) {
1295 ScopedUtfChars path(env, javaFilename);
1296 if (path.c_str() == NULL) {
1297 return;
1298 }
1299
1300 ExecStrings argv(env, javaArgv);
1301 TEMP_FAILURE_RETRY(execv(path.c_str(), argv.get()));
1302
1303 throwErrnoException(env, "execv");
1304 }
1305
Linux_fchmod(JNIEnv * env,jobject,jobject javaFd,jint mode)1306 static void Linux_fchmod(JNIEnv* env, jobject, jobject javaFd, jint mode) {
1307 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1308 throwIfMinusOne(env, "fchmod", TEMP_FAILURE_RETRY(fchmod(fd, mode)));
1309 }
1310
Linux_fchown(JNIEnv * env,jobject,jobject javaFd,jint uid,jint gid)1311 static void Linux_fchown(JNIEnv* env, jobject, jobject javaFd, jint uid, jint gid) {
1312 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1313 throwIfMinusOne(env, "fchown", TEMP_FAILURE_RETRY(fchown(fd, uid, gid)));
1314 }
1315
Linux_fcntlInt(JNIEnv * env,jobject,jobject javaFd,jint cmd,jint arg)1316 static jint Linux_fcntlInt(JNIEnv* env, jobject, jobject javaFd, jint cmd, jint arg) {
1317 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1318 return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd, arg)));
1319 }
1320
Linux_fcntlVoid(JNIEnv * env,jobject,jobject javaFd,jint cmd)1321 static jint Linux_fcntlVoid(JNIEnv* env, jobject, jobject javaFd, jint cmd) {
1322 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1323 return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd)));
1324 }
1325
Linux_fdatasync(JNIEnv * env,jobject,jobject javaFd)1326 static void Linux_fdatasync(JNIEnv* env, jobject, jobject javaFd) {
1327 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1328 throwIfMinusOne(env, "fdatasync", TEMP_FAILURE_RETRY(fdatasync(fd)));
1329 }
1330
Linux_fstat(JNIEnv * env,jobject,jobject javaFd)1331 static jobject Linux_fstat(JNIEnv* env, jobject, jobject javaFd) {
1332 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1333 struct stat64 sb;
1334 int rc = TEMP_FAILURE_RETRY(fstat64(fd, &sb));
1335 if (rc == -1) {
1336 throwErrnoException(env, "fstat");
1337 return NULL;
1338 }
1339 return makeStructStat(env, sb);
1340 }
1341
Linux_fstatvfs(JNIEnv * env,jobject,jobject javaFd)1342 static jobject Linux_fstatvfs(JNIEnv* env, jobject, jobject javaFd) {
1343 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1344 struct statvfs sb;
1345 int rc = TEMP_FAILURE_RETRY(fstatvfs(fd, &sb));
1346 if (rc == -1) {
1347 throwErrnoException(env, "fstatvfs");
1348 return NULL;
1349 }
1350 return makeStructStatVfs(env, sb);
1351 }
1352
Linux_fsync(JNIEnv * env,jobject,jobject javaFd)1353 static void Linux_fsync(JNIEnv* env, jobject, jobject javaFd) {
1354 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1355 throwIfMinusOne(env, "fsync", TEMP_FAILURE_RETRY(fsync(fd)));
1356 }
1357
Linux_ftruncate(JNIEnv * env,jobject,jobject javaFd,jlong length)1358 static void Linux_ftruncate(JNIEnv* env, jobject, jobject javaFd, jlong length) {
1359 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1360 throwIfMinusOne(env, "ftruncate", TEMP_FAILURE_RETRY(ftruncate64(fd, length)));
1361 }
1362
Linux_gai_strerror(JNIEnv * env,jobject,jint error)1363 static jstring Linux_gai_strerror(JNIEnv* env, jobject, jint error) {
1364 return env->NewStringUTF(gai_strerror(error));
1365 }
1366
Linux_android_getaddrinfo(JNIEnv * env,jobject,jstring javaNode,jobject javaHints,jint netId)1367 static jobjectArray Linux_android_getaddrinfo(JNIEnv* env, jobject, jstring javaNode,
1368 jobject javaHints, jint netId) {
1369 ScopedUtfChars node(env, javaNode);
1370 if (node.c_str() == NULL) {
1371 return NULL;
1372 }
1373
1374 static jfieldID flagsFid = env->GetFieldID(JniConstants::GetStructAddrinfoClass(env), "ai_flags", "I");
1375 static jfieldID familyFid = env->GetFieldID(JniConstants::GetStructAddrinfoClass(env), "ai_family", "I");
1376 static jfieldID socktypeFid = env->GetFieldID(JniConstants::GetStructAddrinfoClass(env), "ai_socktype", "I");
1377 static jfieldID protocolFid = env->GetFieldID(JniConstants::GetStructAddrinfoClass(env), "ai_protocol", "I");
1378
1379 addrinfo hints;
1380 memset(&hints, 0, sizeof(hints));
1381 hints.ai_flags = env->GetIntField(javaHints, flagsFid);
1382 hints.ai_family = env->GetIntField(javaHints, familyFid);
1383 hints.ai_socktype = env->GetIntField(javaHints, socktypeFid);
1384 hints.ai_protocol = env->GetIntField(javaHints, protocolFid);
1385
1386 addrinfo* addressList = NULL;
1387 errno = 0;
1388 int rc = android_getaddrinfofornet(node.c_str(), NULL, &hints, netId, 0, &addressList);
1389 std::unique_ptr<addrinfo, addrinfo_deleter> addressListDeleter(addressList);
1390 if (rc != 0) {
1391 throwGaiException(env, "android_getaddrinfo", rc);
1392 return NULL;
1393 }
1394
1395 // Count results so we know how to size the output array.
1396 int addressCount = 0;
1397 for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) {
1398 if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
1399 ++addressCount;
1400 } else {
1401 ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family);
1402 }
1403 }
1404 if (addressCount == 0) {
1405 return NULL;
1406 }
1407
1408 // Prepare output array.
1409 jobjectArray result = env->NewObjectArray(addressCount, JniConstants::GetInetAddressClass(env), NULL);
1410 if (result == NULL) {
1411 return NULL;
1412 }
1413
1414 // Examine returned addresses one by one, save them in the output array.
1415 int index = 0;
1416 for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) {
1417 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) {
1418 // Unknown address family. Skip this address.
1419 ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family);
1420 continue;
1421 }
1422
1423 // Convert each IP address into a Java byte array.
1424 ScopedLocalRef<jobject> inetAddress(env, sockaddrToInetAddress(env, ai->ai_addr, NULL));
1425 if (inetAddress.get() == NULL) {
1426 return NULL;
1427 }
1428 env->SetObjectArrayElement(result, index, inetAddress.get());
1429 ++index;
1430 }
1431 return result;
1432 }
1433
Linux_getegid(JNIEnv *,jobject)1434 static jint Linux_getegid(JNIEnv*, jobject) {
1435 return getegid();
1436 }
1437
Linux_geteuid(JNIEnv *,jobject)1438 static jint Linux_geteuid(JNIEnv*, jobject) {
1439 return geteuid();
1440 }
1441
Linux_getgid(JNIEnv *,jobject)1442 static jint Linux_getgid(JNIEnv*, jobject) {
1443 return getgid();
1444 }
1445
Linux_getenv(JNIEnv * env,jobject,jstring javaName)1446 static jstring Linux_getenv(JNIEnv* env, jobject, jstring javaName) {
1447 ScopedUtfChars name(env, javaName);
1448 if (name.c_str() == NULL) {
1449 return NULL;
1450 }
1451 return env->NewStringUTF(getenv(name.c_str()));
1452 }
1453
Linux_getnameinfo(JNIEnv * env,jobject,jobject javaAddress,jint flags)1454 static jstring Linux_getnameinfo(JNIEnv* env, jobject, jobject javaAddress, jint flags) {
1455 sockaddr_storage ss;
1456 socklen_t sa_len;
1457 if (!inetAddressToSockaddrVerbatim(env, javaAddress, 0, ss, sa_len)) {
1458 return NULL;
1459 }
1460 char buf[NI_MAXHOST]; // NI_MAXHOST is longer than INET6_ADDRSTRLEN.
1461 errno = 0;
1462 int rc = getnameinfo(reinterpret_cast<sockaddr*>(&ss), sa_len, buf, sizeof(buf), NULL, 0, flags);
1463 if (rc != 0) {
1464 throwGaiException(env, "getnameinfo", rc);
1465 return NULL;
1466 }
1467 return env->NewStringUTF(buf);
1468 }
1469
Linux_getpeername(JNIEnv * env,jobject,jobject javaFd)1470 static jobject Linux_getpeername(JNIEnv* env, jobject, jobject javaFd) {
1471 return doGetSockName(env, javaFd, false);
1472 }
1473
Linux_getpgid(JNIEnv * env,jobject,jint pid)1474 static jint Linux_getpgid(JNIEnv* env, jobject, jint pid) {
1475 return throwIfMinusOne(env, "getpgid", TEMP_FAILURE_RETRY(getpgid(pid)));
1476 }
1477
Linux_getpid(JNIEnv *,jobject)1478 static jint Linux_getpid(JNIEnv*, jobject) {
1479 return TEMP_FAILURE_RETRY(getpid());
1480 }
1481
Linux_getppid(JNIEnv *,jobject)1482 static jint Linux_getppid(JNIEnv*, jobject) {
1483 return TEMP_FAILURE_RETRY(getppid());
1484 }
1485
Linux_getpwnam(JNIEnv * env,jobject,jstring javaName)1486 static jobject Linux_getpwnam(JNIEnv* env, jobject, jstring javaName) {
1487 ScopedUtfChars name(env, javaName);
1488 if (name.c_str() == NULL) {
1489 return NULL;
1490 }
1491 return Passwd(env).getpwnam(name.c_str());
1492 }
1493
Linux_getpwuid(JNIEnv * env,jobject,jint uid)1494 static jobject Linux_getpwuid(JNIEnv* env, jobject, jint uid) {
1495 return Passwd(env).getpwuid(uid);
1496 }
1497
Linux_getrlimit(JNIEnv * env,jobject,jint resource)1498 static jobject Linux_getrlimit(JNIEnv* env, jobject, jint resource) {
1499 struct rlimit r;
1500 if (throwIfMinusOne(env, "getrlimit", TEMP_FAILURE_RETRY(getrlimit(resource, &r))) == -1) {
1501 return nullptr;
1502 }
1503
1504 ScopedLocalRef<jclass> rlimit_class(env, env->FindClass("android/system/StructRlimit"));
1505 jmethodID ctor = env->GetMethodID(rlimit_class.get(), "<init>", "(JJ)V");
1506 if (ctor == NULL) {
1507 return NULL;
1508 }
1509 return env->NewObject(rlimit_class.get(), ctor,
1510 static_cast<jlong>(r.rlim_cur),
1511 static_cast<jlong>(r.rlim_max));
1512 }
1513
Linux_getsockname(JNIEnv * env,jobject,jobject javaFd)1514 static jobject Linux_getsockname(JNIEnv* env, jobject, jobject javaFd) {
1515 return doGetSockName(env, javaFd, true);
1516 }
1517
Linux_getsockoptByte(JNIEnv * env,jobject,jobject javaFd,jint level,jint option)1518 static jint Linux_getsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
1519 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1520 u_char result = 0;
1521 socklen_t size = sizeof(result);
1522 throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size)));
1523 return result;
1524 }
1525
Linux_getsockoptInAddr(JNIEnv * env,jobject,jobject javaFd,jint level,jint option)1526 static jobject Linux_getsockoptInAddr(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
1527 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1528 sockaddr_storage ss;
1529 memset(&ss, 0, sizeof(ss));
1530 ss.ss_family = AF_INET; // This is only for the IPv4-only IP_MULTICAST_IF.
1531 sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(&ss);
1532 socklen_t size = sizeof(sa->sin_addr);
1533 int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &sa->sin_addr, &size));
1534 if (rc == -1) {
1535 throwErrnoException(env, "getsockopt");
1536 return NULL;
1537 }
1538 return sockaddrToInetAddress(env, reinterpret_cast<sockaddr*>(&ss), NULL);
1539 }
1540
Linux_getsockoptInt(JNIEnv * env,jobject,jobject javaFd,jint level,jint option)1541 static jint Linux_getsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
1542 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1543 jint result = 0;
1544 socklen_t size = sizeof(result);
1545 throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size)));
1546 return result;
1547 }
1548
Linux_getsockoptLinger(JNIEnv * env,jobject,jobject javaFd,jint level,jint option)1549 static jobject Linux_getsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
1550 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1551 struct linger l;
1552 socklen_t size = sizeof(l);
1553 memset(&l, 0, size);
1554 int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &l, &size));
1555 if (rc == -1) {
1556 throwErrnoException(env, "getsockopt");
1557 return NULL;
1558 }
1559 return makeStructLinger(env, l);
1560 }
1561
Linux_getsockoptTimeval(JNIEnv * env,jobject,jobject javaFd,jint level,jint option)1562 static jobject Linux_getsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
1563 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1564 struct timeval tv;
1565 socklen_t size = sizeof(tv);
1566 memset(&tv, 0, size);
1567 int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &tv, &size));
1568 if (rc == -1) {
1569 throwErrnoException(env, "getsockopt");
1570 return NULL;
1571 }
1572 // If we didn't get the buffer size we expected then error. If other structures are the same
1573 // size as timeval we might not detect an issue and could return junk.
1574 if (size != sizeof(tv)) {
1575 jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
1576 "getsockoptTimeval() unsupported with level %i and option %i", level, option);
1577 return NULL;
1578 }
1579 return makeStructTimeval(env, tv);
1580 }
1581
Linux_getsockoptUcred(JNIEnv * env,jobject,jobject javaFd,jint level,jint option)1582 static jobject Linux_getsockoptUcred(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
1583 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1584 struct ucred u;
1585 socklen_t size = sizeof(u);
1586 memset(&u, 0, size);
1587 int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &u, &size));
1588 if (rc == -1) {
1589 throwErrnoException(env, "getsockopt");
1590 return NULL;
1591 }
1592 return makeStructUcred(env, u);
1593 }
1594
Linux_gettid(JNIEnv * env __unused,jobject)1595 static jint Linux_gettid(JNIEnv* env __unused, jobject) {
1596 #if defined(__BIONIC__)
1597 return TEMP_FAILURE_RETRY(gettid());
1598 #else
1599 return syscall(__NR_gettid);
1600 #endif
1601 }
1602
Linux_getuid(JNIEnv *,jobject)1603 static jint Linux_getuid(JNIEnv*, jobject) {
1604 return getuid();
1605 }
1606
Linux_getxattr(JNIEnv * env,jobject,jstring javaPath,jstring javaName)1607 static jbyteArray Linux_getxattr(JNIEnv* env, jobject, jstring javaPath,
1608 jstring javaName) {
1609 ScopedUtfChars path(env, javaPath);
1610 if (path.c_str() == NULL) {
1611 return NULL;
1612 }
1613 ScopedUtfChars name(env, javaName);
1614 if (name.c_str() == NULL) {
1615 return NULL;
1616 }
1617
1618 while (true) {
1619 // Get the current size of the named extended attribute.
1620 ssize_t valueLength;
1621 if ((valueLength = getxattr(path.c_str(), name.c_str(), NULL, 0)) < 0) {
1622 throwErrnoException(env, "getxattr");
1623 return NULL;
1624 }
1625
1626 // Create the actual byte array.
1627 std::vector<char> buf(valueLength);
1628 if ((valueLength = getxattr(path.c_str(), name.c_str(), buf.data(), valueLength)) < 0) {
1629 if (errno == ERANGE) {
1630 // The attribute value has changed since last getxattr call and buf no longer fits,
1631 // try again.
1632 continue;
1633 }
1634 throwErrnoException(env, "getxattr");
1635 return NULL;
1636 }
1637 jbyteArray array = env->NewByteArray(valueLength);
1638 if (array == NULL) {
1639 return NULL;
1640 }
1641 env->SetByteArrayRegion(array, 0, valueLength, reinterpret_cast<const jbyte*>(buf.data()));
1642 return array;
1643 }
1644 }
1645
Linux_getifaddrs(JNIEnv * env,jobject)1646 static jobjectArray Linux_getifaddrs(JNIEnv* env, jobject) {
1647 jmethodID ctor = env->GetMethodID(JniConstants::GetStructIfaddrsClass(env), "<init>",
1648 "(Ljava/lang/String;ILjava/net/InetAddress;Ljava/net/InetAddress;Ljava/net/InetAddress;[B)V");
1649 CHECK(ctor != NULL);
1650
1651 ifaddrs* ifaddr;
1652 int rc = TEMP_FAILURE_RETRY(getifaddrs(&ifaddr));
1653 if (rc == -1) {
1654 throwErrnoException(env, "getifaddrs");
1655 return NULL;
1656 }
1657 std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifaddrPtr(ifaddr, freeifaddrs);
1658
1659 // Count results so we know how to size the output array.
1660 jint ifCount = 0;
1661 for (ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
1662 ++ifCount;
1663 }
1664
1665 // Prepare output array.
1666 jclass ifAddrsClass = JniConstants::GetStructIfaddrsClass(env);
1667 jobjectArray result = env->NewObjectArray(ifCount, ifAddrsClass, NULL);
1668 if (result == NULL) {
1669 DCHECK(env->ExceptionCheck());
1670 return NULL;
1671 }
1672
1673 // Traverse the list and populate the output array.
1674 int index = 0;
1675 for (ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next, ++index) {
1676 char* ifa_name = ifa->ifa_name;
1677 DCHECK(ifa_name != NULL);
1678 TO_JAVA_STRING(name, ifa_name);
1679 jint flags = ifa->ifa_flags;
1680 jobject addr, netmask, broad;
1681 jbyteArray hwaddr = NULL;
1682 if (ifa->ifa_addr != NULL) {
1683 switch (ifa->ifa_addr->sa_family) {
1684 case AF_INET:
1685 case AF_INET6:
1686 // IPv4 / IPv6.
1687 // interfaceAddr and netmaskAddr are never null.
1688 // sockaddrToInetAddress is not expected to return null.
1689 if ((addr = sockaddrToInetAddress(env, ifa->ifa_addr, NULL)) == NULL) {
1690 DCHECK(env->ExceptionCheck());
1691 return NULL;
1692 }
1693 if ((netmask = sockaddrToInetAddress(env, ifa->ifa_netmask, NULL)) == NULL) {
1694 DCHECK(env->ExceptionCheck());
1695 return NULL;
1696 }
1697 if (ifa->ifa_broadaddr != NULL && (ifa->ifa_flags & IFF_BROADCAST)) {
1698 if ((broad = sockaddrToInetAddress(env, ifa->ifa_broadaddr, NULL)) == NULL) {
1699 DCHECK(env->ExceptionCheck());
1700 return NULL;
1701 }
1702 } else {
1703 broad = NULL;
1704 }
1705 break;
1706 case AF_PACKET:
1707 // Raw Interface.
1708 sockaddr_ll* sll = reinterpret_cast<sockaddr_ll*>(ifa->ifa_addr);
1709
1710 bool allZero = true;
1711 for (int i = 0; i < sll->sll_halen; ++i) {
1712 if (sll->sll_addr[i] != 0) {
1713 allZero = false;
1714 break;
1715 }
1716 }
1717
1718 if (!allZero) {
1719 hwaddr = env->NewByteArray(sll->sll_halen);
1720 if (hwaddr == NULL) {
1721 DCHECK(env->ExceptionCheck());
1722 return NULL;
1723 }
1724 env->SetByteArrayRegion(hwaddr, 0, sll->sll_halen,
1725 reinterpret_cast<const jbyte*>(sll->sll_addr));
1726 }
1727 addr = netmask = broad = NULL;
1728 break;
1729 }
1730 } else {
1731 // Preserve the entry even if the interface has no interface address.
1732 // http://b/29243557/
1733 addr = netmask = broad = NULL;
1734 }
1735
1736 jobject o = env->NewObject(ifAddrsClass, ctor, name, flags, addr, netmask, broad, hwaddr);
1737 if (o == NULL) {
1738 DCHECK(env->ExceptionCheck());
1739 return NULL;
1740 }
1741 env->SetObjectArrayElement(result, index, o);
1742 }
1743
1744 return result;
1745 }
1746
Linux_if_indextoname(JNIEnv * env,jobject,jint index)1747 static jstring Linux_if_indextoname(JNIEnv* env, jobject, jint index) {
1748 char buf[IF_NAMESIZE];
1749 char* name = if_indextoname(index, buf);
1750 // if_indextoname(3) returns NULL on failure, which will come out of NewStringUTF unscathed.
1751 // There's no useful information in errno, so we don't bother throwing. Callers can null-check.
1752 return env->NewStringUTF(name);
1753 }
1754
Linux_if_nametoindex(JNIEnv * env,jobject,jstring name)1755 static jint Linux_if_nametoindex(JNIEnv* env, jobject, jstring name) {
1756 ScopedUtfChars cname(env, name);
1757 if (cname.c_str() == NULL) {
1758 return 0;
1759 }
1760
1761 // There's no useful information in errno, so we don't bother throwing. Callers can zero-check.
1762 return if_nametoindex(cname.c_str());
1763 }
1764
Linux_inet_pton(JNIEnv * env,jobject,jint family,jstring javaName)1765 static jobject Linux_inet_pton(JNIEnv* env, jobject, jint family, jstring javaName) {
1766 ScopedUtfChars name(env, javaName);
1767 if (name.c_str() == NULL) {
1768 return NULL;
1769 }
1770 sockaddr_storage ss;
1771 memset(&ss, 0, sizeof(ss));
1772 void* dst;
1773 if (family == AF_INET) {
1774 dst = &reinterpret_cast<sockaddr_in*>(&ss)->sin_addr;
1775 } else if (family == AF_INET6) {
1776 dst = &reinterpret_cast<sockaddr_in6*>(&ss)->sin6_addr;
1777 } else {
1778 return NULL;
1779 }
1780 if (inet_pton(family, name.c_str(), dst) != 1) {
1781 return NULL;
1782 }
1783 ss.ss_family = family;
1784 return sockaddrToInetAddress(env, reinterpret_cast<sockaddr*>(&ss), NULL);
1785 }
1786
Linux_ioctlFlags(JNIEnv * env,jobject,jobject javaFd,jstring javaInterfaceName)1787 static jint Linux_ioctlFlags(JNIEnv* env, jobject, jobject javaFd, jstring javaInterfaceName) {
1788 struct ifreq req;
1789 if (!fillIfreq(env, javaInterfaceName, req)) {
1790 return 0;
1791 }
1792 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1793 throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, SIOCGIFFLAGS, &req)));
1794 return req.ifr_flags;
1795 }
1796
Linux_ioctlInetAddress(JNIEnv * env,jobject,jobject javaFd,jint cmd,jstring javaInterfaceName)1797 static jobject Linux_ioctlInetAddress(JNIEnv* env, jobject, jobject javaFd, jint cmd, jstring javaInterfaceName) {
1798 struct ifreq req;
1799 if (!fillIfreq(env, javaInterfaceName, req)) {
1800 return NULL;
1801 }
1802 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1803 int rc = throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &req)));
1804 if (rc == -1) {
1805 return NULL;
1806 }
1807 return sockaddrToInetAddress(env, &req.ifr_addr, NULL);
1808 }
1809
Linux_ioctlInt(JNIEnv * env,jobject,jobject javaFd,jint cmd)1810 static jint Linux_ioctlInt(JNIEnv* env, jobject, jobject javaFd, jint cmd) {
1811 // Result is being stored in arg, thus simply returning it
1812 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1813 jint arg = 0;
1814 throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &arg)));
1815 return arg;
1816 }
1817
Linux_ioctlMTU(JNIEnv * env,jobject,jobject javaFd,jstring javaInterfaceName)1818 static jint Linux_ioctlMTU(JNIEnv* env, jobject, jobject javaFd, jstring javaInterfaceName) {
1819 struct ifreq req;
1820 if (!fillIfreq(env, javaInterfaceName, req)) {
1821 return 0;
1822 }
1823 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1824 throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, SIOCGIFMTU, &req)));
1825 return req.ifr_mtu;
1826 }
1827
Linux_isatty(JNIEnv * env,jobject,jobject javaFd)1828 static jboolean Linux_isatty(JNIEnv* env, jobject, jobject javaFd) {
1829 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1830 return TEMP_FAILURE_RETRY(isatty(fd)) == 1;
1831 }
1832
Linux_kill(JNIEnv * env,jobject,jint pid,jint sig)1833 static void Linux_kill(JNIEnv* env, jobject, jint pid, jint sig) {
1834 throwIfMinusOne(env, "kill", TEMP_FAILURE_RETRY(kill(pid, sig)));
1835 }
1836
Linux_lchown(JNIEnv * env,jobject,jstring javaPath,jint uid,jint gid)1837 static void Linux_lchown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) {
1838 ScopedUtfChars path(env, javaPath);
1839 if (path.c_str() == NULL) {
1840 return;
1841 }
1842 throwIfMinusOne(env, "lchown", TEMP_FAILURE_RETRY(lchown(path.c_str(), uid, gid)));
1843 }
1844
Linux_link(JNIEnv * env,jobject,jstring javaOldPath,jstring javaNewPath)1845 static void Linux_link(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) {
1846 ScopedUtfChars oldPath(env, javaOldPath);
1847 if (oldPath.c_str() == NULL) {
1848 return;
1849 }
1850 ScopedUtfChars newPath(env, javaNewPath);
1851 if (newPath.c_str() == NULL) {
1852 return;
1853 }
1854 throwIfMinusOne(env, "link", TEMP_FAILURE_RETRY(link(oldPath.c_str(), newPath.c_str())));
1855 }
1856
Linux_listen(JNIEnv * env,jobject,jobject javaFd,jint backlog)1857 static void Linux_listen(JNIEnv* env, jobject, jobject javaFd, jint backlog) {
1858 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1859 throwIfMinusOne(env, "listen", TEMP_FAILURE_RETRY(listen(fd, backlog)));
1860 }
1861
Linux_listxattr(JNIEnv * env,jobject,jstring javaPath)1862 static jobjectArray Linux_listxattr(JNIEnv* env, jobject, jstring javaPath) {
1863 ScopedUtfChars path(env, javaPath);
1864 if (path.c_str() == NULL) {
1865 return NULL;
1866 }
1867
1868 while (true) {
1869 // Get the current size of the named extended attribute.
1870 ssize_t valueLength;
1871 if ((valueLength = listxattr(path.c_str(), NULL, 0)) < 0) {
1872 throwErrnoException(env, "listxattr");
1873 return NULL;
1874 }
1875
1876 // Create the actual byte array.
1877 std::string buf(valueLength, '\0');
1878 if ((valueLength = listxattr(path.c_str(), &buf[0], valueLength)) < 0) {
1879 if (errno == ERANGE) {
1880 // The attribute value has changed since last listxattr call and buf no longer fits,
1881 // try again.
1882 continue;
1883 }
1884 throwErrnoException(env, "listxattr");
1885 return NULL;
1886 }
1887
1888 // Split the output by '\0'.
1889 buf.resize(valueLength > 0 ? valueLength - 1 : 0); // Remove the trailing NULL character.
1890 std::string delim("\0", 1);
1891 auto xattrs = android::base::Split(buf, delim);
1892
1893 return toStringArray(env, xattrs);
1894 }
1895 }
1896
Linux_lseek(JNIEnv * env,jobject,jobject javaFd,jlong offset,jint whence)1897 static jlong Linux_lseek(JNIEnv* env, jobject, jobject javaFd, jlong offset, jint whence) {
1898 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1899 return throwIfMinusOne(env, "lseek", TEMP_FAILURE_RETRY(lseek64(fd, offset, whence)));
1900 }
1901
Linux_lstat(JNIEnv * env,jobject,jstring javaPath)1902 static jobject Linux_lstat(JNIEnv* env, jobject, jstring javaPath) {
1903 return doStat(env, javaPath, true);
1904 }
1905
Linux_memfd_create(JNIEnv * env,jobject,jstring javaName,jint flags)1906 static jobject Linux_memfd_create(JNIEnv* env, jobject, jstring javaName, jint flags) {
1907 #if defined(__BIONIC__)
1908 ScopedUtfChars name(env, javaName);
1909 if (name.c_str() == NULL) {
1910 return NULL;
1911 }
1912
1913 int fd = throwIfMinusOne(env, "memfd_create", memfd_create(name.c_str(), flags));
1914 return createFileDescriptorIfOpen(env, fd);
1915 #else
1916 UNUSED(env, javaName, flags);
1917 return NULL;
1918 #endif
1919 }
1920
Linux_mincore(JNIEnv * env,jobject,jlong address,jlong byteCount,jbyteArray javaVector)1921 static void Linux_mincore(JNIEnv* env, jobject, jlong address, jlong byteCount, jbyteArray javaVector) {
1922 ScopedByteArrayRW vector(env, javaVector);
1923 if (vector.get() == NULL) {
1924 return;
1925 }
1926 void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
1927 unsigned char* vec = reinterpret_cast<unsigned char*>(vector.get());
1928 throwIfMinusOne(env, "mincore", TEMP_FAILURE_RETRY(mincore(ptr, byteCount, vec)));
1929 }
1930
Linux_mkdir(JNIEnv * env,jobject,jstring javaPath,jint mode)1931 static void Linux_mkdir(JNIEnv* env, jobject, jstring javaPath, jint mode) {
1932 ScopedUtfChars path(env, javaPath);
1933 if (path.c_str() == NULL) {
1934 return;
1935 }
1936 throwIfMinusOne(env, "mkdir", TEMP_FAILURE_RETRY(mkdir(path.c_str(), mode)));
1937 }
1938
Linux_mkfifo(JNIEnv * env,jobject,jstring javaPath,jint mode)1939 static void Linux_mkfifo(JNIEnv* env, jobject, jstring javaPath, jint mode) {
1940 ScopedUtfChars path(env, javaPath);
1941 if (path.c_str() == NULL) {
1942 return;
1943 }
1944 throwIfMinusOne(env, "mkfifo", TEMP_FAILURE_RETRY(mkfifo(path.c_str(), mode)));
1945 }
1946
Linux_mlock(JNIEnv * env,jobject,jlong address,jlong byteCount)1947 static void Linux_mlock(JNIEnv* env, jobject, jlong address, jlong byteCount) {
1948 void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
1949 throwIfMinusOne(env, "mlock", TEMP_FAILURE_RETRY(mlock(ptr, byteCount)));
1950 }
1951
Linux_mmap(JNIEnv * env,jobject,jlong address,jlong byteCount,jint prot,jint flags,jobject javaFd,jlong offset)1952 static jlong Linux_mmap(JNIEnv* env, jobject, jlong address, jlong byteCount, jint prot, jint flags, jobject javaFd, jlong offset) {
1953 int fd = jniGetFDFromFileDescriptor(env, javaFd);
1954 void* suggestedPtr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
1955 void* ptr = mmap64(suggestedPtr, byteCount, prot, flags, fd, offset);
1956 if (ptr == MAP_FAILED) {
1957 throwErrnoException(env, "mmap");
1958 }
1959 return static_cast<jlong>(reinterpret_cast<uintptr_t>(ptr));
1960 }
1961
Linux_msync(JNIEnv * env,jobject,jlong address,jlong byteCount,jint flags)1962 static void Linux_msync(JNIEnv* env, jobject, jlong address, jlong byteCount, jint flags) {
1963 void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
1964 throwIfMinusOne(env, "msync", TEMP_FAILURE_RETRY(msync(ptr, byteCount, flags)));
1965 }
1966
Linux_munlock(JNIEnv * env,jobject,jlong address,jlong byteCount)1967 static void Linux_munlock(JNIEnv* env, jobject, jlong address, jlong byteCount) {
1968 void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
1969 throwIfMinusOne(env, "munlock", TEMP_FAILURE_RETRY(munlock(ptr, byteCount)));
1970 }
1971
Linux_munmap(JNIEnv * env,jobject,jlong address,jlong byteCount)1972 static void Linux_munmap(JNIEnv* env, jobject, jlong address, jlong byteCount) {
1973 void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
1974 throwIfMinusOne(env, "munmap", TEMP_FAILURE_RETRY(munmap(ptr, byteCount)));
1975 }
1976
Linux_open(JNIEnv * env,jobject,jstring javaPath,jint flags,jint mode)1977 static jobject Linux_open(JNIEnv* env, jobject, jstring javaPath, jint flags, jint mode) {
1978 ScopedUtfChars path(env, javaPath);
1979 if (path.c_str() == NULL) {
1980 return NULL;
1981 }
1982 int fd = throwIfMinusOne(env, "open", TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
1983 return createFileDescriptorIfOpen(env, fd);
1984 }
1985
Linux_pipe2(JNIEnv * env,jobject,jint flags __unused)1986 static jobjectArray Linux_pipe2(JNIEnv* env, jobject, jint flags __unused) {
1987 int fds[2];
1988 int pipe2_result = throwIfMinusOne(env, "pipe2", TEMP_FAILURE_RETRY(pipe2(&fds[0], flags)));
1989 if (pipe2_result == -1) {
1990 return NULL;
1991 }
1992 jobjectArray result = env->NewObjectArray(2, JniConstants::GetFileDescriptorClass(env), NULL);
1993 if (result == NULL) {
1994 return NULL;
1995 }
1996 for (int i = 0; i < 2; ++i) {
1997 ScopedLocalRef<jobject> fd(env, jniCreateFileDescriptor(env, fds[i]));
1998 env->SetObjectArrayElement(result, i, fd.get());
1999 if (fd.get() == NULL || env->ExceptionCheck()) {
2000 close(fds[0]);
2001 close(fds[1]);
2002 return NULL;
2003 }
2004 }
2005 return result;
2006 }
2007
Linux_poll(JNIEnv * env,jobject,jobjectArray javaStructs,jint timeoutMs)2008 static jint Linux_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint timeoutMs) {
2009 static jfieldID fdFid = env->GetFieldID(JniConstants::GetStructPollfdClass(env), "fd", "Ljava/io/FileDescriptor;");
2010 static jfieldID eventsFid = env->GetFieldID(JniConstants::GetStructPollfdClass(env), "events", "S");
2011 static jfieldID reventsFid = env->GetFieldID(JniConstants::GetStructPollfdClass(env), "revents", "S");
2012
2013 // Turn the Java android.system.StructPollfd[] into a C++ struct pollfd[].
2014 size_t arrayLength = env->GetArrayLength(javaStructs);
2015 std::unique_ptr<struct pollfd[]> fds(new struct pollfd[arrayLength]);
2016 memset(fds.get(), 0, sizeof(struct pollfd) * arrayLength);
2017 size_t count = 0; // Some trailing array elements may be irrelevant. (See below.)
2018 for (size_t i = 0; i < arrayLength; ++i) {
2019 ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i));
2020 if (javaStruct.get() == NULL) {
2021 break; // We allow trailing nulls in the array for caller convenience.
2022 }
2023 ScopedLocalRef<jobject> javaFd(env, env->GetObjectField(javaStruct.get(), fdFid));
2024 if (javaFd.get() == NULL) {
2025 break; // We also allow callers to just clear the fd field (this is what Selector does).
2026 }
2027 fds[count].fd = jniGetFDFromFileDescriptor(env, javaFd.get());
2028 fds[count].events = env->GetShortField(javaStruct.get(), eventsFid);
2029 ++count;
2030 }
2031
2032 std::vector<AsynchronousCloseMonitor*> monitors;
2033 for (size_t i = 0; i < count; ++i) {
2034 monitors.push_back(new AsynchronousCloseMonitor(fds[i].fd));
2035 }
2036
2037 int rc;
2038 while (true) {
2039 timespec before;
2040 clock_gettime(CLOCK_MONOTONIC, &before);
2041
2042 rc = poll(fds.get(), count, timeoutMs);
2043 if (rc >= 0 || errno != EINTR) {
2044 break;
2045 }
2046
2047 // We got EINTR. Work out how much of the original timeout is still left.
2048 if (timeoutMs > 0) {
2049 timespec now;
2050 clock_gettime(CLOCK_MONOTONIC, &now);
2051
2052 timespec diff;
2053 diff.tv_sec = now.tv_sec - before.tv_sec;
2054 diff.tv_nsec = now.tv_nsec - before.tv_nsec;
2055 if (diff.tv_nsec < 0) {
2056 --diff.tv_sec;
2057 diff.tv_nsec += 1000000000;
2058 }
2059
2060 jint diffMs = diff.tv_sec * 1000 + diff.tv_nsec / 1000000;
2061 if (diffMs >= timeoutMs) {
2062 rc = 0; // We have less than 1ms left anyway, so just time out.
2063 break;
2064 }
2065
2066 timeoutMs -= diffMs;
2067 }
2068 }
2069
2070 for (size_t i = 0; i < monitors.size(); ++i) {
2071 delete monitors[i];
2072 }
2073 if (rc == -1) {
2074 throwErrnoException(env, "poll");
2075 return -1;
2076 }
2077
2078 // Update the revents fields in the Java android.system.StructPollfd[].
2079 for (size_t i = 0; i < count; ++i) {
2080 ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i));
2081 if (javaStruct.get() == NULL) {
2082 return -1;
2083 }
2084 env->SetShortField(javaStruct.get(), reventsFid, fds[i].revents);
2085 }
2086 return rc;
2087 }
2088
Linux_posix_fallocate(JNIEnv * env,jobject,jobject javaFd __unused,jlong offset __unused,jlong length __unused)2089 static void Linux_posix_fallocate(JNIEnv* env, jobject, jobject javaFd __unused,
2090 jlong offset __unused, jlong length __unused) {
2091 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2092 while ((errno = posix_fallocate64(fd, offset, length)) == EINTR) {
2093 }
2094 if (errno != 0) {
2095 throwErrnoException(env, "posix_fallocate");
2096 }
2097 }
2098
Linux_prctl(JNIEnv * env,jobject,jint option __unused,jlong arg2 __unused,jlong arg3 __unused,jlong arg4 __unused,jlong arg5 __unused)2099 static jint Linux_prctl(JNIEnv* env, jobject, jint option __unused, jlong arg2 __unused,
2100 jlong arg3 __unused, jlong arg4 __unused, jlong arg5 __unused) {
2101 int result = TEMP_FAILURE_RETRY(prctl(static_cast<int>(option),
2102 static_cast<unsigned long>(arg2),
2103 static_cast<unsigned long>(arg3),
2104 static_cast<unsigned long>(arg4),
2105 static_cast<unsigned long>(arg5)));
2106 return throwIfMinusOne(env, "prctl", result);
2107 }
2108
Linux_preadBytes(JNIEnv * env,jobject,jobject javaFd,jobject javaBytes,jint byteOffset,jint byteCount,jlong offset)2109 static jint Linux_preadBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jlong offset) {
2110 ScopedBytesRW bytes(env, javaBytes);
2111 if (bytes.get() == NULL) {
2112 return -1;
2113 }
2114 return IO_FAILURE_RETRY(env, ssize_t, pread64, javaFd, bytes.get() + byteOffset, byteCount, offset);
2115 }
2116
Linux_pwriteBytes(JNIEnv * env,jobject,jobject javaFd,jobject javaBytes,jint byteOffset,jint byteCount,jlong offset)2117 static jint Linux_pwriteBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jlong offset) {
2118 ScopedBytesRO bytes(env, javaBytes);
2119 if (bytes.get() == NULL) {
2120 return -1;
2121 }
2122 return IO_FAILURE_RETRY(env, ssize_t, pwrite64, javaFd, bytes.get() + byteOffset, byteCount, offset);
2123 }
2124
Linux_readBytes(JNIEnv * env,jobject,jobject javaFd,jobject javaBytes,jint byteOffset,jint byteCount)2125 static jint Linux_readBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount) {
2126 ScopedBytesRW bytes(env, javaBytes);
2127 if (bytes.get() == NULL) {
2128 return -1;
2129 }
2130 return IO_FAILURE_RETRY(env, ssize_t, read, javaFd, bytes.get() + byteOffset, byteCount);
2131 }
2132
Linux_readlink(JNIEnv * env,jobject,jstring javaPath)2133 static jstring Linux_readlink(JNIEnv* env, jobject, jstring javaPath) {
2134 ScopedUtfChars path(env, javaPath);
2135 if (path.c_str() == NULL) {
2136 return NULL;
2137 }
2138
2139 std::string result;
2140 if (!android::base::Readlink(path.c_str(), &result)) {
2141 throwErrnoException(env, "readlink");
2142 return NULL;
2143 }
2144 return env->NewStringUTF(result.c_str());
2145 }
2146
Linux_realpath(JNIEnv * env,jobject,jstring javaPath)2147 static jstring Linux_realpath(JNIEnv* env, jobject, jstring javaPath) {
2148 ScopedUtfChars path(env, javaPath);
2149 if (path.c_str() == NULL) {
2150 return NULL;
2151 }
2152
2153 std::unique_ptr<char, c_deleter> real_path(realpath(path.c_str(), nullptr));
2154 if (real_path.get() == nullptr) {
2155 throwErrnoException(env, "realpath");
2156 return NULL;
2157 }
2158
2159 return env->NewStringUTF(real_path.get());
2160 }
2161
Linux_readv(JNIEnv * env,jobject,jobject javaFd,jobjectArray buffers,jintArray offsets,jintArray byteCounts)2162 static jint Linux_readv(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) {
2163 IoVec<ScopedBytesRW> ioVec(env, env->GetArrayLength(buffers));
2164 if (!ioVec.init(buffers, offsets, byteCounts)) {
2165 return -1;
2166 }
2167 return IO_FAILURE_RETRY(env, ssize_t, readv, javaFd, ioVec.get(), ioVec.size());
2168 }
2169
Linux_recvfromBytes(JNIEnv * env,jobject,jobject javaFd,jobject javaBytes,jint byteOffset,jint byteCount,jint flags,jobject javaInetSocketAddress)2170 static jint Linux_recvfromBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetSocketAddress) {
2171 ScopedBytesRW bytes(env, javaBytes);
2172 if (bytes.get() == NULL) {
2173 return -1;
2174 }
2175 sockaddr_storage ss;
2176 socklen_t sl = sizeof(ss);
2177 memset(&ss, 0, sizeof(ss));
2178 sockaddr* from = (javaInetSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL;
2179 socklen_t* fromLength = (javaInetSocketAddress != NULL) ? &sl : 0;
2180 jint recvCount = NET_FAILURE_RETRY(env, ssize_t, recvfrom, javaFd, bytes.get() + byteOffset, byteCount, flags, from, fromLength);
2181 if (recvCount >= 0) {
2182 // The socket may have performed orderly shutdown and recvCount would return 0 (see man 2
2183 // recvfrom), in which case ss.ss_family == AF_UNIX and fillInetSocketAddress would fail.
2184 // Don't fill in the address if recvfrom didn't succeed. http://b/33483694
2185 if (ss.ss_family == AF_INET || ss.ss_family == AF_INET6) {
2186 fillInetSocketAddress(env, javaInetSocketAddress, ss);
2187 }
2188 }
2189 return recvCount;
2190 }
2191
Linux_recvmsg(JNIEnv * env,jobject,jobject javaFd,jobject structMsghdr,jint flags)2192 static jint Linux_recvmsg(JNIEnv* env, jobject, jobject javaFd, jobject structMsghdr, jint flags) {
2193 ssize_t rc = -1;
2194 ScopedMsghdr scopedMsghdrValue;
2195 ScopedByteBufferArray scopedBytesArray(env, true);
2196 sockaddr_storage ss = {};
2197
2198 static jfieldID msgNameFid = env->GetFieldID(JniConstants::GetStructMsghdrClass(env),
2199 "msg_name", "Ljava/net/SocketAddress;");
2200 if (!msgNameFid) {
2201 return -1;
2202 }
2203
2204 // Initialize msghdr with everything from StructCMsghdr except msg_name.
2205 if (msghdrJavaToC(env, structMsghdr, scopedMsghdrValue.getObject(),
2206 scopedBytesArray) == false) {
2207 return -1;
2208 }
2209
2210 jobject javaSocketAddress = env->GetObjectField(structMsghdr, msgNameFid);
2211 if (javaSocketAddress) {
2212 // client want to get source address, then set msg_name and msg_namelen.
2213 scopedMsghdrValue.setMsgNameAndLen(reinterpret_cast<sockaddr*>(&ss),
2214 sizeof(sockaddr_in6));
2215 }
2216
2217 rc = NET_FAILURE_RETRY(env, ssize_t, recvmsg, javaFd, \
2218 &scopedMsghdrValue.getObject(), flags);
2219
2220 if (rc < 0) {
2221 return rc;
2222 }
2223
2224 if (javaSocketAddress) {
2225 sockaddr_storage* interfaceAddr = NULL;
2226 if (!scopedMsghdrValue.isNameLenValid()) {
2227 jniThrowException(env, "java/net/SocketException",
2228 "unknown socket address type");
2229 return -1;
2230 }
2231
2232 interfaceAddr = reinterpret_cast<sockaddr_storage*>(scopedMsghdrValue.getObject().msg_name);
2233 if (fillSocketAddress(env, javaSocketAddress, *interfaceAddr,
2234 scopedMsghdrValue.getObject().msg_namelen) == false) {
2235 return -1;
2236 }
2237 }
2238
2239 if (msghdrCToJava(env, structMsghdr, scopedMsghdrValue.getObject(),
2240 scopedBytesArray) == false) {
2241 return -1;
2242 }
2243
2244 return rc;
2245 }
2246
2247
Linux_remove(JNIEnv * env,jobject,jstring javaPath)2248 static void Linux_remove(JNIEnv* env, jobject, jstring javaPath) {
2249 ScopedUtfChars path(env, javaPath);
2250 if (path.c_str() == NULL) {
2251 return;
2252 }
2253 throwIfMinusOne(env, "remove", TEMP_FAILURE_RETRY(remove(path.c_str())));
2254 }
2255
Linux_removexattr(JNIEnv * env,jobject,jstring javaPath,jstring javaName)2256 static void Linux_removexattr(JNIEnv* env, jobject, jstring javaPath, jstring javaName) {
2257 ScopedUtfChars path(env, javaPath);
2258 if (path.c_str() == NULL) {
2259 return;
2260 }
2261 ScopedUtfChars name(env, javaName);
2262 if (name.c_str() == NULL) {
2263 return;
2264 }
2265
2266 int res = removexattr(path.c_str(), name.c_str());
2267 if (res < 0) {
2268 throwErrnoException(env, "removexattr");
2269 }
2270 }
2271
Linux_rename(JNIEnv * env,jobject,jstring javaOldPath,jstring javaNewPath)2272 static void Linux_rename(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) {
2273 ScopedUtfChars oldPath(env, javaOldPath);
2274 if (oldPath.c_str() == NULL) {
2275 return;
2276 }
2277 ScopedUtfChars newPath(env, javaNewPath);
2278 if (newPath.c_str() == NULL) {
2279 return;
2280 }
2281 throwIfMinusOne(env, "rename", TEMP_FAILURE_RETRY(rename(oldPath.c_str(), newPath.c_str())));
2282 }
2283
Linux_sendfile(JNIEnv * env,jobject,jobject javaOutFd,jobject javaInFd,jobject javaOffset,jlong byteCount)2284 static jlong Linux_sendfile(JNIEnv* env, jobject, jobject javaOutFd, jobject javaInFd, jobject javaOffset, jlong byteCount) {
2285 int outFd = jniGetFDFromFileDescriptor(env, javaOutFd);
2286 int inFd = jniGetFDFromFileDescriptor(env, javaInFd);
2287 off_t offset = 0;
2288 off_t* offsetPtr = NULL;
2289 if (javaOffset != NULL) {
2290 // TODO: fix bionic so we can have a 64-bit off_t!
2291 offset = env->GetLongField(javaOffset, int64RefValueFid);
2292 offsetPtr = &offset;
2293 }
2294 jlong result = throwIfMinusOne(env, "sendfile", TEMP_FAILURE_RETRY(sendfile(outFd, inFd, offsetPtr, byteCount)));
2295 if (result == -1) {
2296 return -1;
2297 }
2298 if (javaOffset != NULL) {
2299 env->SetLongField(javaOffset, int64RefValueFid, offset);
2300 }
2301 return result;
2302 }
2303
Linux_sendmsg(JNIEnv * env,jobject,jobject javaFd,jobject structMsghdr,jint flags)2304 static jint Linux_sendmsg(JNIEnv* env, jobject, jobject javaFd, jobject structMsghdr, jint flags) {
2305
2306 ssize_t rc = -1;
2307 ScopedMsghdr scopedMsghdrValue = {};
2308 ScopedByteBufferArray scopedBytesArray(env, false);
2309 static jfieldID msgNameFid = env->GetFieldID(JniConstants::GetStructMsghdrClass(env),
2310 "msg_name",
2311 "Ljava/net/SocketAddress;");
2312 if (!msgNameFid) {
2313 return -1;
2314 }
2315
2316 jobject sockAddrObj = env->GetObjectField(structMsghdr, msgNameFid);
2317
2318 // Initialize structMsghdr with everything from C msghdr except msg_name.
2319 if (msghdrJavaToC(env, structMsghdr, scopedMsghdrValue.getObject(),
2320 scopedBytesArray) == false) {
2321 return -1;
2322 }
2323
2324 sockaddr_storage ss = {};
2325 socklen_t sa_len = 0;
2326 if (sockAddrObj && javaSocketAddressToSockaddr(env, sockAddrObj, ss, sa_len) == false) {
2327 return -1;
2328 }
2329
2330 // Determine if the socket address is an internet address. We need to do this before invoking
2331 // NET_FAILURE_RETRY(sendmsg) because that can throw and we can't call env->IsInstanceOf
2332 // with a pending exception (b/194980932).
2333 const bool isInetSocketAddressClass =
2334 env->IsInstanceOf(sockAddrObj, JniConstants::GetInetSocketAddressClass(env));
2335
2336 sockaddr* _sa = sa_len ? reinterpret_cast<sockaddr*>(&ss) : NULL;
2337 scopedMsghdrValue.setMsgNameAndLen(_sa, sa_len);
2338 rc = NET_FAILURE_RETRY(env, ssize_t, sendmsg, javaFd, \
2339 &(scopedMsghdrValue.getObject()), flags);
2340
2341 if (sockAddrObj && !isInetSocketAddressClass) {
2342 // non InetSockAddress case, return now;
2343 return rc;
2344 }
2345
2346 // InetSocket and IPv6 didn't work, fallback to IPv4.
2347 if (rc == -1 && errno == EAFNOSUPPORT && sa_len && isIPv4MappedAddress(_sa)) {
2348 env->ExceptionClear();
2349
2350 jobject javaInetAddress;
2351 jint port = 0;
2352 javaInetSocketAddressToInetAddressAndPort(env, sockAddrObj, javaInetAddress, port);
2353
2354 // Get IPv4 sockaddr.
2355 if (!inetAddressToSockaddrVerbatim(env, javaInetAddress, port, ss, sa_len)) {
2356 return rc;
2357 }
2358
2359 // Use IPv4 msghdr.msg_name.
2360 _sa = sa_len ? reinterpret_cast<sockaddr*>(&ss) : NULL;
2361 scopedMsghdrValue.setMsgNameAndLen(_sa, sa_len);
2362 rc = NET_FAILURE_RETRY(env, ssize_t, sendmsg, javaFd, \
2363 &(scopedMsghdrValue.getObject()), flags);
2364 }
2365
2366 return rc;
2367 }
2368
Linux_sendtoBytes(JNIEnv * env,jobject,jobject javaFd,jobject javaBytes,jint byteOffset,jint byteCount,jint flags,jobject javaInetAddress,jint port)2369 static jint Linux_sendtoBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetAddress, jint port) {
2370 ScopedBytesRO bytes(env, javaBytes);
2371 if (bytes.get() == NULL) {
2372 return -1;
2373 }
2374
2375 return NET_IPV4_FALLBACK(env, ssize_t, sendto, javaFd, javaInetAddress, port,
2376 NULL_ADDR_OK, bytes.get() + byteOffset, byteCount, flags);
2377 }
2378
Linux_sendtoBytesSocketAddress(JNIEnv * env,jobject,jobject javaFd,jobject javaBytes,jint byteOffset,jint byteCount,jint flags,jobject javaSocketAddress)2379 static jint Linux_sendtoBytesSocketAddress(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaSocketAddress) {
2380 if (javaSocketAddress != NULL &&
2381 env->IsInstanceOf(javaSocketAddress, JniConstants::GetInetSocketAddressClass(env))) {
2382 // Use the InetAddress version so we get the benefit of NET_IPV4_FALLBACK.
2383 jobject javaInetAddress;
2384 jint port;
2385 javaInetSocketAddressToInetAddressAndPort(env, javaSocketAddress, javaInetAddress, port);
2386 return Linux_sendtoBytes(env, NULL, javaFd, javaBytes, byteOffset, byteCount, flags,
2387 javaInetAddress, port);
2388 }
2389
2390 ScopedBytesRO bytes(env, javaBytes);
2391 if (bytes.get() == NULL) {
2392 return -1;
2393 }
2394
2395 sockaddr_storage ss;
2396 socklen_t sa_len;
2397 const sockaddr* sa;
2398
2399 if (javaSocketAddress != NULL) {
2400 if (!javaSocketAddressToSockaddr(env, javaSocketAddress, ss, sa_len)) {
2401 return -1;
2402 }
2403
2404 sa = reinterpret_cast<const sockaddr*>(&ss);
2405 } else {
2406 sa = NULL;
2407 sa_len = 0;
2408 }
2409
2410 // We don't need the return value because we'll already have thrown.
2411 return NET_FAILURE_RETRY(env, ssize_t, sendto, javaFd, bytes.get() + byteOffset, byteCount, flags, sa, sa_len);
2412 }
2413
Linux_setegid(JNIEnv * env,jobject,jint egid)2414 static void Linux_setegid(JNIEnv* env, jobject, jint egid) {
2415 throwIfMinusOne(env, "setegid", TEMP_FAILURE_RETRY(setegid(egid)));
2416 }
2417
Linux_setenv(JNIEnv * env,jobject,jstring javaName,jstring javaValue,jboolean overwrite)2418 static void Linux_setenv(JNIEnv* env, jobject, jstring javaName, jstring javaValue, jboolean overwrite) {
2419 ScopedUtfChars name(env, javaName);
2420 if (name.c_str() == NULL) {
2421 return;
2422 }
2423 ScopedUtfChars value(env, javaValue);
2424 if (value.c_str() == NULL) {
2425 return;
2426 }
2427 throwIfMinusOne(env, "setenv", setenv(name.c_str(), value.c_str(), overwrite));
2428 }
2429
Linux_seteuid(JNIEnv * env,jobject,jint euid)2430 static void Linux_seteuid(JNIEnv* env, jobject, jint euid) {
2431 throwIfMinusOne(env, "seteuid", TEMP_FAILURE_RETRY(seteuid(euid)));
2432 }
2433
Linux_setgid(JNIEnv * env,jobject,jint gid)2434 static void Linux_setgid(JNIEnv* env, jobject, jint gid) {
2435 throwIfMinusOne(env, "setgid", TEMP_FAILURE_RETRY(setgid(gid)));
2436 }
2437
Linux_setpgid(JNIEnv * env,jobject,jint pid,int pgid)2438 static void Linux_setpgid(JNIEnv* env, jobject, jint pid, int pgid) {
2439 throwIfMinusOne(env, "setpgid", TEMP_FAILURE_RETRY(setpgid(pid, pgid)));
2440 }
2441
Linux_setregid(JNIEnv * env,jobject,jint rgid,int egid)2442 static void Linux_setregid(JNIEnv* env, jobject, jint rgid, int egid) {
2443 throwIfMinusOne(env, "setregid", TEMP_FAILURE_RETRY(setregid(rgid, egid)));
2444 }
2445
Linux_setreuid(JNIEnv * env,jobject,jint ruid,int euid)2446 static void Linux_setreuid(JNIEnv* env, jobject, jint ruid, int euid) {
2447 throwIfMinusOne(env, "setreuid", TEMP_FAILURE_RETRY(setreuid(ruid, euid)));
2448 }
2449
Linux_setsid(JNIEnv * env,jobject)2450 static jint Linux_setsid(JNIEnv* env, jobject) {
2451 return throwIfMinusOne(env, "setsid", TEMP_FAILURE_RETRY(setsid()));
2452 }
2453
Linux_setsockoptByte(JNIEnv * env,jobject,jobject javaFd,jint level,jint option,jint value)2454 static void Linux_setsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) {
2455 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2456 u_char byte = value;
2457 throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &byte, sizeof(byte))));
2458 }
2459
Linux_setsockoptIfreq(JNIEnv * env,jobject,jobject javaFd,jint level,jint option,jstring javaInterfaceName)2460 static void Linux_setsockoptIfreq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jstring javaInterfaceName) {
2461 struct ifreq req;
2462 if (!fillIfreq(env, javaInterfaceName, req)) {
2463 return;
2464 }
2465 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2466 throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))));
2467 }
2468
Linux_setsockoptInt(JNIEnv * env,jobject,jobject javaFd,jint level,jint option,jint value)2469 static void Linux_setsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) {
2470 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2471 throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value))));
2472 }
2473
Linux_setsockoptIpMreqn(JNIEnv * env,jobject,jobject javaFd,jint level,jint option,jint value)2474 static void Linux_setsockoptIpMreqn(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) {
2475 ip_mreqn req;
2476 memset(&req, 0, sizeof(req));
2477 req.imr_ifindex = value;
2478 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2479 throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))));
2480 }
2481
Linux_setsockoptGroupReq(JNIEnv * env,jobject,jobject javaFd,jint level,jint option,jobject javaGroupReq)2482 static void Linux_setsockoptGroupReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupReq) {
2483 struct group_req req;
2484 memset(&req, 0, sizeof(req));
2485
2486 static jfieldID grInterfaceFid = env->GetFieldID(JniConstants::GetStructGroupReqClass(env), "gr_interface", "I");
2487 req.gr_interface = env->GetIntField(javaGroupReq, grInterfaceFid);
2488 // Get the IPv4 or IPv6 multicast address to join or leave.
2489 static jfieldID grGroupFid = env->GetFieldID(JniConstants::GetStructGroupReqClass(env), "gr_group", "Ljava/net/InetAddress;");
2490 ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupReq, grGroupFid));
2491 socklen_t sa_len;
2492 if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gr_group, sa_len)) {
2493 return;
2494 }
2495
2496 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2497 int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)));
2498 if (rc == -1 && errno == EINVAL) {
2499 // Maybe we're a 32-bit binary talking to a 64-bit kernel?
2500 // glibc doesn't automatically handle this.
2501 // http://sourceware.org/bugzilla/show_bug.cgi?id=12080
2502 struct group_req64 {
2503 uint32_t gr_interface;
2504 uint32_t my_padding;
2505 sockaddr_storage gr_group;
2506 };
2507 group_req64 req64;
2508 req64.gr_interface = req.gr_interface;
2509 memcpy(&req64.gr_group, &req.gr_group, sizeof(req.gr_group));
2510 rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64)));
2511 }
2512 throwIfMinusOne(env, "setsockopt", rc);
2513 }
2514
Linux_setsockoptLinger(JNIEnv * env,jobject,jobject javaFd,jint level,jint option,jobject javaLinger)2515 static void Linux_setsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaLinger) {
2516 static jfieldID lOnoffFid = env->GetFieldID(JniConstants::GetStructLingerClass(env), "l_onoff", "I");
2517 static jfieldID lLingerFid = env->GetFieldID(JniConstants::GetStructLingerClass(env), "l_linger", "I");
2518 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2519 struct linger value;
2520 value.l_onoff = env->GetIntField(javaLinger, lOnoffFid);
2521 value.l_linger = env->GetIntField(javaLinger, lLingerFid);
2522 throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value))));
2523 }
2524
Linux_setsockoptTimeval(JNIEnv * env,jobject,jobject javaFd,jint level,jint option,jobject javaTimeval)2525 static void Linux_setsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaTimeval) {
2526 if (javaTimeval == nullptr) {
2527 jniThrowNullPointerException(env, "null javaTimeval");
2528 return;
2529 }
2530
2531 static jfieldID tvSecFid = env->GetFieldID(JniConstants::GetStructTimevalClass(env), "tv_sec", "J");
2532 static jfieldID tvUsecFid = env->GetFieldID(JniConstants::GetStructTimevalClass(env), "tv_usec", "J");
2533 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2534 struct timeval value;
2535 value.tv_sec = env->GetLongField(javaTimeval, tvSecFid);
2536 value.tv_usec = env->GetLongField(javaTimeval, tvUsecFid);
2537 throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value))));
2538 }
2539
Linux_setuid(JNIEnv * env,jobject,jint uid)2540 static void Linux_setuid(JNIEnv* env, jobject, jint uid) {
2541 throwIfMinusOne(env, "setuid", TEMP_FAILURE_RETRY(setuid(uid)));
2542 }
2543
Linux_setxattr(JNIEnv * env,jobject,jstring javaPath,jstring javaName,jbyteArray javaValue,jint flags)2544 static void Linux_setxattr(JNIEnv* env, jobject, jstring javaPath, jstring javaName,
2545 jbyteArray javaValue, jint flags) {
2546 ScopedUtfChars path(env, javaPath);
2547 if (path.c_str() == NULL) {
2548 return;
2549 }
2550 ScopedUtfChars name(env, javaName);
2551 if (name.c_str() == NULL) {
2552 return;
2553 }
2554 ScopedBytesRO value(env, javaValue);
2555 if (value.get() == NULL) {
2556 return;
2557 }
2558 size_t valueLength = env->GetArrayLength(javaValue);
2559 int res = setxattr(path.c_str(), name.c_str(), value.get(), valueLength, flags);
2560 if (res < 0) {
2561 throwErrnoException(env, "setxattr");
2562 }
2563 }
2564
Linux_shutdown(JNIEnv * env,jobject,jobject javaFd,jint how)2565 static void Linux_shutdown(JNIEnv* env, jobject, jobject javaFd, jint how) {
2566 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2567 throwIfMinusOne(env, "shutdown", TEMP_FAILURE_RETRY(shutdown(fd, how)));
2568 }
2569
Linux_socket(JNIEnv * env,jobject,jint domain,jint type,jint protocol)2570 static jobject Linux_socket(JNIEnv* env, jobject, jint domain, jint type, jint protocol) {
2571 if (domain == AF_PACKET) {
2572 protocol = htons(protocol); // Packet sockets specify the protocol in host byte order.
2573 }
2574 int fd = throwIfMinusOne(env, "socket", TEMP_FAILURE_RETRY(socket(domain, type, protocol)));
2575 return createFileDescriptorIfOpen(env, fd);
2576 }
2577
Linux_socketpair(JNIEnv * env,jobject,jint domain,jint type,jint protocol,jobject javaFd1,jobject javaFd2)2578 static void Linux_socketpair(JNIEnv* env, jobject, jint domain, jint type, jint protocol, jobject javaFd1, jobject javaFd2) {
2579 int fds[2];
2580 // Fail fast to avoid leaking file descriptors if either FileDescriptor is null.
2581 if (javaFd1 == nullptr) {
2582 jniThrowNullPointerException(env, "null fd1");
2583 } else if (javaFd2 == nullptr) {
2584 jniThrowNullPointerException(env, "null fd2");
2585 } else {
2586 int rc = throwIfMinusOne(env, "socketpair",
2587 TEMP_FAILURE_RETRY(socketpair(domain, type, protocol, fds)));
2588 if (rc != -1) {
2589 jniSetFileDescriptorOfFD(env, javaFd1, fds[0]);
2590 jniSetFileDescriptorOfFD(env, javaFd2, fds[1]);
2591 }
2592 }
2593 }
2594
Linux_splice(JNIEnv * env,jobject,jobject javaFdIn,jobject javaOffIn,jobject javaFdOut,jobject javaOffOut,jlong len,jint flags)2595 static jlong Linux_splice(JNIEnv* env, jobject, jobject javaFdIn, jobject javaOffIn, jobject javaFdOut, jobject javaOffOut, jlong len, jint flags) {
2596 int fdIn = jniGetFDFromFileDescriptor(env, javaFdIn);
2597 int fdOut = jniGetFDFromFileDescriptor(env, javaFdOut);
2598 int spliceErrno;
2599
2600 jlong offIn = (javaOffIn == NULL ? 0 : env->GetLongField(javaOffIn, int64RefValueFid));
2601 jlong offOut = (javaOffOut == NULL ? 0 : env->GetLongField(javaOffOut, int64RefValueFid));
2602 jlong ret = -1;
2603 do {
2604 bool wasSignaled = false;
2605 {
2606 AsynchronousCloseMonitor monitorIn(fdIn);
2607 AsynchronousCloseMonitor monitorOut(fdOut);
2608 ret = splice(fdIn, (javaOffIn == NULL ? NULL : &offIn),
2609 fdOut, (javaOffOut == NULL ? NULL : &offOut),
2610 len, flags);
2611 spliceErrno = errno;
2612 wasSignaled = monitorIn.wasSignaled() || monitorOut.wasSignaled();
2613 }
2614 if (wasSignaled) {
2615 jniThrowException(env, "java/io/InterruptedIOException", "splice interrupted");
2616 ret = -1;
2617 break;
2618 }
2619 if (ret == -1 && spliceErrno != EINTR) {
2620 throwErrnoException(env, "splice");
2621 break;
2622 }
2623 } while (ret == -1);
2624 if (ret == -1) {
2625 /* If the syscall failed, re-set errno: throwing an exception might have modified it. */
2626 errno = spliceErrno;
2627 } else {
2628 if (javaOffIn != NULL) {
2629 env->SetLongField(javaOffIn, int64RefValueFid, offIn);
2630 }
2631 if (javaOffOut != NULL) {
2632 env->SetLongField(javaOffOut, int64RefValueFid, offOut);
2633 }
2634 }
2635 return ret;
2636 }
2637
2638
Linux_stat(JNIEnv * env,jobject,jstring javaPath)2639 static jobject Linux_stat(JNIEnv* env, jobject, jstring javaPath) {
2640 return doStat(env, javaPath, false);
2641 }
2642
Linux_statvfs(JNIEnv * env,jobject,jstring javaPath)2643 static jobject Linux_statvfs(JNIEnv* env, jobject, jstring javaPath) {
2644 ScopedUtfChars path(env, javaPath);
2645 if (path.c_str() == NULL) {
2646 return NULL;
2647 }
2648 struct statvfs sb;
2649 int rc = TEMP_FAILURE_RETRY(statvfs(path.c_str(), &sb));
2650 if (rc == -1) {
2651 throwErrnoException(env, "statvfs");
2652 return NULL;
2653 }
2654 return makeStructStatVfs(env, sb);
2655 }
2656
Linux_strerror(JNIEnv * env,jobject,jint errnum)2657 static jstring Linux_strerror(JNIEnv* env, jobject, jint errnum) {
2658 char buffer[BUFSIZ];
2659 #ifdef ANDROID_HOST_MUSL
2660 /* musl only provides the posix version of strerror_r that returns int */
2661 int ret = strerror_r(errnum, buffer, sizeof(buffer));
2662 if (ret != 0) {
2663 return env->NewStringUTF(android::base::StringPrintf("Unknown error %d", errnum).c_str());
2664 }
2665 return env->NewStringUTF(buffer);
2666 #else
2667 const char* message = strerror_r(errnum, buffer, sizeof(buffer));
2668 return env->NewStringUTF(message);
2669 #endif
2670 }
2671
Linux_strsignal(JNIEnv * env,jobject,jint signal)2672 static jstring Linux_strsignal(JNIEnv* env, jobject, jint signal) {
2673 return env->NewStringUTF(strsignal(signal));
2674 }
2675
Linux_symlink(JNIEnv * env,jobject,jstring javaOldPath,jstring javaNewPath)2676 static void Linux_symlink(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) {
2677 ScopedUtfChars oldPath(env, javaOldPath);
2678 if (oldPath.c_str() == NULL) {
2679 return;
2680 }
2681 ScopedUtfChars newPath(env, javaNewPath);
2682 if (newPath.c_str() == NULL) {
2683 return;
2684 }
2685 throwIfMinusOne(env, "symlink", TEMP_FAILURE_RETRY(symlink(oldPath.c_str(), newPath.c_str())));
2686 }
2687
Linux_sysconf(JNIEnv * env,jobject,jint name)2688 static jlong Linux_sysconf(JNIEnv* env, jobject, jint name) {
2689 // Since -1 is a valid result from sysconf(3), detecting failure is a little more awkward.
2690 errno = 0;
2691 long result = sysconf(name);
2692 if (result == -1L && errno == EINVAL) {
2693 throwErrnoException(env, "sysconf");
2694 }
2695 return result;
2696 }
2697
Linux_tcdrain(JNIEnv * env,jobject,jobject javaFd)2698 static void Linux_tcdrain(JNIEnv* env, jobject, jobject javaFd) {
2699 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2700 throwIfMinusOne(env, "tcdrain", TEMP_FAILURE_RETRY(tcdrain(fd)));
2701 }
2702
Linux_tcsendbreak(JNIEnv * env,jobject,jobject javaFd,jint duration)2703 static void Linux_tcsendbreak(JNIEnv* env, jobject, jobject javaFd, jint duration) {
2704 int fd = jniGetFDFromFileDescriptor(env, javaFd);
2705 throwIfMinusOne(env, "tcsendbreak", TEMP_FAILURE_RETRY(tcsendbreak(fd, duration)));
2706 }
2707
Linux_umaskImpl(JNIEnv *,jobject,jint mask)2708 static jint Linux_umaskImpl(JNIEnv*, jobject, jint mask) {
2709 return umask(mask);
2710 }
2711
Linux_uname(JNIEnv * env,jobject)2712 static jobject Linux_uname(JNIEnv* env, jobject) {
2713 struct utsname buf;
2714 if (TEMP_FAILURE_RETRY(uname(&buf)) == -1) {
2715 return NULL; // Can't happen.
2716 }
2717 return makeStructUtsname(env, buf);
2718 }
2719
Linux_unlink(JNIEnv * env,jobject,jstring javaPathname)2720 static void Linux_unlink(JNIEnv* env, jobject, jstring javaPathname) {
2721 ScopedUtfChars pathname(env, javaPathname);
2722 if (pathname.c_str() == NULL) {
2723 return;
2724 }
2725 throwIfMinusOne(env, "unlink", unlink(pathname.c_str()));
2726 }
2727
Linux_unsetenv(JNIEnv * env,jobject,jstring javaName)2728 static void Linux_unsetenv(JNIEnv* env, jobject, jstring javaName) {
2729 ScopedUtfChars name(env, javaName);
2730 if (name.c_str() == NULL) {
2731 return;
2732 }
2733 throwIfMinusOne(env, "unsetenv", unsetenv(name.c_str()));
2734 }
2735
Linux_waitpid(JNIEnv * env,jobject,jint pid,jobject javaStatus,jint options)2736 static jint Linux_waitpid(JNIEnv* env, jobject, jint pid, jobject javaStatus, jint options) {
2737 int status;
2738 int rc = throwIfMinusOne(env, "waitpid", TEMP_FAILURE_RETRY(waitpid(pid, &status, options)));
2739 if (javaStatus != NULL && rc != -1) {
2740 env->SetIntField(javaStatus, int32RefValueFid, status);
2741 }
2742 return rc;
2743 }
2744
Linux_writeBytes(JNIEnv * env,jobject,jobject javaFd,jobject javaBytes,jint byteOffset,jint byteCount)2745 static jint Linux_writeBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount) {
2746 ScopedBytesRO bytes(env, javaBytes);
2747 if (bytes.get() == NULL) {
2748 return -1;
2749 }
2750 return IO_FAILURE_RETRY(env, ssize_t, write, javaFd, bytes.get() + byteOffset, byteCount);
2751 }
2752
Linux_writev(JNIEnv * env,jobject,jobject javaFd,jobjectArray buffers,jintArray offsets,jintArray byteCounts)2753 static jint Linux_writev(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) {
2754 IoVec<ScopedBytesRO> ioVec(env, env->GetArrayLength(buffers));
2755 if (!ioVec.init(buffers, offsets, byteCounts)) {
2756 return -1;
2757 }
2758 return IO_FAILURE_RETRY(env, ssize_t, writev, javaFd, ioVec.get(), ioVec.size());
2759 }
2760
2761 #define NATIVE_METHOD_OVERLOAD(className, functionName, signature, variant) \
2762 { #functionName, signature, reinterpret_cast<void*>(className ## _ ## functionName ## variant) }
2763
2764 static JNINativeMethod gMethods[] = {
2765 NATIVE_METHOD(Linux, accept, "(Ljava/io/FileDescriptor;Ljava/net/SocketAddress;)Ljava/io/FileDescriptor;"),
2766 NATIVE_METHOD(Linux, access, "(Ljava/lang/String;I)Z"),
2767 NATIVE_METHOD(Linux, android_fdsan_exchange_owner_tag, "(Ljava/io/FileDescriptor;JJ)V"),
2768 NATIVE_METHOD(Linux, android_fdsan_get_owner_tag, "(Ljava/io/FileDescriptor;)J"),
2769 NATIVE_METHOD(Linux, android_fdsan_get_tag_type, "(J)Ljava/lang/String;"),
2770 NATIVE_METHOD(Linux, android_fdsan_get_tag_value, "(J)J"),
2771 NATIVE_METHOD(Linux, android_getaddrinfo, "(Ljava/lang/String;Landroid/system/StructAddrinfo;I)[Ljava/net/InetAddress;"),
2772 NATIVE_METHOD(Linux, bind, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"),
2773 NATIVE_METHOD_OVERLOAD(Linux, bind, "(Ljava/io/FileDescriptor;Ljava/net/SocketAddress;)V", SocketAddress),
2774 NATIVE_METHOD(Linux, capget,
2775 "(Landroid/system/StructCapUserHeader;)[Landroid/system/StructCapUserData;"),
2776 NATIVE_METHOD(Linux, capset,
2777 "(Landroid/system/StructCapUserHeader;[Landroid/system/StructCapUserData;)V"),
2778 NATIVE_METHOD(Linux, chmod, "(Ljava/lang/String;I)V"),
2779 NATIVE_METHOD(Linux, chown, "(Ljava/lang/String;II)V"),
2780 NATIVE_METHOD(Linux, close, "(Ljava/io/FileDescriptor;)V"),
2781 NATIVE_METHOD(Linux, connect, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"),
2782 NATIVE_METHOD_OVERLOAD(Linux, connect, "(Ljava/io/FileDescriptor;Ljava/net/SocketAddress;)V", SocketAddress),
2783 NATIVE_METHOD(Linux, dup, "(Ljava/io/FileDescriptor;)Ljava/io/FileDescriptor;"),
2784 NATIVE_METHOD(Linux, dup2, "(Ljava/io/FileDescriptor;I)Ljava/io/FileDescriptor;"),
2785 NATIVE_METHOD(Linux, environ, "()[Ljava/lang/String;"),
2786 NATIVE_METHOD(Linux, execv, "(Ljava/lang/String;[Ljava/lang/String;)V"),
2787 NATIVE_METHOD(Linux, execve, "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V"),
2788 NATIVE_METHOD(Linux, fchmod, "(Ljava/io/FileDescriptor;I)V"),
2789 NATIVE_METHOD(Linux, fchown, "(Ljava/io/FileDescriptor;II)V"),
2790 NATIVE_METHOD(Linux, fcntlInt, "(Ljava/io/FileDescriptor;II)I"),
2791 NATIVE_METHOD(Linux, fcntlVoid, "(Ljava/io/FileDescriptor;I)I"),
2792 NATIVE_METHOD(Linux, fdatasync, "(Ljava/io/FileDescriptor;)V"),
2793 NATIVE_METHOD(Linux, fstat, "(Ljava/io/FileDescriptor;)Landroid/system/StructStat;"),
2794 NATIVE_METHOD(Linux, fstatvfs, "(Ljava/io/FileDescriptor;)Landroid/system/StructStatVfs;"),
2795 NATIVE_METHOD(Linux, fsync, "(Ljava/io/FileDescriptor;)V"),
2796 NATIVE_METHOD(Linux, ftruncate, "(Ljava/io/FileDescriptor;J)V"),
2797 NATIVE_METHOD(Linux, gai_strerror, "(I)Ljava/lang/String;"),
2798 NATIVE_METHOD(Linux, getegid, "()I"),
2799 NATIVE_METHOD(Linux, geteuid, "()I"),
2800 NATIVE_METHOD(Linux, getgid, "()I"),
2801 NATIVE_METHOD(Linux, getenv, "(Ljava/lang/String;)Ljava/lang/String;"),
2802 NATIVE_METHOD(Linux, getnameinfo, "(Ljava/net/InetAddress;I)Ljava/lang/String;"),
2803 NATIVE_METHOD(Linux, getpeername, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"),
2804 NATIVE_METHOD(Linux, getpgid, "(I)I"),
2805 NATIVE_METHOD(Linux, getpid, "()I"),
2806 NATIVE_METHOD(Linux, getppid, "()I"),
2807 NATIVE_METHOD(Linux, getpwnam, "(Ljava/lang/String;)Landroid/system/StructPasswd;"),
2808 NATIVE_METHOD(Linux, getpwuid, "(I)Landroid/system/StructPasswd;"),
2809 NATIVE_METHOD(Linux, getrlimit, "(I)Landroid/system/StructRlimit;"),
2810 NATIVE_METHOD(Linux, getsockname, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"),
2811 NATIVE_METHOD(Linux, getsockoptByte, "(Ljava/io/FileDescriptor;II)I"),
2812 NATIVE_METHOD(Linux, getsockoptInAddr, "(Ljava/io/FileDescriptor;II)Ljava/net/InetAddress;"),
2813 NATIVE_METHOD(Linux, getsockoptInt, "(Ljava/io/FileDescriptor;II)I"),
2814 NATIVE_METHOD(Linux, getsockoptLinger, "(Ljava/io/FileDescriptor;II)Landroid/system/StructLinger;"),
2815 NATIVE_METHOD(Linux, getsockoptTimeval, "(Ljava/io/FileDescriptor;II)Landroid/system/StructTimeval;"),
2816 NATIVE_METHOD(Linux, getsockoptUcred, "(Ljava/io/FileDescriptor;II)Landroid/system/StructUcred;"),
2817 NATIVE_METHOD(Linux, gettid, "()I"),
2818 NATIVE_METHOD(Linux, getuid, "()I"),
2819 NATIVE_METHOD(Linux, getxattr, "(Ljava/lang/String;Ljava/lang/String;)[B"),
2820 NATIVE_METHOD(Linux, getifaddrs, "()[Landroid/system/StructIfaddrs;"),
2821 NATIVE_METHOD(Linux, if_indextoname, "(I)Ljava/lang/String;"),
2822 NATIVE_METHOD(Linux, if_nametoindex, "(Ljava/lang/String;)I"),
2823 NATIVE_METHOD(Linux, inet_pton, "(ILjava/lang/String;)Ljava/net/InetAddress;"),
2824 NATIVE_METHOD(Linux, ioctlFlags, "(Ljava/io/FileDescriptor;Ljava/lang/String;)I"),
2825 NATIVE_METHOD(Linux, ioctlInetAddress, "(Ljava/io/FileDescriptor;ILjava/lang/String;)Ljava/net/InetAddress;"),
2826 NATIVE_METHOD(Linux, ioctlInt, "(Ljava/io/FileDescriptor;I)I"),
2827 NATIVE_METHOD(Linux, ioctlMTU, "(Ljava/io/FileDescriptor;Ljava/lang/String;)I"),
2828 NATIVE_METHOD(Linux, isatty, "(Ljava/io/FileDescriptor;)Z"),
2829 NATIVE_METHOD(Linux, kill, "(II)V"),
2830 NATIVE_METHOD(Linux, lchown, "(Ljava/lang/String;II)V"),
2831 NATIVE_METHOD(Linux, link, "(Ljava/lang/String;Ljava/lang/String;)V"),
2832 NATIVE_METHOD(Linux, listen, "(Ljava/io/FileDescriptor;I)V"),
2833 NATIVE_METHOD(Linux, listxattr, "(Ljava/lang/String;)[Ljava/lang/String;"),
2834 NATIVE_METHOD(Linux, lseek, "(Ljava/io/FileDescriptor;JI)J"),
2835 NATIVE_METHOD(Linux, lstat, "(Ljava/lang/String;)Landroid/system/StructStat;"),
2836 NATIVE_METHOD(Linux, memfd_create, "(Ljava/lang/String;I)Ljava/io/FileDescriptor;"),
2837 NATIVE_METHOD(Linux, mincore, "(JJ[B)V"),
2838 NATIVE_METHOD(Linux, mkdir, "(Ljava/lang/String;I)V"),
2839 NATIVE_METHOD(Linux, mkfifo, "(Ljava/lang/String;I)V"),
2840 NATIVE_METHOD(Linux, mlock, "(JJ)V"),
2841 NATIVE_METHOD(Linux, mmap, "(JJIILjava/io/FileDescriptor;J)J"),
2842 NATIVE_METHOD(Linux, msync, "(JJI)V"),
2843 NATIVE_METHOD(Linux, munlock, "(JJ)V"),
2844 NATIVE_METHOD(Linux, munmap, "(JJ)V"),
2845 NATIVE_METHOD(Linux, open, "(Ljava/lang/String;II)Ljava/io/FileDescriptor;"),
2846 NATIVE_METHOD(Linux, pipe2, "(I)[Ljava/io/FileDescriptor;"),
2847 NATIVE_METHOD(Linux, poll, "([Landroid/system/StructPollfd;I)I"),
2848 NATIVE_METHOD(Linux, posix_fallocate, "(Ljava/io/FileDescriptor;JJ)V"),
2849 NATIVE_METHOD(Linux, prctl, "(IJJJJ)I"),
2850 NATIVE_METHOD(Linux, preadBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
2851 NATIVE_METHOD(Linux, pwriteBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
2852 NATIVE_METHOD(Linux, readBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"),
2853 NATIVE_METHOD(Linux, readlink, "(Ljava/lang/String;)Ljava/lang/String;"),
2854 NATIVE_METHOD(Linux, realpath, "(Ljava/lang/String;)Ljava/lang/String;"),
2855 NATIVE_METHOD(Linux, readv, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"),
2856 NATIVE_METHOD(Linux, recvfromBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetSocketAddress;)I"),
2857 NATIVE_METHOD(Linux, recvmsg, "(Ljava/io/FileDescriptor;Landroid/system/StructMsghdr;I)I"),
2858 NATIVE_METHOD(Linux, remove, "(Ljava/lang/String;)V"),
2859 NATIVE_METHOD(Linux, removexattr, "(Ljava/lang/String;Ljava/lang/String;)V"),
2860 NATIVE_METHOD(Linux, rename, "(Ljava/lang/String;Ljava/lang/String;)V"),
2861 NATIVE_METHOD(Linux, sendfile, "(Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;Landroid/system/Int64Ref;J)J"),
2862 NATIVE_METHOD(Linux, sendmsg, "(Ljava/io/FileDescriptor;Landroid/system/StructMsghdr;I)I"),
2863 NATIVE_METHOD(Linux, sendtoBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetAddress;I)I"),
2864 NATIVE_METHOD_OVERLOAD(Linux, sendtoBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/SocketAddress;)I", SocketAddress),
2865 NATIVE_METHOD(Linux, setegid, "(I)V"),
2866 NATIVE_METHOD(Linux, setenv, "(Ljava/lang/String;Ljava/lang/String;Z)V"),
2867 NATIVE_METHOD(Linux, seteuid, "(I)V"),
2868 NATIVE_METHOD(Linux, setgid, "(I)V"),
2869 NATIVE_METHOD(Linux, setpgid, "(II)V"),
2870 NATIVE_METHOD(Linux, setregid, "(II)V"),
2871 NATIVE_METHOD(Linux, setreuid, "(II)V"),
2872 NATIVE_METHOD(Linux, setsid, "()I"),
2873 NATIVE_METHOD(Linux, setsockoptByte, "(Ljava/io/FileDescriptor;III)V"),
2874 NATIVE_METHOD(Linux, setsockoptIfreq, "(Ljava/io/FileDescriptor;IILjava/lang/String;)V"),
2875 NATIVE_METHOD(Linux, setsockoptInt, "(Ljava/io/FileDescriptor;III)V"),
2876 NATIVE_METHOD(Linux, setsockoptIpMreqn, "(Ljava/io/FileDescriptor;III)V"),
2877 NATIVE_METHOD(Linux, setsockoptGroupReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupReq;)V"),
2878 NATIVE_METHOD(Linux, setsockoptLinger, "(Ljava/io/FileDescriptor;IILandroid/system/StructLinger;)V"),
2879 NATIVE_METHOD(Linux, setsockoptTimeval, "(Ljava/io/FileDescriptor;IILandroid/system/StructTimeval;)V"),
2880 NATIVE_METHOD(Linux, setuid, "(I)V"),
2881 NATIVE_METHOD(Linux, setxattr, "(Ljava/lang/String;Ljava/lang/String;[BI)V"),
2882 NATIVE_METHOD(Linux, shutdown, "(Ljava/io/FileDescriptor;I)V"),
2883 NATIVE_METHOD(Linux, socket, "(III)Ljava/io/FileDescriptor;"),
2884 NATIVE_METHOD(Linux, socketpair, "(IIILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V"),
2885 NATIVE_METHOD(Linux, splice, "(Ljava/io/FileDescriptor;Landroid/system/Int64Ref;Ljava/io/FileDescriptor;Landroid/system/Int64Ref;JI)J"),
2886 NATIVE_METHOD(Linux, stat, "(Ljava/lang/String;)Landroid/system/StructStat;"),
2887 NATIVE_METHOD(Linux, statvfs, "(Ljava/lang/String;)Landroid/system/StructStatVfs;"),
2888 NATIVE_METHOD(Linux, strerror, "(I)Ljava/lang/String;"),
2889 NATIVE_METHOD(Linux, strsignal, "(I)Ljava/lang/String;"),
2890 NATIVE_METHOD(Linux, symlink, "(Ljava/lang/String;Ljava/lang/String;)V"),
2891 NATIVE_METHOD(Linux, sysconf, "(I)J"),
2892 NATIVE_METHOD(Linux, tcdrain, "(Ljava/io/FileDescriptor;)V"),
2893 NATIVE_METHOD(Linux, tcsendbreak, "(Ljava/io/FileDescriptor;I)V"),
2894 NATIVE_METHOD(Linux, umaskImpl, "(I)I"),
2895 NATIVE_METHOD(Linux, uname, "()Landroid/system/StructUtsname;"),
2896 NATIVE_METHOD(Linux, unlink, "(Ljava/lang/String;)V"),
2897 NATIVE_METHOD(Linux, unsetenv, "(Ljava/lang/String;)V"),
2898 NATIVE_METHOD(Linux, waitpid, "(ILandroid/system/Int32Ref;I)I"),
2899 NATIVE_METHOD(Linux, writeBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"),
2900 NATIVE_METHOD(Linux, writev, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"),
2901 };
register_libcore_io_Linux(JNIEnv * env)2902 void register_libcore_io_Linux(JNIEnv* env) {
2903 // Note: it is safe to only cache the fields as boot classpath classes are never
2904 // unloaded.
2905 ScopedLocalRef<jclass> int32RefClass(env, env->FindClass("android/system/Int32Ref"));
2906 CHECK(int32RefClass != nullptr);
2907 int32RefValueFid = env->GetFieldID(int32RefClass.get(), "value", "I");
2908 CHECK(int32RefValueFid != nullptr);
2909
2910 ScopedLocalRef<jclass> int64RefClass(env, env->FindClass("android/system/Int64Ref"));
2911 CHECK(int64RefClass != nullptr);
2912 int64RefValueFid = env->GetFieldID(int64RefClass.get(), "value", "J");
2913 CHECK(int64RefValueFid != nullptr);
2914
2915 jniRegisterNativeMethods(env, "libcore/io/Linux", gMethods, NELEM(gMethods));
2916 }
2917