2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Native method resolution.
20 * Currently the "Dalvik native" methods are only used for internal methods.
21 * Someday we may want to export the interface as a faster but riskier
29 static void freeSharedLibEntry(void* ptr);
30 static void* lookupSharedLibMethod(const Method* method);
34 * Initialize the native code loader.
36 bool dvmNativeStartup(void)
38 gDvm.nativeLibs = dvmHashTableCreate(4, freeSharedLibEntry);
39 if (gDvm.nativeLibs == NULL)
48 void dvmNativeShutdown(void)
50 dvmHashTableFree(gDvm.nativeLibs);
51 gDvm.nativeLibs = NULL;
56 * Resolve a native method and invoke it.
58 * This is executed as if it were a native bridge or function. If the
59 * resolution succeeds, method->insns is replaced, and we don't go through
60 * here again unless the method is unregistered.
62 * Initializes method's class if necessary.
64 * An exception is thrown on resolution failure.
66 * (This should not be taking "const Method*", because it modifies the
67 * structure, but the declaration needs to match the DalvikBridgeFunc
70 void dvmResolveNativeMethod(const u4* args, JValue* pResult,
71 const Method* method, Thread* self)
73 ClassObject* clazz = method->clazz;
77 * If this is a static method, it could be called before the class
78 * has been initialized.
80 if (dvmIsStaticMethod(method)) {
81 if (!dvmIsClassInitialized(clazz) && !dvmInitClass(clazz)) {
82 assert(dvmCheckException(dvmThreadSelf()));
86 assert(dvmIsClassInitialized(clazz) ||
87 dvmIsClassInitializing(clazz));
90 /* start with our internal-native methods */
91 func = dvmLookupInternalNativeMethod(method);
93 /* resolution always gets the same answer, so no race here */
95 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
96 LOGVV("+++ resolved native %s.%s %s, invoking\n",
97 clazz->descriptor, method->name, desc);
100 if (dvmIsSynchronizedMethod(method)) {
101 LOGE("ERROR: internal-native can't be declared 'synchronized'\n");
102 LOGE("Failing on %s.%s\n", method->clazz->descriptor, method->name);
103 dvmAbort(); // harsh, but this is VM-internal problem
105 DalvikBridgeFunc dfunc = (DalvikBridgeFunc) func;
106 dvmSetNativeFunc((Method*) method, dfunc, NULL);
107 dfunc(args, pResult, method, self);
111 /* now scan any DLLs we have loaded for JNI signatures */
112 func = lookupSharedLibMethod(method);
114 /* found it, point it at the JNI bridge and then call it */
115 dvmUseJNIBridge((Method*) method, func);
116 (*method->nativeFunc)(args, pResult, method, self);
121 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
122 LOGW("No implementation found for native %s.%s %s\n",
123 clazz->descriptor, method->name, desc);
127 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", method->name);
132 * ===========================================================================
133 * Native shared library support
134 * ===========================================================================
137 // TODO? if a ClassLoader is unloaded, we need to unload all DLLs that
138 // are associated with it. (Or not -- can't determine if native code
139 // is still using parts of it.)
141 typedef enum OnLoadState {
142 kOnLoadPending = 0, /* initial state, must be zero */
148 * We add one of these to the hash table for every library we load. The
149 * hash is on the "pathName" field.
151 typedef struct SharedLib {
152 char* pathName; /* absolute path to library */
153 void* handle; /* from dlopen */
154 Object* classLoader; /* ClassLoader we are associated with */
156 pthread_mutex_t onLoadLock; /* guards remaining items */
157 pthread_cond_t onLoadCond; /* wait for JNI_OnLoad in other thread */
158 u4 onLoadThreadId; /* recursive invocation guard */
159 OnLoadState onLoadResult; /* result of earlier JNI_OnLoad */
163 * (This is a dvmHashTableLookup callback.)
165 * Find an entry that matches the string.
167 static int hashcmpNameStr(const void* ventry, const void* vname)
169 const SharedLib* pLib = (const SharedLib*) ventry;
170 const char* name = (const char*) vname;
172 return strcmp(pLib->pathName, name);
176 * (This is a dvmHashTableLookup callback.)
178 * Find an entry that matches the new entry.
180 * We don't compare the class loader here, because you're not allowed to
181 * have the same shared library associated with more than one CL.
183 static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
185 const SharedLib* pLib = (const SharedLib*) ventry;
186 const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
188 LOGD("--- comparing %p '%s' %p '%s'\n",
189 pLib, pLib->pathName, pNewLib, pNewLib->pathName);
190 return strcmp(pLib->pathName, pNewLib->pathName);
194 * Check to see if an entry with the same pathname already exists.
196 static SharedLib* findSharedLibEntry(const char* pathName)
198 u4 hash = dvmComputeUtf8Hash(pathName);
201 ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
202 hashcmpNameStr, false);
207 * Add the new entry to the table.
209 * Returns the table entry, which will not be the same as "pLib" if the
210 * entry already exists.
212 static SharedLib* addSharedLibEntry(SharedLib* pLib)
214 u4 hash = dvmComputeUtf8Hash(pLib->pathName);
217 * Do the lookup with the "add" flag set. If we add it, we will get
218 * our own pointer back. If somebody beat us to the punch, we'll get
219 * their pointer back instead.
221 return dvmHashTableLookup(gDvm.nativeLibs, hash, pLib, hashcmpSharedLib,
226 * Free up an entry. (This is a dvmHashTableFree callback.)
228 static void freeSharedLibEntry(void* ptr)
230 SharedLib* pLib = (SharedLib*) ptr;
233 * Calling dlclose() here is somewhat dangerous, because it's possible
234 * that a thread outside the VM is still accessing the code we loaded.
237 dlclose(pLib->handle);
238 free(pLib->pathName);
243 * Convert library name to system-dependent form, e.g. "jpeg" becomes
246 * (Should we have this take buffer+len and avoid the alloc? It gets
247 * called very rarely.)
249 char* dvmCreateSystemLibraryName(char* libName)
254 len = snprintf(buf, sizeof(buf), OS_SHARED_LIB_FORMAT_STR, libName);
255 if (len >= (int) sizeof(buf))
262 * Check the result of an earlier call to JNI_OnLoad on this library. If
263 * the call has not yet finished in another thread, wait for it.
265 static bool checkOnLoadResult(SharedLib* pEntry)
267 Thread* self = dvmThreadSelf();
268 if (pEntry->onLoadThreadId == self->threadId) {
270 * Check this so we don't end up waiting for ourselves. We need
271 * to return "true" so the caller can continue.
273 LOGI("threadid=%d: recursive native library load attempt (%s)\n",
274 self->threadId, pEntry->pathName);
278 LOGV("+++ retrieving %s OnLoad status\n", pEntry->pathName);
281 dvmLockMutex(&pEntry->onLoadLock);
282 while (pEntry->onLoadResult == kOnLoadPending) {
283 LOGD("threadid=%d: waiting for %s OnLoad status\n",
284 self->threadId, pEntry->pathName);
285 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
286 pthread_cond_wait(&pEntry->onLoadCond, &pEntry->onLoadLock);
287 dvmChangeStatus(self, oldStatus);
289 if (pEntry->onLoadResult == kOnLoadOkay) {
290 LOGV("+++ earlier OnLoad(%s) okay\n", pEntry->pathName);
293 LOGV("+++ earlier OnLoad(%s) failed\n", pEntry->pathName);
296 dvmUnlockMutex(&pEntry->onLoadLock);
300 typedef int (*OnLoadFunc)(JavaVM*, void*);
303 * Load native code from the specified absolute pathname. Per the spec,
304 * if we've already loaded a library with the specified pathname, we
305 * return without doing anything.
307 * TODO? for better results we should absolutify the pathname. For fully
308 * correct results we should stat to get the inode and compare that. The
309 * existing implementation is fine so long as everybody is using
310 * System.loadLibrary.
312 * The library will be associated with the specified class loader. The JNI
313 * spec says we can't load the same library into more than one class loader.
315 * Returns "true" on success. On failure, sets *detail to a
316 * human-readable description of the error or NULL if no detail is
317 * available; ownership of the string is transferred to the caller.
319 bool dvmLoadNativeCode(const char* pathName, Object* classLoader,
326 /* reduce noise by not chattering about system libraries */
327 verbose = !!strncmp(pathName, "/system", sizeof("/system")-1);
328 verbose = verbose && !!strncmp(pathName, "/vendor", sizeof("/vendor")-1);
331 LOGD("Trying to load lib %s %p\n", pathName, classLoader);
336 * See if we've already loaded it. If we have, and the class loader
337 * matches, return successfully without doing anything.
339 pEntry = findSharedLibEntry(pathName);
340 if (pEntry != NULL) {
341 if (pEntry->classLoader != classLoader) {
342 LOGW("Shared lib '%s' already opened by CL %p; can't open in %p\n",
343 pathName, pEntry->classLoader, classLoader);
347 LOGD("Shared lib '%s' already loaded in same CL %p\n",
348 pathName, classLoader);
350 if (!checkOnLoadResult(pEntry))
356 * Open the shared library. Because we're using a full path, the system
357 * doesn't have to search through LD_LIBRARY_PATH. (It may do so to
358 * resolve this library's dependencies though.)
360 * Failures here are expected when java.library.path has several entries
361 * and we have to hunt for the lib.
363 * The current version of the dynamic linker prints detailed information
364 * about dlopen() failures. Some things to check if the message is
366 * - make sure the library exists on the device
367 * - verify that the right path is being opened (the debug log message
368 * above can help with that)
369 * - check to see if the library is valid (e.g. not zero bytes long)
370 * - check config/prelink-linux-arm.map to ensure that the library
371 * is listed and is not being overrun by the previous entry (if
372 * loading suddenly stops working on a prelinked library, this is
373 * a good one to check)
374 * - write a trivial app that calls sleep() then dlopen(), attach
375 * to it with "strace -p <pid>" while it sleeps, and watch for
376 * attempts to open nonexistent dependent shared libs
378 * This can execute slowly for a large library on a busy system, so we
379 * want to switch from RUNNING to VMWAIT while it executes. This allows
380 * the GC to ignore us.
382 Thread* self = dvmThreadSelf();
383 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
384 handle = dlopen(pathName, RTLD_LAZY);
385 dvmChangeStatus(self, oldStatus);
387 if (handle == NULL) {
388 *detail = strdup(dlerror());
392 /* create a new entry */
393 SharedLib* pNewEntry;
394 pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
395 pNewEntry->pathName = strdup(pathName);
396 pNewEntry->handle = handle;
397 pNewEntry->classLoader = classLoader;
398 dvmInitMutex(&pNewEntry->onLoadLock);
399 pthread_cond_init(&pNewEntry->onLoadCond, NULL);
400 pNewEntry->onLoadThreadId = self->threadId;
402 /* try to add it to the list */
403 SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
405 if (pNewEntry != pActualEntry) {
406 LOGI("WOW: we lost a race to add a shared lib (%s CL=%p)\n",
407 pathName, classLoader);
408 freeSharedLibEntry(pNewEntry);
409 return checkOnLoadResult(pActualEntry);
412 LOGD("Added shared lib %s %p\n", pathName, classLoader);
418 vonLoad = dlsym(handle, "JNI_OnLoad");
419 if (vonLoad == NULL) {
420 LOGD("No JNI_OnLoad found in %s %p, skipping init\n",
421 pathName, classLoader);
424 * Call JNI_OnLoad. We have to override the current class
425 * loader, which will always be "null" since the stuff at the
426 * top of the stack is around Runtime.loadLibrary(). (See
427 * the comments in the JNI FindClass function.)
429 OnLoadFunc func = vonLoad;
430 Object* prevOverride = self->classLoaderOverride;
432 self->classLoaderOverride = classLoader;
433 oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
434 LOGV("+++ calling JNI_OnLoad(%s)\n", pathName);
435 version = (*func)(gDvm.vmList, NULL);
436 dvmChangeStatus(self, oldStatus);
437 self->classLoaderOverride = prevOverride;
439 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
440 version != JNI_VERSION_1_6)
442 LOGW("JNI_OnLoad returned bad version (%d) in %s %p\n",
443 version, pathName, classLoader);
445 * It's unwise to call dlclose() here, but we can mark it
446 * as bad and ensure that future load attempts will fail.
448 * We don't know how far JNI_OnLoad got, so there could
449 * be some partially-initialized stuff accessible through
450 * newly-registered native method calls. We could try to
451 * unregister them, but that doesn't seem worthwhile.
455 LOGV("+++ finished JNI_OnLoad %s\n", pathName);
460 pNewEntry->onLoadResult = kOnLoadOkay;
462 pNewEntry->onLoadResult = kOnLoadFailed;
464 pNewEntry->onLoadThreadId = 0;
467 * Broadcast a wakeup to anybody sleeping on the condition variable.
469 dvmLockMutex(&pNewEntry->onLoadLock);
470 pthread_cond_broadcast(&pNewEntry->onLoadCond);
471 dvmUnlockMutex(&pNewEntry->onLoadLock);
478 * Un-register JNI native methods.
480 * There are two relevant fields in struct Method, "nativeFunc" and
481 * "insns". The former holds a function pointer to a "bridge" function
482 * (or, for internal native, the actual implementation). The latter holds
483 * a pointer to the actual JNI method.
485 * The obvious approach is to reset both fields to their initial state
486 * (nativeFunc points at dvmResolveNativeMethod, insns holds NULL), but
487 * that creates some unpleasant race conditions. In particular, if another
488 * thread is executing inside the call bridge for the method in question,
489 * and we reset insns to NULL, the VM will crash. (See the comments above
490 * dvmSetNativeFunc() for additional commentary.)
492 * We can't rely on being able to update two 32-bit fields in one atomic
493 * operation (e.g. no 64-bit atomic ops on ARMv5TE), so we want to change
494 * only one field. It turns out we can simply reset nativeFunc to its
495 * initial state, leaving insns alone, because dvmResolveNativeMethod
496 * ignores "insns" entirely.
498 * When the method is re-registered, both fields will be updated, but
499 * dvmSetNativeFunc guarantees that "insns" is updated first. This means
500 * we shouldn't be in a situation where we have a "live" call bridge and
501 * a stale implementation pointer.
503 static void unregisterJNINativeMethods(Method* methods, size_t count)
508 Method* meth = &methods[count];
509 if (!dvmIsNativeMethod(meth))
511 if (dvmIsAbstractMethod(meth)) /* avoid abstract method stubs */
515 * Strictly speaking this ought to test the function pointer against
516 * the various JNI bridge functions to ensure that we only undo
517 * methods that were registered through JNI. In practice, any
518 * native method with a non-NULL "insns" is a registered JNI method.
520 * If we inadvertently unregister an internal-native, it'll get
521 * re-resolved on the next call; unregistering an unregistered
522 * JNI method is a no-op. So we don't really need to test for
526 LOGD("Unregistering JNI method %s.%s:%s\n",
527 meth->clazz->descriptor, meth->name, meth->shorty);
528 dvmSetNativeFunc(meth, dvmResolveNativeMethod, NULL);
533 * Un-register all JNI native methods from a class.
535 void dvmUnregisterJNINativeMethods(ClassObject* clazz)
537 unregisterJNINativeMethods(clazz->directMethods, clazz->directMethodCount);
538 unregisterJNINativeMethods(clazz->virtualMethods, clazz->virtualMethodCount);
543 * ===========================================================================
544 * Signature-based method lookup
545 * ===========================================================================
549 * Create the pre-mangled form of the class+method string.
551 * Returns a newly-allocated string, and sets "*pLen" to the length.
553 static char* createJniNameString(const char* classDescriptor,
554 const char* methodName, int* pLen)
557 size_t descriptorLength = strlen(classDescriptor);
559 *pLen = 4 + descriptorLength + strlen(methodName);
561 result = malloc(*pLen +1);
566 * Add one to classDescriptor to skip the "L", and then replace
567 * the final ";" with a "/" after the sprintf() call.
569 sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
570 result[5 + (descriptorLength - 2)] = '/';
576 * Returns a newly-allocated, mangled copy of "str".
578 * "str" is a "modified UTF-8" string. We convert it to UTF-16 first to
581 static char* mangleString(const char* str, int len)
587 //LOGI("mangling '%s' %d\n", str, len);
589 assert(str[len] == '\0');
591 charLen = dvmUtf8Len(str);
592 utf16 = (u2*) malloc(sizeof(u2) * charLen);
596 dvmConvertUtf8ToUtf16(utf16, str);
599 * Compute the length of the mangled string.
601 int i, mangleLen = 0;
603 for (i = 0; i < charLen; i++) {
606 if (ch == '$' || ch > 127) {
624 mangle = (char*) malloc(mangleLen +1);
628 for (i = 0, cp = mangle; i < charLen; i++) {
631 if (ch == '$' || ch > 127) {
632 sprintf(cp, "_0%04x", ch);
666 * Create the mangled form of the parameter types.
668 static char* createMangledSignature(const DexProto* proto)
670 DexStringCache sigCache;
674 dexStringCacheInit(&sigCache);
675 interim = dexProtoGetParameterDescriptors(proto, &sigCache);
676 result = mangleString(interim, strlen(interim));
677 dexStringCacheRelease(&sigCache);
683 * (This is a dvmHashForeach callback.)
685 * Search for a matching method in this shared library.
687 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
689 static int findMethodInLib(void* vlib, void* vmethod)
691 const SharedLib* pLib = (const SharedLib*) vlib;
692 const Method* meth = (const Method*) vmethod;
693 char* preMangleCM = NULL;
694 char* mangleCM = NULL;
695 char* mangleSig = NULL;
696 char* mangleCMSig = NULL;
700 if (meth->clazz->classLoader != pLib->classLoader) {
701 LOGV("+++ not scanning '%s' for '%s' (wrong CL)\n",
702 pLib->pathName, meth->name);
705 LOGV("+++ scanning '%s' for '%s'\n", pLib->pathName, meth->name);
708 * First, we try it without the signature.
711 createJniNameString(meth->clazz->descriptor, meth->name, &len);
712 if (preMangleCM == NULL)
715 mangleCM = mangleString(preMangleCM, len);
716 if (mangleCM == NULL)
719 LOGV("+++ calling dlsym(%s)\n", mangleCM);
720 func = dlsym(pLib->handle, mangleCM);
723 createMangledSignature(&meth->prototype);
724 if (mangleSig == NULL)
727 mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
728 if (mangleCMSig == NULL)
731 sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
733 LOGV("+++ calling dlsym(%s)\n", mangleCMSig);
734 func = dlsym(pLib->handle, mangleCMSig);
736 LOGV("Found '%s' with dlsym\n", mangleCMSig);
739 LOGV("Found '%s' with dlsym\n", mangleCM);
751 * See if the requested method lives in any of the currently-loaded
752 * shared libraries. We do this by checking each of them for the expected
755 static void* lookupSharedLibMethod(const Method* method)
757 if (gDvm.nativeLibs == NULL) {
758 LOGE("Unexpected init state: nativeLibs not ready\n");
761 return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,
766 static void appendValue(char type, const JValue value, char* buf, size_t n,
769 size_t len = strlen(buf);
770 if (len >= n - 32) { // 32 should be longer than anything we could append.
779 if (value.b >= 0 && value.b < 10) {
780 sprintf(p, "%d", value.b);
782 sprintf(p, "0x%x (%d)", value.b, value.b);
786 if (value.c < 0x7f && value.c >= ' ') {
787 sprintf(p, "U+%x ('%c')", value.c, value.c);
789 sprintf(p, "U+%x", value.c);
793 sprintf(p, "%g", value.d);
796 sprintf(p, "%g", value.f);
799 sprintf(p, "%d", value.i);
802 sprintf(p, "0x%x", value.i);
805 sprintf(p, "%lld", value.j);
808 sprintf(p, "%d", value.s);
814 strcpy(p, value.z ? "true" : "false");
817 sprintf(p, "unknown type '%c'", type);
826 #define LOGI_NATIVE(...) LOG(LOG_INFO, LOG_TAG "-native", __VA_ARGS__)
828 void dvmLogNativeMethodEntry(const Method* method, const u4* args)
830 char thisString[32] = { 0 };
831 const u4* sp = args; // &args[method->registersSize - method->insSize];
832 if (!dvmIsStaticMethod(method)) {
833 sprintf(thisString, "this=0x%08x ", *sp++);
836 char argsString[128]= { 0 };
837 const char* desc = &method->shorty[1];
838 while (*desc != '\0') {
839 char argType = *desc++;
841 if (argType == 'D' || argType == 'J') {
842 value.j = dvmGetArgLong(sp, 0);
847 appendValue(argType, value, argsString, sizeof(argsString),
851 char* className = dvmHumanReadableDescriptor(method->clazz->descriptor);
852 char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
853 LOGI_NATIVE("-> %s %s%s %s(%s)", className, method->name, signature,
854 thisString, argsString);
859 void dvmLogNativeMethodExit(const Method* method, Thread* self,
860 const JValue returnValue)
862 char* className = dvmHumanReadableDescriptor(method->clazz->descriptor);
863 char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
864 if (dvmCheckException(self)) {
865 Object* exception = dvmGetException(self);
866 char* exceptionClassName =
867 dvmHumanReadableDescriptor(exception->clazz->descriptor);
868 LOGI_NATIVE("<- %s %s%s threw %s", className,
869 method->name, signature, exceptionClassName);
870 free(exceptionClassName);
872 char returnValueString[128] = { 0 };
873 char returnType = method->shorty[0];
874 appendValue(returnType, returnValue,
875 returnValueString, sizeof(returnValueString), false);
876 LOGI_NATIVE("<- %s %s%s returned %s", className,
877 method->name, signature, returnValueString);