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.
17 * Native method resolution.
19 * Currently the "Dalvik native" methods are only used for internal methods.
20 * Someday we may want to export the interface as a faster but riskier
28 static void freeSharedLibEntry(void* ptr);
29 static void* lookupSharedLibMethod(const Method* method);
33 * Initialize the native code loader.
35 bool dvmNativeStartup(void)
37 gDvm.nativeLibs = dvmHashTableCreate(4, freeSharedLibEntry);
38 if (gDvm.nativeLibs == NULL)
47 void dvmNativeShutdown(void)
49 dvmHashTableFree(gDvm.nativeLibs);
50 gDvm.nativeLibs = NULL;
55 * Resolve a native method and invoke it.
57 * This is executed as if it were a native bridge or function. If the
58 * resolution succeeds, method->insns is replaced, and we don't go through
61 * Initializes method's class if necessary.
63 * An exception is thrown on resolution failure.
65 void dvmResolveNativeMethod(const u4* args, JValue* pResult,
66 const Method* method, Thread* self)
68 ClassObject* clazz = method->clazz;
72 * If this is a static method, it could be called before the class
73 * has been initialized.
75 if (dvmIsStaticMethod(method)) {
76 if (!dvmIsClassInitialized(clazz) && !dvmInitClass(clazz)) {
77 assert(dvmCheckException(dvmThreadSelf()));
81 assert(dvmIsClassInitialized(clazz) ||
82 dvmIsClassInitializing(clazz));
85 /* start with our internal-native methods */
86 func = dvmLookupInternalNativeMethod(method);
88 /* resolution always gets the same answer, so no race here */
90 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
91 LOGVV("+++ resolved native %s.%s %s, invoking\n",
92 clazz->descriptor, method->name, desc);
95 if (dvmIsSynchronizedMethod(method)) {
96 LOGE("ERROR: internal-native can't be declared 'synchronized'\n");
97 LOGE("Failing on %s.%s\n", method->clazz->descriptor, method->name);
98 dvmAbort(); // harsh, but this is VM-internal problem
100 DalvikBridgeFunc dfunc = (DalvikBridgeFunc) func;
101 dvmSetNativeFunc(method, dfunc, NULL);
102 assert(method->insns == NULL);
103 dfunc(args, pResult, method, self);
107 /* now scan any DLLs we have loaded for JNI signatures */
108 func = lookupSharedLibMethod(method);
110 if (dvmIsSynchronizedMethod(method))
111 dvmSetNativeFunc(method, dvmCallSynchronizedJNIMethod, func);
113 dvmSetNativeFunc(method, dvmCallJNIMethod, func);
114 dvmCallJNIMethod(args, pResult, method, self);
119 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
120 LOGW("No implementation found for native %s.%s %s\n",
121 clazz->descriptor, method->name, desc);
125 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", method->name);
130 * ===========================================================================
131 * Native shared library support
132 * ===========================================================================
135 // TODO? if a ClassLoader is unloaded, we need to unload all DLLs that
136 // are associated with it. (Or not -- can't determine if native code
137 // is still using parts of it.)
139 typedef enum OnLoadState {
140 kOnLoadPending = 0, /* initial state, must be zero */
146 * We add one of these to the hash table for every library we load. The
147 * hash is on the "pathName" field.
149 typedef struct SharedLib {
150 char* pathName; /* absolute path to library */
151 void* handle; /* from dlopen */
152 Object* classLoader; /* ClassLoader we are associated with */
154 pthread_mutex_t onLoadLock; /* guards remaining items */
155 pthread_cond_t onLoadCond; /* wait for JNI_OnLoad in other thread */
156 u4 onLoadThreadId; /* recursive invocation guard */
157 OnLoadState onLoadResult; /* result of earlier JNI_OnLoad */
161 * (This is a dvmHashTableLookup callback.)
163 * Find an entry that matches the string.
165 static int hashcmpNameStr(const void* ventry, const void* vname)
167 const SharedLib* pLib = (const SharedLib*) ventry;
168 const char* name = (const char*) vname;
170 return strcmp(pLib->pathName, name);
174 * (This is a dvmHashTableLookup callback.)
176 * Find an entry that matches the new entry.
178 * We don't compare the class loader here, because you're not allowed to
179 * have the same shared library associated with more than one CL.
181 static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
183 const SharedLib* pLib = (const SharedLib*) ventry;
184 const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
186 LOGD("--- comparing %p '%s' %p '%s'\n",
187 pLib, pLib->pathName, pNewLib, pNewLib->pathName);
188 return strcmp(pLib->pathName, pNewLib->pathName);
192 * Check to see if an entry with the same pathname already exists.
194 static SharedLib* findSharedLibEntry(const char* pathName)
196 u4 hash = dvmComputeUtf8Hash(pathName);
199 ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
200 hashcmpNameStr, false);
205 * Add the new entry to the table.
207 * Returns the table entry, which will not be the same as "pLib" if the
208 * entry already exists.
210 static SharedLib* addSharedLibEntry(SharedLib* pLib)
212 u4 hash = dvmComputeUtf8Hash(pLib->pathName);
216 * Do the lookup with the "add" flag set. If we add it, we will get
217 * our own pointer back. If somebody beat us to the punch, we'll get
218 * their pointer back instead.
220 return dvmHashTableLookup(gDvm.nativeLibs, hash, pLib, hashcmpSharedLib,
225 * Free up an entry. (This is a dvmHashTableFree callback.)
227 static void freeSharedLibEntry(void* ptr)
229 SharedLib* pLib = (SharedLib*) ptr;
232 * Calling dlclose() here is somewhat dangerous, because it's possible
233 * that a thread outside the VM is still accessing the code we loaded.
236 dlclose(pLib->handle);
237 free(pLib->pathName);
242 * Convert library name to system-dependent form, e.g. "jpeg" becomes
245 * (Should we have this take buffer+len and avoid the alloc? It gets
246 * called very rarely.)
248 char* dvmCreateSystemLibraryName(char* libName)
253 len = snprintf(buf, sizeof(buf), OS_SHARED_LIB_FORMAT_STR, libName);
254 if (len >= (int) sizeof(buf))
263 * Find a library, given the lib's system-dependent name (e.g. "libjpeg.so").
265 * We need to search through the path defined by the java.library.path
268 * Returns NULL if the library was not found.
270 static char* findLibrary(const char* libSysName)
272 char* javaLibraryPath = NULL;
273 char* testName = NULL;
278 javaLibraryPath = dvmGetProperty("java.library.path");
279 if (javaLibraryPath == NULL)
282 LOGVV("+++ path is '%s'\n", javaLibraryPath);
284 start = cp = javaLibraryPath;
289 cp = strchr(start, ':');
293 len = snprintf(pathBuf, sizeof(pathBuf), "%s/%s", start, libSysName);
294 if (len >= (int) sizeof(pathBuf)) {
295 LOGW("Path overflowed %d bytes: '%s' / '%s'\n",
296 len, start, libSysName);
297 /* keep going, next one might fit */
299 LOGVV("+++ trying '%s'\n", pathBuf);
300 if (access(pathBuf, R_OK) == 0) {
301 testName = strdup(pathBuf);
310 free(javaLibraryPath);
315 * Load a native shared library, given the system-independent piece of
318 * Throws an exception on failure.
320 void dvmLoadNativeLibrary(StringObject* libNameObj, Object* classLoader)
322 char* libName = NULL;
323 char* libSysName = NULL;
324 char* libPath = NULL;
327 * If "classLoader" isn't NULL, call the class loader's "findLibrary"
328 * method with the lib name. If it returns a non-NULL result, we use
329 * that as the pathname.
331 if (classLoader != NULL) {
333 Object* findLibResult;
335 findLibrary = dvmFindVirtualMethodByDescriptor(classLoader->clazz,
336 "findLibrary", "(Ljava/lang/String;)Ljava/lang/String;");
337 if (findLibrary == NULL) {
338 LOGW("Could not find findLibrary() in %s\n",
339 classLoader->clazz->name);
340 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;",
345 findLibResult = (Object*)(u4) dvmCallMethod(findLibrary, classLoader,
347 if (dvmCheckException()) {
348 LOGV("returning early on exception\n");
351 if (findLibResult != NULL) {
353 libPath = dvmCreateCstrFromString(libNameObj);
354 LOGI("Found library through CL: '%s'\n", libPath);
355 dvmLoadNativeCode(libPath, classLoader);
360 libName = dvmCreateCstrFromString(libNameObj);
363 libSysName = dvmCreateSystemLibraryName(libName);
364 if (libSysName == NULL)
367 libPath = findLibrary(libSysName);
368 if (libPath != NULL) {
369 LOGD("Found library through path: '%s'\n", libPath);
370 dvmLoadNativeCode(libPath, classLoader);
372 LOGW("Unable to locate shared lib matching '%s'\n", libSysName);
373 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", libName);
385 * Check the result of an earlier call to JNI_OnLoad on this library. If
386 * the call has not yet finished in another thread, wait for it.
388 static bool checkOnLoadResult(SharedLib* pEntry)
390 Thread* self = dvmThreadSelf();
391 if (pEntry->onLoadThreadId == self->threadId) {
393 * Check this so we don't end up waiting for ourselves. We need
394 * to return "true" so the caller can continue.
396 LOGI("threadid=%d: recursive native library load attempt (%s)\n",
397 self->threadId, pEntry->pathName);
401 LOGV("+++ retrieving %s OnLoad status\n", pEntry->pathName);
404 dvmLockMutex(&pEntry->onLoadLock);
405 while (pEntry->onLoadResult == kOnLoadPending) {
406 LOGD("threadid=%d: waiting for %s OnLoad status\n",
407 self->threadId, pEntry->pathName);
408 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
409 pthread_cond_wait(&pEntry->onLoadCond, &pEntry->onLoadLock);
410 dvmChangeStatus(self, oldStatus);
412 if (pEntry->onLoadResult == kOnLoadOkay) {
413 LOGV("+++ earlier OnLoad(%s) okay\n", pEntry->pathName);
416 LOGV("+++ earlier OnLoad(%s) failed\n", pEntry->pathName);
419 dvmUnlockMutex(&pEntry->onLoadLock);
423 typedef int (*OnLoadFunc)(JavaVM*, void*);
426 * Load native code from the specified absolute pathname. Per the spec,
427 * if we've already loaded a library with the specified pathname, we
428 * return without doing anything.
430 * TODO? for better results we should absolutify the pathname. For fully
431 * correct results we should stat to get the inode and compare that. The
432 * existing implementation is fine so long as everybody is using
433 * System.loadLibrary.
435 * The library will be associated with the specified class loader. The JNI
436 * spec says we can't load the same library into more than one class loader.
438 * Returns "true" on success.
440 bool dvmLoadNativeCode(const char* pathName, Object* classLoader)
445 LOGD("Trying to load lib %s %p\n", pathName, classLoader);
448 * See if we've already loaded it. If we have, and the class loader
449 * matches, return successfully without doing anything.
451 pEntry = findSharedLibEntry(pathName);
452 if (pEntry != NULL) {
453 if (pEntry->classLoader != classLoader) {
454 LOGW("Shared lib '%s' already opened by CL %p; can't open in %p\n",
455 pathName, pEntry->classLoader, classLoader);
458 LOGD("Shared lib '%s' already loaded in same CL %p\n",
459 pathName, classLoader);
460 if (!checkOnLoadResult(pEntry))
466 * Open the shared library. Because we're using a full path, the system
467 * doesn't have to search through LD_LIBRARY_PATH. (It may do so to
468 * resolve this library's dependencies though.)
470 * Failures here are expected when java.library.path has several entries.
472 * The current android-arm dynamic linker implementation tends to
473 * return "Cannot find library" from dlerror() regardless of the actual
474 * problem. A more useful diagnostic may be sent to stdout/stderr,
475 * but often that's not visible. Some things to try:
476 * - make sure the library exists on the device
477 * - verify that the right path is being opened (the debug log message
478 * above can help with that)
479 * - check to see if the library is valid
480 * - check config/prelink-linux-arm.map to ensure that the library
481 * is listed and is not being overrun by the previous entry (if
482 * loading suddenly stops working on a prelinked library, this is
483 * a good one to check)
484 * - write a trivial app that calls sleep() then dlopen(), attach
485 * to it with "strace -p <pid>" while it sleeps, and watch for
486 * attempts to open nonexistent dependent shared libs
488 * This can execute slowly for a large library on a busy system, so we
489 * want to switch from RUNNING to VMWAIT while it executes. This allows
490 * the GC to ignore us.
492 Thread* self = dvmThreadSelf();
493 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
494 handle = dlopen(pathName, RTLD_LAZY);
495 dvmChangeStatus(self, oldStatus);
497 if (handle == NULL) {
498 LOGI("Unable to dlopen(%s): %s\n", pathName, dlerror());
502 /* create a new entry */
503 SharedLib* pNewEntry;
504 pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
505 pNewEntry->pathName = strdup(pathName);
506 pNewEntry->handle = handle;
507 pNewEntry->classLoader = classLoader;
508 dvmInitMutex(&pNewEntry->onLoadLock);
509 pthread_cond_init(&pNewEntry->onLoadCond, NULL);
510 pNewEntry->onLoadThreadId = self->threadId;
512 /* try to add it to the list */
513 SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
515 if (pNewEntry != pActualEntry) {
516 LOGI("WOW: we lost a race to add a shared lib (%s CL=%p)\n",
517 pathName, classLoader);
518 freeSharedLibEntry(pNewEntry);
519 return checkOnLoadResult(pActualEntry);
521 LOGD("Added shared lib %s %p\n", pathName, classLoader);
527 vonLoad = dlsym(handle, "JNI_OnLoad");
528 if (vonLoad == NULL) {
529 LOGD("No JNI_OnLoad found in %s %p\n", pathName, classLoader);
532 * Call JNI_OnLoad. We have to override the current class
533 * loader, which will always be "null" since the stuff at the
534 * top of the stack is around Runtime.loadLibrary(). (See
535 * the comments in the JNI FindClass function.)
537 OnLoadFunc func = vonLoad;
538 Object* prevOverride = self->classLoaderOverride;
540 self->classLoaderOverride = classLoader;
541 oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
542 LOGV("+++ calling JNI_OnLoad(%s)\n", pathName);
543 version = (*func)(gDvm.vmList, NULL);
544 dvmChangeStatus(self, oldStatus);
545 self->classLoaderOverride = prevOverride;
547 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
548 version != JNI_VERSION_1_6)
550 LOGW("JNI_OnLoad returned bad version (%d) in %s %p\n",
551 version, pathName, classLoader);
553 * It's unwise to call dlclose() here, but we can mark it
554 * as bad and ensure that future load attempts will fail.
556 * We don't know how far JNI_OnLoad got, so there could
557 * be some partially-initialized stuff accessible through
558 * newly-registered native method calls. We could try to
559 * unregister them, but that doesn't seem worthwhile.
563 LOGV("+++ finished JNI_OnLoad %s\n", pathName);
568 pNewEntry->onLoadResult = kOnLoadOkay;
570 pNewEntry->onLoadResult = kOnLoadFailed;
572 pNewEntry->onLoadThreadId = 0;
575 * Broadcast a wakeup to anybody sleeping on the condition variable.
577 dvmLockMutex(&pNewEntry->onLoadLock);
578 pthread_cond_broadcast(&pNewEntry->onLoadCond);
579 dvmUnlockMutex(&pNewEntry->onLoadLock);
586 * ===========================================================================
587 * Signature-based method lookup
588 * ===========================================================================
592 * Create the pre-mangled form of the class+method string.
594 * Returns a newly-allocated string, and sets "*pLen" to the length.
596 static char* createJniNameString(const char* classDescriptor,
597 const char* methodName, int* pLen)
600 size_t descriptorLength = strlen(classDescriptor);
602 *pLen = 4 + descriptorLength + strlen(methodName);
604 result = malloc(*pLen +1);
609 * Add one to classDescriptor to skip the "L", and then replace
610 * the final ";" with a "/" after the sprintf() call.
612 sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
613 result[5 + (descriptorLength - 2)] = '/';
619 * Returns a newly-allocated, mangled copy of "str".
621 * "str" is a "modified UTF-8" string. We convert it to UTF-16 first to
624 static char* mangleString(const char* str, int len)
630 //LOGI("mangling '%s' %d\n", str, len);
632 assert(str[len] == '\0');
634 charLen = dvmUtf8Len(str);
635 utf16 = (u2*) malloc(sizeof(u2) * charLen);
639 dvmConvertUtf8ToUtf16(utf16, str);
642 * Compute the length of the mangled string.
644 int i, mangleLen = 0;
646 for (i = 0; i < charLen; i++) {
667 mangle = (char*) malloc(mangleLen +1);
671 for (i = 0, cp = mangle; i < charLen; i++) {
675 sprintf(cp, "_0%04x", ch);
709 * Create the mangled form of the parameter types.
711 static char* createMangledSignature(const DexProto* proto)
713 DexStringCache sigCache;
717 dexStringCacheInit(&sigCache);
718 interim = dexProtoGetParameterDescriptors(proto, &sigCache);
719 result = mangleString(interim, strlen(interim));
720 dexStringCacheRelease(&sigCache);
726 * (This is a dvmHashForeach callback.)
728 * Search for a matching method in this shared library.
730 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
732 static int findMethodInLib(void* vlib, void* vmethod)
734 const SharedLib* pLib = (const SharedLib*) vlib;
735 const Method* meth = (const Method*) vmethod;
736 char* preMangleCM = NULL;
737 char* mangleCM = NULL;
738 char* mangleSig = NULL;
739 char* mangleCMSig = NULL;
743 if (meth->clazz->classLoader != pLib->classLoader) {
744 LOGD("+++ not scanning '%s' for '%s' (wrong CL)\n",
745 pLib->pathName, meth->name);
748 LOGV("+++ scanning '%s' for '%s'\n", pLib->pathName, meth->name);
751 * First, we try it without the signature.
754 createJniNameString(meth->clazz->descriptor, meth->name, &len);
755 if (preMangleCM == NULL)
758 mangleCM = mangleString(preMangleCM, len);
759 if (mangleCM == NULL)
762 LOGV("+++ calling dlsym(%s)\n", mangleCM);
763 func = dlsym(pLib->handle, mangleCM);
766 createMangledSignature(&meth->prototype);
767 if (mangleSig == NULL)
770 mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
771 if (mangleCMSig == NULL)
774 sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
776 LOGV("+++ calling dlsym(%s)\n", mangleCMSig);
777 func = dlsym(pLib->handle, mangleCMSig);
779 LOGV("Found '%s' with dlsym\n", mangleCMSig);
782 LOGV("Found '%s' with dlsym\n", mangleCM);
794 * See if the requested method lives in any of the currently-loaded
795 * shared libraries. We do this by checking each of them for the expected
798 static void* lookupSharedLibMethod(const Method* method)
800 if (gDvm.nativeLibs == NULL) {
801 LOGE("Unexpected init state: nativeLibs not ready\n");
804 return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,