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 #include<stdio.h>
36 #include <dlfcn.h>
37 #include <limits.h>
38 #include <unistd.h>
39 
40 #include "common_throws.h"
41 #include "gc/heap.h"
42 #include "thread.h"
43 #include "thread_list.h"
44 #include "runtime.h"
45 #include "handle_scope-inl.h"
46 #include "scoped_thread_state_change.h"
47 #include "ScopedUtfChars.h"
48 #include "mirror/class_loader.h"
49 #include "verify_object-inl.h"
50 #include "base/logging.h"
51 #include "base/macros.h"
52 #include "../../libcore/ojluni/src/main/native/jvm.h"  // TODO(narayan): fix it
53 #include "jni_internal.h"
54 #include "mirror/string-inl.h"
55 #include "native/scoped_fast_native_object_access.h"
56 #include "ScopedLocalRef.h"
57 #include <sys/time.h>
58 #include <sys/socket.h>
59 #include <sys/ioctl.h>
60 
61 #undef LOG_TAG
62 #define LOG_TAG "artopenjdk"
63 
64 using art::WARNING;
65 using art::INFO;
66 using art::ERROR;
67 using art::FATAL;
68 
69 /* posix open() with extensions; used by e.g. ZipFile */
JVM_Open(const char * fname,jint flags,jint mode)70 JNIEXPORT jint JVM_Open(const char* fname, jint flags, jint mode) {
71     /*
72      * The call is expected to handle JVM_O_DELETE, which causes the file
73      * to be removed after it is opened.  Also, some code seems to
74      * want the special return value JVM_EEXIST if the file open fails
75      * due to O_EXCL.
76      */
77     int fd = TEMP_FAILURE_RETRY(open(fname, flags & ~JVM_O_DELETE, mode));
78     if (fd < 0) {
79         int err = errno;
80         if (err == EEXIST) {
81             return JVM_EEXIST;
82         } else {
83             return -1;
84         }
85     }
86 
87     if (flags & JVM_O_DELETE) {
88         if (unlink(fname) != 0) {
89             LOG(WARNING) << "Post-open deletion of '" << fname << "' failed: " << strerror(errno);
90         }
91     }
92 
93     return fd;
94 }
95 
96 /* posix close() */
JVM_Close(jint fd)97 JNIEXPORT jint JVM_Close(jint fd) {
98     // don't want TEMP_FAILURE_RETRY here -- file is closed even if EINTR
99     return close(fd);
100 }
101 
102 /* posix read() */
JVM_Read(jint fd,char * buf,jint nbytes)103 JNIEXPORT jint JVM_Read(jint fd, char* buf, jint nbytes) {
104     return TEMP_FAILURE_RETRY(read(fd, buf, nbytes));
105 }
106 
107 /* posix write(); is used to write messages to stderr */
JVM_Write(jint fd,char * buf,jint nbytes)108 JNIEXPORT jint JVM_Write(jint fd, char* buf, jint nbytes) {
109     return TEMP_FAILURE_RETRY(write(fd, buf, nbytes));
110 }
111 
112 /* posix lseek() */
JVM_Lseek(jint fd,jlong offset,jint whence)113 JNIEXPORT jlong JVM_Lseek(jint fd, jlong offset, jint whence) {
114 #if !defined(__APPLE__)
115     // NOTE: Using TEMP_FAILURE_RETRY here is busted for LP32 on glibc - the return
116     // value will be coerced into an int32_t.
117     //
118     // lseek64 isn't specified to return EINTR so it shouldn't be necessary
119     // anyway.
120     return lseek64(fd, offset, whence);
121 #else
122     // NOTE: This code is compiled for Mac OS but isn't ever run on that
123     // platform.
124     return lseek(fd, offset, whence);
125 #endif
126 }
127 
128 /*
129  * "raw monitors" seem to be expected to behave like non-recursive pthread
130  * mutexes.  They're used by ZipFile.
131  */
JVM_RawMonitorCreate(void)132 JNIEXPORT void* JVM_RawMonitorCreate(void) {
133     pthread_mutex_t* mutex =
134         reinterpret_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));
135     CHECK(mutex != nullptr);
136     CHECK_PTHREAD_CALL(pthread_mutex_init, (mutex, nullptr), "JVM_RawMonitorCreate");
137     return mutex;
138 }
139 
JVM_RawMonitorDestroy(void * mon)140 JNIEXPORT void JVM_RawMonitorDestroy(void* mon) {
141     CHECK_PTHREAD_CALL(pthread_mutex_destroy,
142                        (reinterpret_cast<pthread_mutex_t*>(mon)),
143                        "JVM_RawMonitorDestroy");
144     free(mon);
145 }
146 
JVM_RawMonitorEnter(void * mon)147 JNIEXPORT jint JVM_RawMonitorEnter(void* mon) {
148     return pthread_mutex_lock(reinterpret_cast<pthread_mutex_t*>(mon));
149 }
150 
JVM_RawMonitorExit(void * mon)151 JNIEXPORT void JVM_RawMonitorExit(void* mon) {
152     CHECK_PTHREAD_CALL(pthread_mutex_unlock,
153                        (reinterpret_cast<pthread_mutex_t*>(mon)),
154                        "JVM_RawMonitorExit");
155 }
156 
JVM_NativePath(char * path)157 JNIEXPORT char* JVM_NativePath(char* path) {
158     return path;
159 }
160 
JVM_GetLastErrorString(char * buf,int len)161 JNIEXPORT jint JVM_GetLastErrorString(char* buf, int len) {
162 #if defined(__GLIBC__) || defined(__BIONIC__)
163   if (len == 0) {
164     return 0;
165   }
166 
167   const int err = errno;
168   char* result = strerror_r(err, buf, len);
169   if (result != buf) {
170     strncpy(buf, result, len);
171     buf[len - 1] = '\0';
172   }
173 
174   return strlen(buf);
175 #else
176   UNUSED(buf);
177   UNUSED(len);
178   return -1;
179 #endif
180 }
181 
jio_fprintf(FILE * fp,const char * fmt,...)182 JNIEXPORT int jio_fprintf(FILE* fp, const char* fmt, ...) {
183     va_list args;
184 
185     va_start(args, fmt);
186     int len = jio_vfprintf(fp, fmt, args);
187     va_end(args);
188 
189     return len;
190 }
191 
jio_vfprintf(FILE * fp,const char * fmt,va_list args)192 JNIEXPORT int jio_vfprintf(FILE* fp, const char* fmt, va_list args) {
193     assert(fp != NULL);
194     return vfprintf(fp, fmt, args);
195 }
196 
197 /* posix fsync() */
JVM_Sync(jint fd)198 JNIEXPORT jint JVM_Sync(jint fd) {
199     return TEMP_FAILURE_RETRY(fsync(fd));
200 }
201 
JVM_FindLibraryEntry(void * handle,const char * name)202 JNIEXPORT void* JVM_FindLibraryEntry(void* handle, const char* name) {
203     return dlsym(handle, name);
204 }
205 
JVM_CurrentTimeMillis(JNIEnv * env ATTRIBUTE_UNUSED,jclass clazz ATTRIBUTE_UNUSED)206 JNIEXPORT jlong JVM_CurrentTimeMillis(JNIEnv* env ATTRIBUTE_UNUSED,
207                                       jclass clazz ATTRIBUTE_UNUSED) {
208     struct timeval tv;
209     gettimeofday(&tv, (struct timezone *) NULL);
210     jlong when = tv.tv_sec * 1000LL + tv.tv_usec / 1000;
211     return when;
212 }
213 
JVM_Socket(jint domain,jint type,jint protocol)214 JNIEXPORT jint JVM_Socket(jint domain, jint type, jint protocol) {
215     return TEMP_FAILURE_RETRY(socket(domain, type, protocol));
216 }
217 
JVM_InitializeSocketLibrary()218 JNIEXPORT jint JVM_InitializeSocketLibrary() {
219   return 0;
220 }
221 
jio_vsnprintf(char * str,size_t count,const char * fmt,va_list args)222 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
223   if ((intptr_t)count <= 0) return -1;
224   return vsnprintf(str, count, fmt, args);
225 }
226 
jio_snprintf(char * str,size_t count,const char * fmt,...)227 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
228   va_list args;
229   int len;
230   va_start(args, fmt);
231   len = jio_vsnprintf(str, count, fmt, args);
232   va_end(args);
233   return len;
234 }
235 
JVM_SetSockOpt(jint fd,int level,int optname,const char * optval,int optlen)236 JNIEXPORT jint JVM_SetSockOpt(jint fd, int level, int optname,
237     const char* optval, int optlen) {
238   return TEMP_FAILURE_RETRY(setsockopt(fd, level, optname, optval, optlen));
239 }
240 
JVM_SocketShutdown(jint fd,jint howto)241 JNIEXPORT jint JVM_SocketShutdown(jint fd, jint howto) {
242   return TEMP_FAILURE_RETRY(shutdown(fd, howto));
243 }
244 
JVM_GetSockOpt(jint fd,int level,int optname,char * optval,int * optlen)245 JNIEXPORT jint JVM_GetSockOpt(jint fd, int level, int optname, char* optval,
246   int* optlen) {
247   socklen_t len = *optlen;
248   int cc = TEMP_FAILURE_RETRY(getsockopt(fd, level, optname, optval, &len));
249   *optlen = len;
250   return cc;
251 }
252 
JVM_GetSockName(jint fd,struct sockaddr * addr,int * addrlen)253 JNIEXPORT jint JVM_GetSockName(jint fd, struct sockaddr* addr, int* addrlen) {
254   socklen_t len = *addrlen;
255   int cc = TEMP_FAILURE_RETRY(getsockname(fd, addr, &len));
256   *addrlen = len;
257   return cc;
258 }
259 
JVM_SocketAvailable(jint fd,jint * result)260 JNIEXPORT jint JVM_SocketAvailable(jint fd, jint* result) {
261   if (TEMP_FAILURE_RETRY(ioctl(fd, FIONREAD, result)) < 0) {
262       return JNI_FALSE;
263   }
264 
265   return JNI_TRUE;
266 }
267 
JVM_Send(jint fd,char * buf,jint nBytes,jint flags)268 JNIEXPORT jint JVM_Send(jint fd, char* buf, jint nBytes, jint flags) {
269   return TEMP_FAILURE_RETRY(send(fd, buf, nBytes, flags));
270 }
271 
JVM_SocketClose(jint fd)272 JNIEXPORT jint JVM_SocketClose(jint fd) {
273   // Don't want TEMP_FAILURE_RETRY here -- file is closed even if EINTR.
274   return close(fd);
275 }
276 
JVM_Listen(jint fd,jint count)277 JNIEXPORT jint JVM_Listen(jint fd, jint count) {
278   return TEMP_FAILURE_RETRY(listen(fd, count));
279 }
280 
JVM_Connect(jint fd,struct sockaddr * addr,jint addrlen)281 JNIEXPORT jint JVM_Connect(jint fd, struct sockaddr* addr, jint addrlen) {
282   return TEMP_FAILURE_RETRY(connect(fd, addr, addrlen));
283 }
284 
JVM_GetHostName(char * name,int namelen)285 JNIEXPORT int JVM_GetHostName(char* name, int namelen) {
286   return TEMP_FAILURE_RETRY(gethostname(name, namelen));
287 }
288 
JVM_InternString(JNIEnv * env,jstring jstr)289 JNIEXPORT jstring JVM_InternString(JNIEnv* env, jstring jstr) {
290   art::ScopedFastNativeObjectAccess soa(env);
291   art::mirror::String* s = soa.Decode<art::mirror::String*>(jstr);
292   art::mirror::String* result = s->Intern();
293   return soa.AddLocalReference<jstring>(result);
294 }
295 
JVM_FreeMemory(void)296 JNIEXPORT jlong JVM_FreeMemory(void) {
297   return art::Runtime::Current()->GetHeap()->GetFreeMemory();
298 }
299 
JVM_TotalMemory(void)300 JNIEXPORT jlong JVM_TotalMemory(void) {
301   return art::Runtime::Current()->GetHeap()->GetTotalMemory();
302 }
303 
JVM_MaxMemory(void)304 JNIEXPORT jlong JVM_MaxMemory(void) {
305   return art::Runtime::Current()->GetHeap()->GetMaxMemory();
306 }
307 
JVM_GC(void)308 JNIEXPORT void JVM_GC(void) {
309   if (art::Runtime::Current()->IsExplicitGcDisabled()) {
310       LOG(INFO) << "Explicit GC skipped.";
311       return;
312   }
313   art::Runtime::Current()->GetHeap()->CollectGarbage(false);
314 }
315 
JVM_Exit(jint status)316 JNIEXPORT __attribute__((noreturn)) void JVM_Exit(jint status) {
317   LOG(INFO) << "System.exit called, status: " << status;
318   art::Runtime::Current()->CallExitHook(status);
319   exit(status);
320 }
321 
JVM_NativeLoad(JNIEnv * env,jstring javaFilename,jobject javaLoader,jstring javaLibrarySearchPath)322 JNIEXPORT jstring JVM_NativeLoad(JNIEnv* env,
323                                  jstring javaFilename,
324                                  jobject javaLoader,
325                                  jstring javaLibrarySearchPath) {
326   ScopedUtfChars filename(env, javaFilename);
327   if (filename.c_str() == NULL) {
328     return NULL;
329   }
330 
331   std::string error_msg;
332   {
333     art::JavaVMExt* vm = art::Runtime::Current()->GetJavaVM();
334     bool success = vm->LoadNativeLibrary(env,
335                                          filename.c_str(),
336                                          javaLoader,
337                                          javaLibrarySearchPath,
338                                          &error_msg);
339     if (success) {
340       return nullptr;
341     }
342   }
343 
344   // Don't let a pending exception from JNI_OnLoad cause a CheckJNI issue with NewStringUTF.
345   env->ExceptionClear();
346   return env->NewStringUTF(error_msg.c_str());
347 }
348 
JVM_StartThread(JNIEnv * env,jobject jthread,jlong stack_size,jboolean daemon)349 JNIEXPORT void JVM_StartThread(JNIEnv* env, jobject jthread, jlong stack_size, jboolean daemon) {
350   art::Thread::CreateNativeThread(env, jthread, stack_size, daemon == JNI_TRUE);
351 }
352 
JVM_SetThreadPriority(JNIEnv * env,jobject jthread,jint prio)353 JNIEXPORT void JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio) {
354   art::ScopedObjectAccess soa(env);
355   art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
356   art::Thread* thread = art::Thread::FromManagedThread(soa, jthread);
357   if (thread != NULL) {
358     thread->SetNativePriority(prio);
359   }
360 }
361 
JVM_Yield(JNIEnv * env ATTRIBUTE_UNUSED,jclass threadClass ATTRIBUTE_UNUSED)362 JNIEXPORT void JVM_Yield(JNIEnv* env ATTRIBUTE_UNUSED, jclass threadClass ATTRIBUTE_UNUSED) {
363   sched_yield();
364 }
365 
JVM_Sleep(JNIEnv * env,jclass threadClass ATTRIBUTE_UNUSED,jobject java_lock,jlong millis)366 JNIEXPORT void JVM_Sleep(JNIEnv* env, jclass threadClass ATTRIBUTE_UNUSED,
367                          jobject java_lock, jlong millis) {
368   art::ScopedFastNativeObjectAccess soa(env);
369   art::mirror::Object* lock = soa.Decode<art::mirror::Object*>(java_lock);
370   art::Monitor::Wait(art::Thread::Current(), lock, millis, 0, true, art::kSleeping);
371 }
372 
JVM_CurrentThread(JNIEnv * env,jclass unused ATTRIBUTE_UNUSED)373 JNIEXPORT jobject JVM_CurrentThread(JNIEnv* env, jclass unused ATTRIBUTE_UNUSED) {
374   art::ScopedFastNativeObjectAccess soa(env);
375   return soa.AddLocalReference<jobject>(soa.Self()->GetPeer());
376 }
377 
JVM_Interrupt(JNIEnv * env,jobject jthread)378 JNIEXPORT void JVM_Interrupt(JNIEnv* env, jobject jthread) {
379   art::ScopedFastNativeObjectAccess soa(env);
380   art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
381   art::Thread* thread = art::Thread::FromManagedThread(soa, jthread);
382   if (thread != nullptr) {
383     thread->Interrupt(soa.Self());
384   }
385 }
386 
JVM_IsInterrupted(JNIEnv * env,jobject jthread,jboolean clearInterrupted)387 JNIEXPORT jboolean JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clearInterrupted) {
388   if (clearInterrupted) {
389     return static_cast<art::JNIEnvExt*>(env)->self->Interrupted() ? JNI_TRUE : JNI_FALSE;
390   } else {
391     art::ScopedFastNativeObjectAccess soa(env);
392     art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
393     art::Thread* thread = art::Thread::FromManagedThread(soa, jthread);
394     return (thread != nullptr) ? thread->IsInterrupted() : JNI_FALSE;
395   }
396 }
397 
JVM_HoldsLock(JNIEnv * env,jclass unused ATTRIBUTE_UNUSED,jobject jobj)398 JNIEXPORT jboolean JVM_HoldsLock(JNIEnv* env, jclass unused ATTRIBUTE_UNUSED, jobject jobj) {
399   art::ScopedObjectAccess soa(env);
400   art::mirror::Object* object = soa.Decode<art::mirror::Object*>(jobj);
401   if (object == NULL) {
402     art::ThrowNullPointerException("object == null");
403     return JNI_FALSE;
404   }
405   return soa.Self()->HoldsLock(object);
406 }
407 
JVM_SetNativeThreadName(JNIEnv * env,jobject jthread,jstring java_name)408 JNIEXPORT void JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring java_name) {
409   ScopedUtfChars name(env, java_name);
410   {
411     art::ScopedObjectAccess soa(env);
412     if (soa.Decode<art::mirror::Object*>(jthread) == soa.Self()->GetPeer()) {
413       soa.Self()->SetThreadName(name.c_str());
414       return;
415     }
416   }
417   // Suspend thread to avoid it from killing itself while we set its name. We don't just hold the
418   // thread list lock to avoid this, as setting the thread name causes mutator to lock/unlock
419   // in the DDMS send code.
420   art::ThreadList* thread_list = art::Runtime::Current()->GetThreadList();
421   bool timed_out;
422   // Take suspend thread lock to avoid races with threads trying to suspend this one.
423   art::Thread* thread;
424   {
425     thread = thread_list->SuspendThreadByPeer(jthread, true, false, &timed_out);
426   }
427   if (thread != NULL) {
428     {
429       art::ScopedObjectAccess soa(env);
430       thread->SetThreadName(name.c_str());
431     }
432     thread_list->Resume(thread, false);
433   } else if (timed_out) {
434     LOG(ERROR) << "Trying to set thread name to '" << name.c_str() << "' failed as the thread "
435         "failed to suspend within a generous timeout.";
436   }
437 }
438 
JVM_IHashCode(JNIEnv * env ATTRIBUTE_UNUSED,jobject javaObject ATTRIBUTE_UNUSED)439 JNIEXPORT jint JVM_IHashCode(JNIEnv* env ATTRIBUTE_UNUSED,
440                              jobject javaObject ATTRIBUTE_UNUSED) {
441   UNIMPLEMENTED(FATAL) << "JVM_IHashCode is not implemented";
442   return 0;
443 }
444 
JVM_NanoTime(JNIEnv * env ATTRIBUTE_UNUSED,jclass unused ATTRIBUTE_UNUSED)445 JNIEXPORT jlong JVM_NanoTime(JNIEnv* env ATTRIBUTE_UNUSED, jclass unused ATTRIBUTE_UNUSED) {
446   UNIMPLEMENTED(FATAL) << "JVM_NanoTime is not implemented";
447   return 0L;
448 }
449 
JVM_ArrayCopy(JNIEnv *,jclass,jobject,jint,jobject,jint,jint)450 JNIEXPORT void JVM_ArrayCopy(JNIEnv* /* env */, jclass /* unused */, jobject /* javaSrc */,
451                              jint /* srcPos */, jobject /* javaDst */, jint /* dstPos */,
452                              jint /* length */) {
453   UNIMPLEMENTED(FATAL) << "JVM_ArrayCopy is not implemented";
454 }
455 
JVM_FindSignal(const char * name ATTRIBUTE_UNUSED)456 JNIEXPORT jint JVM_FindSignal(const char* name ATTRIBUTE_UNUSED) {
457   LOG(FATAL) << "JVM_FindSignal is not implemented";
458   return 0;
459 }
460 
JVM_RegisterSignal(jint signum ATTRIBUTE_UNUSED,void * handler ATTRIBUTE_UNUSED)461 JNIEXPORT void* JVM_RegisterSignal(jint signum ATTRIBUTE_UNUSED, void* handler ATTRIBUTE_UNUSED) {
462   LOG(FATAL) << "JVM_RegisterSignal is not implemented";
463   return nullptr;
464 }
465 
JVM_RaiseSignal(jint signum ATTRIBUTE_UNUSED)466 JNIEXPORT jboolean JVM_RaiseSignal(jint signum ATTRIBUTE_UNUSED) {
467   LOG(FATAL) << "JVM_RaiseSignal is not implemented";
468   return JNI_FALSE;
469 }
470 
JVM_Halt(jint code)471 JNIEXPORT __attribute__((noreturn))  void JVM_Halt(jint code) {
472   exit(code);
473 }
474 
JVM_IsNaN(jdouble d)475 JNIEXPORT jboolean JVM_IsNaN(jdouble d) {
476   return isnan(d);
477 }
478