1 /* Copyright (C) 2014 The Android Open Source Project
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This file implements interfaces from the file jvm.h. This implementation
5 * is licensed under the same terms as the file jvm.h. The
6 * copyright and license information for the file jvm.h follows.
7 *
8 * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
10 *
11 * This code is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 only, as
13 * published by the Free Software Foundation. Oracle designates this
14 * particular file as subject to the "Classpath" exception as provided
15 * by Oracle in the LICENSE file that accompanied this code.
16 *
17 * This code is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
20 * version 2 for more details (a copy is included in the LICENSE file that
21 * accompanied this code).
22 *
23 * You should have received a copy of the GNU General Public License version
24 * 2 along with this work; if not, write to the Free Software Foundation,
25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
26 *
27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
28 * or visit www.oracle.com if you need additional information or have any
29 * questions.
30 */
31
32 /*
33 * Services that OpenJDK expects the VM to provide.
34 */
35
36 #include <assert.h>
37 #include <dlfcn.h>
38 #include <limits.h>
39 #include <stdio.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <sys/time.h>
43 #include <unistd.h>
44
45 #include <android-base/logging.h>
46
47 #include "../../libcore/ojluni/src/main/native/jvm.h" // TODO(narayan): fix it
48
49 #include "base/macros.h"
50 #include "base/fast_exit.h"
51 #include "common_throws.h"
52 #include "gc/heap.h"
53 #include "handle_scope-inl.h"
54 #include "jni/java_vm_ext.h"
55 #include "jni/jni_internal.h"
56 #include "mirror/class_loader.h"
57 #include "mirror/string-inl.h"
58 #include "monitor.h"
59 #include "native/scoped_fast_native_object_access-inl.h"
60 #include "nativehelper/scoped_local_ref.h"
61 #include "nativehelper/scoped_utf_chars.h"
62 #include "runtime.h"
63 #include "scoped_thread_state_change-inl.h"
64 #include "thread.h"
65 #include "thread_list.h"
66 #include "verify_object.h"
67
68 #undef LOG_TAG
69 #define LOG_TAG "artopenjdk"
70
71 /* posix open() with extensions; used by e.g. ZipFile */
JVM_Open(const char * fname,jint flags,jint mode)72 JNIEXPORT jint JVM_Open(const char* fname, jint flags, jint mode) {
73 /*
74 * Some code seems to want the special return value JVM_EEXIST if the
75 * file open fails due to O_EXCL.
76 */
77 // Don't use JVM_O_DELETE, it's problematic with FUSE, see b/28901232.
78 if (flags & JVM_O_DELETE) {
79 LOG(FATAL) << "JVM_O_DELETE option is not supported (while opening: '"
80 << fname << "')";
81 }
82
83 flags |= O_CLOEXEC;
84 int fd = TEMP_FAILURE_RETRY(open(fname, flags & ~JVM_O_DELETE, mode));
85 if (fd < 0) {
86 int err = errno;
87 if (err == EEXIST) {
88 return JVM_EEXIST;
89 } else {
90 return -1;
91 }
92 }
93
94 return fd;
95 }
96
97 /* posix close() */
JVM_Close(jint fd)98 JNIEXPORT jint JVM_Close(jint fd) {
99 // don't want TEMP_FAILURE_RETRY here -- file is closed even if EINTR
100 return close(fd);
101 }
102
103 /* posix read() */
JVM_Read(jint fd,char * buf,jint nbytes)104 JNIEXPORT jint JVM_Read(jint fd, char* buf, jint nbytes) {
105 return TEMP_FAILURE_RETRY(read(fd, buf, nbytes));
106 }
107
108 /* posix write(); is used to write messages to stderr */
JVM_Write(jint fd,char * buf,jint nbytes)109 JNIEXPORT jint JVM_Write(jint fd, char* buf, jint nbytes) {
110 return TEMP_FAILURE_RETRY(write(fd, buf, nbytes));
111 }
112
113 /* posix lseek() */
JVM_Lseek(jint fd,jlong offset,jint whence)114 JNIEXPORT jlong JVM_Lseek(jint fd, jlong offset, jint whence) {
115 #if !defined(__APPLE__)
116 // NOTE: Using TEMP_FAILURE_RETRY here is busted for LP32 on glibc - the return
117 // value will be coerced into an int32_t.
118 //
119 // lseek64 isn't specified to return EINTR so it shouldn't be necessary
120 // anyway.
121 return lseek64(fd, offset, whence);
122 #else
123 // NOTE: This code is compiled for Mac OS but isn't ever run on that
124 // platform.
125 return lseek(fd, offset, whence);
126 #endif
127 }
128
129 /*
130 * "raw monitors" seem to be expected to behave like non-recursive pthread
131 * mutexes. They're used by ZipFile.
132 */
JVM_RawMonitorCreate(void)133 JNIEXPORT void* JVM_RawMonitorCreate(void) {
134 pthread_mutex_t* mutex =
135 reinterpret_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));
136 CHECK(mutex != nullptr);
137 CHECK_PTHREAD_CALL(pthread_mutex_init, (mutex, nullptr), "JVM_RawMonitorCreate");
138 return mutex;
139 }
140
JVM_RawMonitorDestroy(void * mon)141 JNIEXPORT void JVM_RawMonitorDestroy(void* mon) {
142 CHECK_PTHREAD_CALL(pthread_mutex_destroy,
143 (reinterpret_cast<pthread_mutex_t*>(mon)),
144 "JVM_RawMonitorDestroy");
145 free(mon);
146 }
147
JVM_RawMonitorEnter(void * mon)148 JNIEXPORT jint JVM_RawMonitorEnter(void* mon) {
149 return pthread_mutex_lock(reinterpret_cast<pthread_mutex_t*>(mon));
150 }
151
JVM_RawMonitorExit(void * mon)152 JNIEXPORT void JVM_RawMonitorExit(void* mon) {
153 CHECK_PTHREAD_CALL(pthread_mutex_unlock,
154 (reinterpret_cast<pthread_mutex_t*>(mon)),
155 "JVM_RawMonitorExit");
156 }
157
JVM_NativePath(char * path)158 JNIEXPORT char* JVM_NativePath(char* path) {
159 return path;
160 }
161
JVM_GetLastErrorString(char * buf,int len)162 JNIEXPORT jint JVM_GetLastErrorString(char* buf, int len) {
163 #if defined(__GLIBC__) || defined(__BIONIC__)
164 if (len == 0) {
165 return 0;
166 }
167
168 const int err = errno;
169 char* result = strerror_r(err, buf, len);
170 if (result != buf) {
171 strncpy(buf, result, len);
172 buf[len - 1] = '\0';
173 }
174
175 return strlen(buf);
176 #else
177 UNUSED(buf);
178 UNUSED(len);
179 return -1;
180 #endif
181 }
182
jio_fprintf(FILE * fp,const char * fmt,...)183 JNIEXPORT int jio_fprintf(FILE* fp, const char* fmt, ...) {
184 va_list args;
185
186 va_start(args, fmt);
187 int len = jio_vfprintf(fp, fmt, args);
188 va_end(args);
189
190 return len;
191 }
192
jio_vfprintf(FILE * fp,const char * fmt,va_list args)193 JNIEXPORT int jio_vfprintf(FILE* fp, const char* fmt, va_list args) {
194 assert(fp != nullptr);
195 return vfprintf(fp, fmt, args);
196 }
197
198 /* posix fsync() */
JVM_Sync(jint fd)199 JNIEXPORT jint JVM_Sync(jint fd) {
200 return TEMP_FAILURE_RETRY(fsync(fd));
201 }
202
JVM_FindLibraryEntry(void * handle,const char * name)203 JNIEXPORT void* JVM_FindLibraryEntry(void* handle, const char* name) {
204 return dlsym(handle, name);
205 }
206
JVM_CurrentTimeMillis(JNIEnv * env,jclass clazz)207 JNIEXPORT jlong JVM_CurrentTimeMillis([[maybe_unused]] JNIEnv* env, [[maybe_unused]] jclass clazz) {
208 struct timeval tv;
209 gettimeofday(&tv, (struct timezone *) nullptr);
210 jlong when = tv.tv_sec * 1000LL + tv.tv_usec / 1000;
211 return when;
212 }
213
214 /**
215 * See the spec of this function in jdk.internal.misc.VM.
216 * @return -1 if the system time isn't within +/- 2^32 seconds from offset_secs
217 */
JVM_GetNanoTimeAdjustment(JNIEnv *,jclass,jlong offset_secs)218 JNIEXPORT jlong JVM_GetNanoTimeAdjustment([[maybe_unused]] JNIEnv*,
219 [[maybe_unused]] jclass,
220 jlong offset_secs) {
221 struct timeval tv;
222 // Note that we don't want the elapsed time here, but the system clock.
223 // gettimeofday() doesn't provide nanosecond-level precision.
224 // clock_gettime(CLOCK_REALTIME, tp) may provide nanosecond-level precision.
225 // If it does support higher precision, we should switch both
226 // JVM_CurrentTimeMillis and JVM_GetNanoTimeAdjustment to use clock_gettime
227 // instead of gettimeofday() because various callers assume that
228 // System.currentTimeMillis() and VM.getNanoTimeAdjustment(offset) use the
229 // same time source.
230 gettimeofday(&tv, (struct timezone *) nullptr);
231 jlong sec_diff = ((jlong) tv.tv_sec) - offset_secs;
232 const jlong max_diff = ((jlong) 1) << 32;
233 const jlong min_diff = -max_diff;
234 if (sec_diff >= max_diff || sec_diff <= min_diff) {
235 return -1;
236 }
237 jlong usec_diff = sec_diff * 1000000LL + tv.tv_usec;
238 return usec_diff * 1000;
239 }
240
JVM_Socket(jint domain,jint type,jint protocol)241 JNIEXPORT jint JVM_Socket(jint domain, jint type, jint protocol) {
242 return TEMP_FAILURE_RETRY(socket(domain, type, protocol));
243 }
244
JVM_InitializeSocketLibrary()245 JNIEXPORT jint JVM_InitializeSocketLibrary() {
246 return 0;
247 }
248
jio_vsnprintf(char * str,size_t count,const char * fmt,va_list args)249 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
250 if ((intptr_t)count <= 0) return -1;
251 return vsnprintf(str, count, fmt, args);
252 }
253
jio_snprintf(char * str,size_t count,const char * fmt,...)254 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
255 va_list args;
256 int len;
257 va_start(args, fmt);
258 len = jio_vsnprintf(str, count, fmt, args);
259 va_end(args);
260 return len;
261 }
262
JVM_SetSockOpt(jint fd,int level,int optname,const char * optval,int optlen)263 JNIEXPORT jint JVM_SetSockOpt(jint fd, int level, int optname,
264 const char* optval, int optlen) {
265 return TEMP_FAILURE_RETRY(setsockopt(fd, level, optname, optval, optlen));
266 }
267
JVM_SocketShutdown(jint fd,jint howto)268 JNIEXPORT jint JVM_SocketShutdown(jint fd, jint howto) {
269 return TEMP_FAILURE_RETRY(shutdown(fd, howto));
270 }
271
JVM_GetSockOpt(jint fd,int level,int optname,char * optval,int * optlen)272 JNIEXPORT jint JVM_GetSockOpt(jint fd, int level, int optname, char* optval,
273 int* optlen) {
274 socklen_t len = *optlen;
275 int cc = TEMP_FAILURE_RETRY(getsockopt(fd, level, optname, optval, &len));
276 *optlen = len;
277 return cc;
278 }
279
JVM_GetSockName(jint fd,struct sockaddr * addr,int * addrlen)280 JNIEXPORT jint JVM_GetSockName(jint fd, struct sockaddr* addr, int* addrlen) {
281 socklen_t len = *addrlen;
282 int cc = TEMP_FAILURE_RETRY(getsockname(fd, addr, &len));
283 *addrlen = len;
284 return cc;
285 }
286
JVM_SocketAvailable(jint fd,jint * result)287 JNIEXPORT jint JVM_SocketAvailable(jint fd, jint* result) {
288 if (TEMP_FAILURE_RETRY(ioctl(fd, FIONREAD, result)) < 0) {
289 return JNI_FALSE;
290 }
291
292 return JNI_TRUE;
293 }
294
JVM_Send(jint fd,char * buf,jint nBytes,jint flags)295 JNIEXPORT jint JVM_Send(jint fd, char* buf, jint nBytes, jint flags) {
296 return TEMP_FAILURE_RETRY(send(fd, buf, nBytes, flags));
297 }
298
JVM_SocketClose(jint fd)299 JNIEXPORT jint JVM_SocketClose(jint fd) {
300 // Don't want TEMP_FAILURE_RETRY here -- file is closed even if EINTR.
301 return close(fd);
302 }
303
JVM_Listen(jint fd,jint count)304 JNIEXPORT jint JVM_Listen(jint fd, jint count) {
305 return TEMP_FAILURE_RETRY(listen(fd, count));
306 }
307
JVM_Connect(jint fd,struct sockaddr * addr,jint addrlen)308 JNIEXPORT jint JVM_Connect(jint fd, struct sockaddr* addr, jint addrlen) {
309 return TEMP_FAILURE_RETRY(connect(fd, addr, addrlen));
310 }
311
JVM_GetHostName(char * name,int namelen)312 JNIEXPORT int JVM_GetHostName(char* name, int namelen) {
313 return TEMP_FAILURE_RETRY(gethostname(name, namelen));
314 }
315
JVM_InternString(JNIEnv * env,jstring jstr)316 JNIEXPORT jstring JVM_InternString(JNIEnv* env, jstring jstr) {
317 art::ScopedFastNativeObjectAccess soa(env);
318 art::ObjPtr<art::mirror::String> s = soa.Decode<art::mirror::String>(jstr);
319 return soa.AddLocalReference<jstring>(s->Intern());
320 }
321
JVM_FreeMemory(void)322 JNIEXPORT jlong JVM_FreeMemory(void) {
323 return art::Runtime::Current()->GetHeap()->GetFreeMemory();
324 }
325
JVM_TotalMemory(void)326 JNIEXPORT jlong JVM_TotalMemory(void) {
327 return art::Runtime::Current()->GetHeap()->GetTotalMemory();
328 }
329
JVM_MaxMemory(void)330 JNIEXPORT jlong JVM_MaxMemory(void) {
331 return art::Runtime::Current()->GetHeap()->GetMaxMemory();
332 }
333
JVM_GC(void)334 JNIEXPORT void JVM_GC(void) {
335 if (art::Runtime::Current()->IsExplicitGcDisabled()) {
336 LOG(INFO) << "Explicit GC skipped.";
337 return;
338 }
339 art::Runtime::Current()->GetHeap()->CollectGarbage(/* clear_soft_references */ false);
340 }
341
JVM_Exit(jint status)342 JNIEXPORT __attribute__((noreturn)) void JVM_Exit(jint status) {
343 LOG(INFO) << "System.exit called, status: " << status;
344 art::Runtime::Current()->CallExitHook(status);
345 // Unsafe to call exit() while threads may still be running. They would race
346 // with static destructors.
347 art::FastExit(status);
348 }
349
JVM_NativeLoad(JNIEnv * env,jstring javaFilename,jobject javaLoader,jclass caller)350 JNIEXPORT jstring JVM_NativeLoad(JNIEnv* env,
351 jstring javaFilename,
352 jobject javaLoader,
353 jclass caller) {
354 ScopedUtfChars filename(env, javaFilename);
355 if (filename.c_str() == nullptr) {
356 return nullptr;
357 }
358
359 std::string error_msg;
360 {
361 art::JavaVMExt* vm = art::Runtime::Current()->GetJavaVM();
362 bool success = vm->LoadNativeLibrary(env,
363 filename.c_str(),
364 javaLoader,
365 caller,
366 &error_msg);
367 if (success) {
368 return nullptr;
369 }
370 }
371
372 // Don't let a pending exception from JNI_OnLoad cause a CheckJNI issue with NewStringUTF.
373 env->ExceptionClear();
374 return env->NewStringUTF(error_msg.c_str());
375 }
376
JVM_StartThread(JNIEnv * env,jobject jthread,jlong stack_size,jboolean daemon)377 JNIEXPORT void JVM_StartThread(JNIEnv* env, jobject jthread, jlong stack_size, jboolean daemon) {
378 art::Thread::CreateNativeThread(env, jthread, stack_size, daemon == JNI_TRUE);
379 }
380
JVM_SetThreadPriority(JNIEnv * env,jobject jthread,jint prio)381 JNIEXPORT void JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio) {
382 art::ScopedObjectAccess soa(env);
383 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
384 art::Thread* thread = art::Thread::FromManagedThread(soa, jthread);
385 if (thread != nullptr) {
386 thread->SetNativePriority(prio);
387 }
388 }
389
JVM_Yield(JNIEnv * env,jclass threadClass)390 JNIEXPORT void JVM_Yield([[maybe_unused]] JNIEnv* env, [[maybe_unused]] jclass threadClass) {
391 sched_yield();
392 }
393
JVM_Sleep(JNIEnv * env,jclass threadClass,jobject java_lock,jlong millis)394 JNIEXPORT void JVM_Sleep(JNIEnv* env,
395 [[maybe_unused]] jclass threadClass,
396 jobject java_lock,
397 jlong millis) {
398 art::ScopedFastNativeObjectAccess soa(env);
399 art::ObjPtr<art::mirror::Object> lock = soa.Decode<art::mirror::Object>(java_lock);
400 art::Monitor::Wait(
401 art::Thread::Current(), lock.Ptr(), millis, 0, true, art::ThreadState::kSleeping);
402 }
403
JVM_CurrentThread(JNIEnv * env,jclass unused)404 JNIEXPORT jobject JVM_CurrentThread(JNIEnv* env, [[maybe_unused]] jclass unused) {
405 art::ScopedFastNativeObjectAccess soa(env);
406 return soa.AddLocalReference<jobject>(soa.Self()->GetPeer());
407 }
408
JVM_Interrupt(JNIEnv * env,jobject jthread)409 JNIEXPORT void JVM_Interrupt(JNIEnv* env, jobject jthread) {
410 art::ScopedFastNativeObjectAccess soa(env);
411 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
412 art::Thread* thread = art::Thread::FromManagedThread(soa, jthread);
413 if (thread != nullptr) {
414 thread->Interrupt(soa.Self());
415 }
416 }
417
JVM_IsInterrupted(JNIEnv * env,jobject jthread,jboolean clearInterrupted)418 JNIEXPORT jboolean JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clearInterrupted) {
419 if (clearInterrupted) {
420 return static_cast<art::JNIEnvExt*>(env)->GetSelf()->Interrupted() ? JNI_TRUE : JNI_FALSE;
421 } else {
422 art::ScopedFastNativeObjectAccess soa(env);
423 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
424 art::Thread* thread = art::Thread::FromManagedThread(soa, jthread);
425 return (thread != nullptr) ? thread->IsInterrupted() : JNI_FALSE;
426 }
427 }
428
JVM_HoldsLock(JNIEnv * env,jclass unused,jobject jobj)429 JNIEXPORT jboolean JVM_HoldsLock(JNIEnv* env, [[maybe_unused]] jclass unused, jobject jobj) {
430 art::ScopedObjectAccess soa(env);
431 art::ObjPtr<art::mirror::Object> object = soa.Decode<art::mirror::Object>(jobj);
432 if (object == nullptr) {
433 art::ThrowNullPointerException("object == null");
434 return JNI_FALSE;
435 }
436 return soa.Self()->HoldsLock(object);
437 }
438
JVM_SetNativeThreadName(JNIEnv * env,jobject jthread,jstring java_name)439 JNIEXPORT __attribute__((noreturn)) void JVM_SetNativeThreadName(
440 [[maybe_unused]] JNIEnv* env,
441 [[maybe_unused]] jobject jthread,
442 [[maybe_unused]] jstring java_name) {
443 UNIMPLEMENTED(FATAL) << "JVM_SetNativeThreadName is not implemented";
444 UNREACHABLE();
445 }
446
JVM_IHashCode(JNIEnv * env,jobject javaObject)447 JNIEXPORT __attribute__((noreturn)) jint JVM_IHashCode([[maybe_unused]] JNIEnv* env,
448 [[maybe_unused]] jobject javaObject) {
449 UNIMPLEMENTED(FATAL) << "JVM_IHashCode is not implemented";
450 UNREACHABLE();
451 }
452
JVM_NanoTime(JNIEnv * env,jclass unused)453 JNIEXPORT __attribute__((noreturn)) jlong JVM_NanoTime([[maybe_unused]] JNIEnv* env,
454 [[maybe_unused]] jclass unused) {
455 UNIMPLEMENTED(FATAL) << "JVM_NanoTime is not implemented";
456 UNREACHABLE();
457 }
458
JVM_ArrayCopy(JNIEnv *,jclass,jobject,jint,jobject,jint,jint)459 JNIEXPORT __attribute__((noreturn)) void JVM_ArrayCopy(JNIEnv* /* env */, jclass /* unused */, jobject /* javaSrc */,
460 jint /* srcPos */, jobject /* javaDst */, jint /* dstPos */,
461 jint /* length */) {
462 UNIMPLEMENTED(FATAL) << "JVM_ArrayCopy is not implemented";
463 UNREACHABLE();
464 }
465
JVM_FindSignal(const char * name)466 JNIEXPORT __attribute__((noreturn)) jint JVM_FindSignal([[maybe_unused]] const char* name) {
467 LOG(FATAL) << "JVM_FindSignal is not implemented";
468 UNREACHABLE();
469 }
470
JVM_RegisterSignal(jint signum,void * handler)471 JNIEXPORT __attribute__((noreturn)) void* JVM_RegisterSignal([[maybe_unused]] jint signum,
472 [[maybe_unused]] void* handler) {
473 LOG(FATAL) << "JVM_RegisterSignal is not implemented";
474 UNREACHABLE();
475 }
476
JVM_RaiseSignal(jint signum)477 JNIEXPORT __attribute__((noreturn)) jboolean JVM_RaiseSignal([[maybe_unused]] jint signum) {
478 LOG(FATAL) << "JVM_RaiseSignal is not implemented";
479 UNREACHABLE();
480 }
481
JVM_Halt(jint code)482 JNIEXPORT __attribute__((noreturn)) void JVM_Halt(jint code) {
483 _exit(code);
484 }
485
JVM_IsNaN(jdouble d)486 JNIEXPORT jboolean JVM_IsNaN(jdouble d) {
487 return isnan(d);
488 }
489