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
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, dfunc, NULL);
107 assert(method->insns == NULL);
108 dfunc(args, pResult, method, self);
112 /* now scan any DLLs we have loaded for JNI signatures */
113 func = lookupSharedLibMethod(method);
115 /* found it, point it at the JNI bridge and then call it */
116 dvmUseJNIBridge((Method*) method, func);
117 dvmCallJNIMethod(args, pResult, method, self);
122 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
123 LOGW("No implementation found for native %s.%s %s\n",
124 clazz->descriptor, method->name, desc);
128 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", method->name);
133 * ===========================================================================
134 * Native shared library support
135 * ===========================================================================
138 // TODO? if a ClassLoader is unloaded, we need to unload all DLLs that
139 // are associated with it. (Or not -- can't determine if native code
140 // is still using parts of it.)
142 typedef enum OnLoadState {
143 kOnLoadPending = 0, /* initial state, must be zero */
149 * We add one of these to the hash table for every library we load. The
150 * hash is on the "pathName" field.
152 typedef struct SharedLib {
153 char* pathName; /* absolute path to library */
154 void* handle; /* from dlopen */
155 Object* classLoader; /* ClassLoader we are associated with */
157 pthread_mutex_t onLoadLock; /* guards remaining items */
158 pthread_cond_t onLoadCond; /* wait for JNI_OnLoad in other thread */
159 u4 onLoadThreadId; /* recursive invocation guard */
160 OnLoadState onLoadResult; /* result of earlier JNI_OnLoad */
164 * (This is a dvmHashTableLookup callback.)
166 * Find an entry that matches the string.
168 static int hashcmpNameStr(const void* ventry, const void* vname)
170 const SharedLib* pLib = (const SharedLib*) ventry;
171 const char* name = (const char*) vname;
173 return strcmp(pLib->pathName, name);
177 * (This is a dvmHashTableLookup callback.)
179 * Find an entry that matches the new entry.
181 * We don't compare the class loader here, because you're not allowed to
182 * have the same shared library associated with more than one CL.
184 static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
186 const SharedLib* pLib = (const SharedLib*) ventry;
187 const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
189 LOGD("--- comparing %p '%s' %p '%s'\n",
190 pLib, pLib->pathName, pNewLib, pNewLib->pathName);
191 return strcmp(pLib->pathName, pNewLib->pathName);
195 * Check to see if an entry with the same pathname already exists.
197 static SharedLib* findSharedLibEntry(const char* pathName)
199 u4 hash = dvmComputeUtf8Hash(pathName);
202 ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
203 hashcmpNameStr, false);
208 * Add the new entry to the table.
210 * Returns the table entry, which will not be the same as "pLib" if the
211 * entry already exists.
213 static SharedLib* addSharedLibEntry(SharedLib* pLib)
215 u4 hash = dvmComputeUtf8Hash(pLib->pathName);
219 * Do the lookup with the "add" flag set. If we add it, we will get
220 * our own pointer back. If somebody beat us to the punch, we'll get
221 * their pointer back instead.
223 return dvmHashTableLookup(gDvm.nativeLibs, hash, pLib, hashcmpSharedLib,
228 * Free up an entry. (This is a dvmHashTableFree callback.)
230 static void freeSharedLibEntry(void* ptr)
232 SharedLib* pLib = (SharedLib*) ptr;
235 * Calling dlclose() here is somewhat dangerous, because it's possible
236 * that a thread outside the VM is still accessing the code we loaded.
239 dlclose(pLib->handle);
240 free(pLib->pathName);
245 * Convert library name to system-dependent form, e.g. "jpeg" becomes
248 * (Should we have this take buffer+len and avoid the alloc? It gets
249 * called very rarely.)
251 char* dvmCreateSystemLibraryName(char* libName)
256 len = snprintf(buf, sizeof(buf), OS_SHARED_LIB_FORMAT_STR, libName);
257 if (len >= (int) sizeof(buf))
266 * Find a library, given the lib's system-dependent name (e.g. "libjpeg.so").
268 * We need to search through the path defined by the java.library.path
271 * Returns NULL if the library was not found.
273 static char* findLibrary(const char* libSysName)
275 char* javaLibraryPath = NULL;
276 char* testName = NULL;
281 javaLibraryPath = dvmGetProperty("java.library.path");
282 if (javaLibraryPath == NULL)
285 LOGVV("+++ path is '%s'\n", javaLibraryPath);
287 start = cp = javaLibraryPath;
292 cp = strchr(start, ':');
296 len = snprintf(pathBuf, sizeof(pathBuf), "%s/%s", start, libSysName);
297 if (len >= (int) sizeof(pathBuf)) {
298 LOGW("Path overflowed %d bytes: '%s' / '%s'\n",
299 len, start, libSysName);
300 /* keep going, next one might fit */
302 LOGVV("+++ trying '%s'\n", pathBuf);
303 if (access(pathBuf, R_OK) == 0) {
304 testName = strdup(pathBuf);
313 free(javaLibraryPath);
318 * Load a native shared library, given the system-independent piece of
321 * Throws an exception on failure.
323 void dvmLoadNativeLibrary(StringObject* libNameObj, Object* classLoader)
325 char* libName = NULL;
326 char* libSysName = NULL;
327 char* libPath = NULL;
330 * If "classLoader" isn't NULL, call the class loader's "findLibrary"
331 * method with the lib name. If it returns a non-NULL result, we use
332 * that as the pathname.
334 if (classLoader != NULL) {
336 Object* findLibResult;
338 findLibrary = dvmFindVirtualMethodByDescriptor(classLoader->clazz,
339 "findLibrary", "(Ljava/lang/String;)Ljava/lang/String;");
340 if (findLibrary == NULL) {
341 LOGW("Could not find findLibrary() in %s\n",
342 classLoader->clazz->name);
343 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;",
348 findLibResult = (Object*)(u4) dvmCallMethod(findLibrary, classLoader,
350 if (dvmCheckException()) {
351 LOGV("returning early on exception\n");
354 if (findLibResult != NULL) {
356 libPath = dvmCreateCstrFromString(libNameObj);
357 LOGI("Found library through CL: '%s'\n", libPath);
358 dvmLoadNativeCode(libPath, classLoader);
363 libName = dvmCreateCstrFromString(libNameObj);
366 libSysName = dvmCreateSystemLibraryName(libName);
367 if (libSysName == NULL)
370 libPath = findLibrary(libSysName);
371 if (libPath != NULL) {
372 LOGD("Found library through path: '%s'\n", libPath);
373 dvmLoadNativeCode(libPath, classLoader);
375 LOGW("Unable to locate shared lib matching '%s'\n", libSysName);
376 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", libName);
388 * Check the result of an earlier call to JNI_OnLoad on this library. If
389 * the call has not yet finished in another thread, wait for it.
391 static bool checkOnLoadResult(SharedLib* pEntry)
393 Thread* self = dvmThreadSelf();
394 if (pEntry->onLoadThreadId == self->threadId) {
396 * Check this so we don't end up waiting for ourselves. We need
397 * to return "true" so the caller can continue.
399 LOGI("threadid=%d: recursive native library load attempt (%s)\n",
400 self->threadId, pEntry->pathName);
404 LOGV("+++ retrieving %s OnLoad status\n", pEntry->pathName);
407 dvmLockMutex(&pEntry->onLoadLock);
408 while (pEntry->onLoadResult == kOnLoadPending) {
409 LOGD("threadid=%d: waiting for %s OnLoad status\n",
410 self->threadId, pEntry->pathName);
411 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
412 pthread_cond_wait(&pEntry->onLoadCond, &pEntry->onLoadLock);
413 dvmChangeStatus(self, oldStatus);
415 if (pEntry->onLoadResult == kOnLoadOkay) {
416 LOGV("+++ earlier OnLoad(%s) okay\n", pEntry->pathName);
419 LOGV("+++ earlier OnLoad(%s) failed\n", pEntry->pathName);
422 dvmUnlockMutex(&pEntry->onLoadLock);
426 typedef int (*OnLoadFunc)(JavaVM*, void*);
429 * Load native code from the specified absolute pathname. Per the spec,
430 * if we've already loaded a library with the specified pathname, we
431 * return without doing anything.
433 * TODO? for better results we should absolutify the pathname. For fully
434 * correct results we should stat to get the inode and compare that. The
435 * existing implementation is fine so long as everybody is using
436 * System.loadLibrary.
438 * The library will be associated with the specified class loader. The JNI
439 * spec says we can't load the same library into more than one class loader.
441 * Returns "true" on success.
443 bool dvmLoadNativeCode(const char* pathName, Object* classLoader)
448 LOGD("Trying to load lib %s %p\n", pathName, classLoader);
451 * See if we've already loaded it. If we have, and the class loader
452 * matches, return successfully without doing anything.
454 pEntry = findSharedLibEntry(pathName);
455 if (pEntry != NULL) {
456 if (pEntry->classLoader != classLoader) {
457 LOGW("Shared lib '%s' already opened by CL %p; can't open in %p\n",
458 pathName, pEntry->classLoader, classLoader);
461 LOGD("Shared lib '%s' already loaded in same CL %p\n",
462 pathName, classLoader);
463 if (!checkOnLoadResult(pEntry))
469 * Open the shared library. Because we're using a full path, the system
470 * doesn't have to search through LD_LIBRARY_PATH. (It may do so to
471 * resolve this library's dependencies though.)
473 * Failures here are expected when java.library.path has several entries
474 * and we have to hunt for the lib.
476 * The current android-arm dynamic linker implementation tends to
477 * return "Cannot find library" from dlerror() regardless of the actual
478 * problem. A more useful diagnostic may be sent to stdout/stderr if
479 * linker diagnostics are enabled, but that's not usually visible in
480 * Android apps. Some things to try:
481 * - make sure the library exists on the device
482 * - verify that the right path is being opened (the debug log message
483 * above can help with that)
484 * - check to see if the library is valid (e.g. not zero bytes long)
485 * - check config/prelink-linux-arm.map to ensure that the library
486 * is listed and is not being overrun by the previous entry (if
487 * loading suddenly stops working on a prelinked library, this is
488 * a good one to check)
489 * - write a trivial app that calls sleep() then dlopen(), attach
490 * to it with "strace -p <pid>" while it sleeps, and watch for
491 * attempts to open nonexistent dependent shared libs
493 * This can execute slowly for a large library on a busy system, so we
494 * want to switch from RUNNING to VMWAIT while it executes. This allows
495 * the GC to ignore us.
497 Thread* self = dvmThreadSelf();
498 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
499 handle = dlopen(pathName, RTLD_LAZY);
500 dvmChangeStatus(self, oldStatus);
502 if (handle == NULL) {
503 LOGI("Unable to dlopen(%s): %s\n", pathName, dlerror());
507 /* create a new entry */
508 SharedLib* pNewEntry;
509 pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
510 pNewEntry->pathName = strdup(pathName);
511 pNewEntry->handle = handle;
512 pNewEntry->classLoader = classLoader;
513 dvmInitMutex(&pNewEntry->onLoadLock);
514 pthread_cond_init(&pNewEntry->onLoadCond, NULL);
515 pNewEntry->onLoadThreadId = self->threadId;
517 /* try to add it to the list */
518 SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
520 if (pNewEntry != pActualEntry) {
521 LOGI("WOW: we lost a race to add a shared lib (%s CL=%p)\n",
522 pathName, classLoader);
523 freeSharedLibEntry(pNewEntry);
524 return checkOnLoadResult(pActualEntry);
526 LOGD("Added shared lib %s %p\n", pathName, classLoader);
532 vonLoad = dlsym(handle, "JNI_OnLoad");
533 if (vonLoad == NULL) {
534 LOGD("No JNI_OnLoad found in %s %p\n", pathName, classLoader);
537 * Call JNI_OnLoad. We have to override the current class
538 * loader, which will always be "null" since the stuff at the
539 * top of the stack is around Runtime.loadLibrary(). (See
540 * the comments in the JNI FindClass function.)
542 OnLoadFunc func = vonLoad;
543 Object* prevOverride = self->classLoaderOverride;
545 self->classLoaderOverride = classLoader;
546 oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
547 LOGV("+++ calling JNI_OnLoad(%s)\n", pathName);
548 version = (*func)(gDvm.vmList, NULL);
549 dvmChangeStatus(self, oldStatus);
550 self->classLoaderOverride = prevOverride;
552 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
553 version != JNI_VERSION_1_6)
555 LOGW("JNI_OnLoad returned bad version (%d) in %s %p\n",
556 version, pathName, classLoader);
558 * It's unwise to call dlclose() here, but we can mark it
559 * as bad and ensure that future load attempts will fail.
561 * We don't know how far JNI_OnLoad got, so there could
562 * be some partially-initialized stuff accessible through
563 * newly-registered native method calls. We could try to
564 * unregister them, but that doesn't seem worthwhile.
568 LOGV("+++ finished JNI_OnLoad %s\n", pathName);
573 pNewEntry->onLoadResult = kOnLoadOkay;
575 pNewEntry->onLoadResult = kOnLoadFailed;
577 pNewEntry->onLoadThreadId = 0;
580 * Broadcast a wakeup to anybody sleeping on the condition variable.
582 dvmLockMutex(&pNewEntry->onLoadLock);
583 pthread_cond_broadcast(&pNewEntry->onLoadCond);
584 dvmUnlockMutex(&pNewEntry->onLoadLock);
591 * ===========================================================================
592 * Signature-based method lookup
593 * ===========================================================================
597 * Create the pre-mangled form of the class+method string.
599 * Returns a newly-allocated string, and sets "*pLen" to the length.
601 static char* createJniNameString(const char* classDescriptor,
602 const char* methodName, int* pLen)
605 size_t descriptorLength = strlen(classDescriptor);
607 *pLen = 4 + descriptorLength + strlen(methodName);
609 result = malloc(*pLen +1);
614 * Add one to classDescriptor to skip the "L", and then replace
615 * the final ";" with a "/" after the sprintf() call.
617 sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
618 result[5 + (descriptorLength - 2)] = '/';
624 * Returns a newly-allocated, mangled copy of "str".
626 * "str" is a "modified UTF-8" string. We convert it to UTF-16 first to
629 static char* mangleString(const char* str, int len)
635 //LOGI("mangling '%s' %d\n", str, len);
637 assert(str[len] == '\0');
639 charLen = dvmUtf8Len(str);
640 utf16 = (u2*) malloc(sizeof(u2) * charLen);
644 dvmConvertUtf8ToUtf16(utf16, str);
647 * Compute the length of the mangled string.
649 int i, mangleLen = 0;
651 for (i = 0; i < charLen; i++) {
654 if (ch == '$' || ch > 127) {
672 mangle = (char*) malloc(mangleLen +1);
676 for (i = 0, cp = mangle; i < charLen; i++) {
679 if (ch == '$' || ch > 127) {
680 sprintf(cp, "_0%04x", ch);
714 * Create the mangled form of the parameter types.
716 static char* createMangledSignature(const DexProto* proto)
718 DexStringCache sigCache;
722 dexStringCacheInit(&sigCache);
723 interim = dexProtoGetParameterDescriptors(proto, &sigCache);
724 result = mangleString(interim, strlen(interim));
725 dexStringCacheRelease(&sigCache);
731 * (This is a dvmHashForeach callback.)
733 * Search for a matching method in this shared library.
735 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
737 static int findMethodInLib(void* vlib, void* vmethod)
739 const SharedLib* pLib = (const SharedLib*) vlib;
740 const Method* meth = (const Method*) vmethod;
741 char* preMangleCM = NULL;
742 char* mangleCM = NULL;
743 char* mangleSig = NULL;
744 char* mangleCMSig = NULL;
748 if (meth->clazz->classLoader != pLib->classLoader) {
749 LOGD("+++ not scanning '%s' for '%s' (wrong CL)\n",
750 pLib->pathName, meth->name);
753 LOGV("+++ scanning '%s' for '%s'\n", pLib->pathName, meth->name);
756 * First, we try it without the signature.
759 createJniNameString(meth->clazz->descriptor, meth->name, &len);
760 if (preMangleCM == NULL)
763 mangleCM = mangleString(preMangleCM, len);
764 if (mangleCM == NULL)
767 LOGV("+++ calling dlsym(%s)\n", mangleCM);
768 func = dlsym(pLib->handle, mangleCM);
771 createMangledSignature(&meth->prototype);
772 if (mangleSig == NULL)
775 mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
776 if (mangleCMSig == NULL)
779 sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
781 LOGV("+++ calling dlsym(%s)\n", mangleCMSig);
782 func = dlsym(pLib->handle, mangleCMSig);
784 LOGV("Found '%s' with dlsym\n", mangleCMSig);
787 LOGV("Found '%s' with dlsym\n", mangleCM);
799 * See if the requested method lives in any of the currently-loaded
800 * shared libraries. We do this by checking each of them for the expected
803 static void* lookupSharedLibMethod(const Method* method)
805 if (gDvm.nativeLibs == NULL) {
806 LOGE("Unexpected init state: nativeLibs not ready\n");
809 return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,