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()
38 gDvm.nativeLibs = dvmHashTableCreate(4, freeSharedLibEntry);
39 if (gDvm.nativeLibs == NULL)
48 void dvmNativeShutdown()
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;
76 * If this is a static method, it could be called before the class
77 * has been initialized.
79 if (dvmIsStaticMethod(method)) {
80 if (!dvmIsClassInitialized(clazz) && !dvmInitClass(clazz)) {
81 assert(dvmCheckException(dvmThreadSelf()));
85 assert(dvmIsClassInitialized(clazz) ||
86 dvmIsClassInitializing(clazz));
89 /* start with our internal-native methods */
90 DalvikNativeFunc infunc = dvmLookupInternalNativeMethod(method);
92 /* resolution always gets the same answer, so no race here */
94 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
95 LOGVV("+++ resolved native %s.%s %s, invoking",
96 clazz->descriptor, method->name, desc);
99 if (dvmIsSynchronizedMethod(method)) {
100 ALOGE("ERROR: internal-native can't be declared 'synchronized'");
101 ALOGE("Failing on %s.%s", method->clazz->descriptor, method->name);
102 dvmAbort(); // harsh, but this is VM-internal problem
104 DalvikBridgeFunc dfunc = (DalvikBridgeFunc) infunc;
105 dvmSetNativeFunc((Method*) method, dfunc, NULL);
106 dfunc(args, pResult, method, self);
110 /* now scan any DLLs we have loaded for JNI signatures */
111 void* func = lookupSharedLibMethod(method);
113 /* found it, point it at the JNI bridge and then call it */
114 dvmUseJNIBridge((Method*) method, func);
115 (*method->nativeFunc)(args, pResult, method, self);
120 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
121 ALOGW("No implementation found for native %s.%s:%s",
122 clazz->descriptor, method->name, desc);
126 dvmThrowUnsatisfiedLinkError("Native method not found", method);
131 * ===========================================================================
132 * Native shared library support
133 * ===========================================================================
136 // TODO? if a ClassLoader is unloaded, we need to unload all DLLs that
137 // are associated with it. (Or not -- can't determine if native code
138 // is still using parts of it.)
141 kOnLoadPending = 0, /* initial state, must be zero */
147 * We add one of these to the hash table for every library we load. The
148 * hash is on the "pathName" field.
151 char* pathName; /* absolute path to library */
152 void* handle; /* from dlopen */
153 Object* classLoader; /* ClassLoader we are associated with */
155 pthread_mutex_t onLoadLock; /* guards remaining items */
156 pthread_cond_t onLoadCond; /* wait for JNI_OnLoad in other thread */
157 u4 onLoadThreadId; /* recursive invocation guard */
158 OnLoadState onLoadResult; /* result of earlier JNI_OnLoad */
162 * (This is a dvmHashTableLookup callback.)
164 * Find an entry that matches the string.
166 static int hashcmpNameStr(const void* ventry, const void* vname)
168 const SharedLib* pLib = (const SharedLib*) ventry;
169 const char* name = (const char*) vname;
171 return strcmp(pLib->pathName, name);
175 * (This is a dvmHashTableLookup callback.)
177 * Find an entry that matches the new entry.
179 * We don't compare the class loader here, because you're not allowed to
180 * have the same shared library associated with more than one CL.
182 static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
184 const SharedLib* pLib = (const SharedLib*) ventry;
185 const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
187 ALOGD("--- comparing %p '%s' %p '%s'",
188 pLib, pLib->pathName, pNewLib, pNewLib->pathName);
189 return strcmp(pLib->pathName, pNewLib->pathName);
193 * Check to see if an entry with the same pathname already exists.
195 static SharedLib* findSharedLibEntry(const char* pathName)
197 u4 hash = dvmComputeUtf8Hash(pathName);
200 ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
201 hashcmpNameStr, false);
202 return (SharedLib*)ent;
206 * Add the new entry to the table.
208 * Returns the table entry, which will not be the same as "pLib" if the
209 * entry already exists.
211 static SharedLib* addSharedLibEntry(SharedLib* pLib)
213 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 (SharedLib*)dvmHashTableLookup(gDvm.nativeLibs, hash, pLib,
221 hashcmpSharedLib, true);
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))
261 * Check the result of an earlier call to JNI_OnLoad on this library. If
262 * the call has not yet finished in another thread, wait for it.
264 static bool checkOnLoadResult(SharedLib* pEntry)
266 Thread* self = dvmThreadSelf();
267 if (pEntry->onLoadThreadId == self->threadId) {
269 * Check this so we don't end up waiting for ourselves. We need
270 * to return "true" so the caller can continue.
272 ALOGI("threadid=%d: recursive native library load attempt (%s)",
273 self->threadId, pEntry->pathName);
277 ALOGV("+++ retrieving %s OnLoad status", pEntry->pathName);
280 dvmLockMutex(&pEntry->onLoadLock);
281 while (pEntry->onLoadResult == kOnLoadPending) {
282 ALOGD("threadid=%d: waiting for %s OnLoad status",
283 self->threadId, pEntry->pathName);
284 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
285 pthread_cond_wait(&pEntry->onLoadCond, &pEntry->onLoadLock);
286 dvmChangeStatus(self, oldStatus);
288 if (pEntry->onLoadResult == kOnLoadOkay) {
289 ALOGV("+++ earlier OnLoad(%s) okay", pEntry->pathName);
292 ALOGV("+++ earlier OnLoad(%s) failed", pEntry->pathName);
295 dvmUnlockMutex(&pEntry->onLoadLock);
299 typedef int (*OnLoadFunc)(JavaVM*, void*);
302 * Load native code from the specified absolute pathname. Per the spec,
303 * if we've already loaded a library with the specified pathname, we
304 * return without doing anything.
306 * TODO? for better results we should absolutify the pathname. For fully
307 * correct results we should stat to get the inode and compare that. The
308 * existing implementation is fine so long as everybody is using
309 * System.loadLibrary.
311 * The library will be associated with the specified class loader. The JNI
312 * spec says we can't load the same library into more than one class loader.
314 * Returns "true" on success. On failure, sets *detail to a
315 * human-readable description of the error or NULL if no detail is
316 * available; ownership of the string is transferred to the caller.
318 bool dvmLoadNativeCode(const char* pathName, Object* classLoader,
325 /* reduce noise by not chattering about system libraries */
326 verbose = !!strncmp(pathName, "/system", sizeof("/system")-1);
327 verbose = verbose && !!strncmp(pathName, "/vendor", sizeof("/vendor")-1);
330 ALOGD("Trying to load lib %s %p", pathName, classLoader);
335 * See if we've already loaded it. If we have, and the class loader
336 * matches, return successfully without doing anything.
338 pEntry = findSharedLibEntry(pathName);
339 if (pEntry != NULL) {
340 if (pEntry->classLoader != classLoader) {
341 ALOGW("Shared lib '%s' already opened by CL %p; can't open in %p",
342 pathName, pEntry->classLoader, classLoader);
346 ALOGD("Shared lib '%s' already loaded in same CL %p",
347 pathName, classLoader);
349 if (!checkOnLoadResult(pEntry))
355 * Open the shared library. Because we're using a full path, the system
356 * doesn't have to search through LD_LIBRARY_PATH. (It may do so to
357 * resolve this library's dependencies though.)
359 * Failures here are expected when java.library.path has several entries
360 * and we have to hunt for the lib.
362 * The current version of the dynamic linker prints detailed information
363 * about dlopen() failures. Some things to check if the message is
365 * - make sure the library exists on the device
366 * - verify that the right path is being opened (the debug log message
367 * above can help with that)
368 * - check to see if the library is valid (e.g. not zero bytes long)
369 * - check config/prelink-linux-arm.map to ensure that the library
370 * is listed and is not being overrun by the previous entry (if
371 * loading suddenly stops working on a prelinked library, this is
372 * a good one to check)
373 * - write a trivial app that calls sleep() then dlopen(), attach
374 * to it with "strace -p <pid>" while it sleeps, and watch for
375 * attempts to open nonexistent dependent shared libs
377 * This can execute slowly for a large library on a busy system, so we
378 * want to switch from RUNNING to VMWAIT while it executes. This allows
379 * the GC to ignore us.
381 Thread* self = dvmThreadSelf();
382 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
383 handle = dlopen(pathName, RTLD_LAZY);
384 dvmChangeStatus(self, oldStatus);
386 if (handle == NULL) {
387 *detail = strdup(dlerror());
388 ALOGE("dlopen(\"%s\") failed: %s", pathName, *detail);
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 ALOGI("WOW: we lost a race to add a shared lib (%s CL=%p)",
407 pathName, classLoader);
408 freeSharedLibEntry(pNewEntry);
409 return checkOnLoadResult(pActualEntry);
412 ALOGD("Added shared lib %s %p", pathName, classLoader);
418 vonLoad = dlsym(handle, "JNI_OnLoad");
419 if (vonLoad == NULL) {
420 ALOGD("No JNI_OnLoad found in %s %p, skipping init",
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 = (OnLoadFunc)vonLoad;
430 Object* prevOverride = self->classLoaderOverride;
432 self->classLoaderOverride = classLoader;
433 oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
434 if (gDvm.verboseJni) {
435 ALOGI("[Calling JNI_OnLoad for \"%s\"]", pathName);
437 version = (*func)(gDvmJni.jniVm, NULL);
438 dvmChangeStatus(self, oldStatus);
439 self->classLoaderOverride = prevOverride;
441 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
442 version != JNI_VERSION_1_6)
444 ALOGW("JNI_OnLoad returned bad version (%d) in %s %p",
445 version, pathName, classLoader);
447 * It's unwise to call dlclose() here, but we can mark it
448 * as bad and ensure that future load attempts will fail.
450 * We don't know how far JNI_OnLoad got, so there could
451 * be some partially-initialized stuff accessible through
452 * newly-registered native method calls. We could try to
453 * unregister them, but that doesn't seem worthwhile.
457 if (gDvm.verboseJni) {
458 ALOGI("[Returned from JNI_OnLoad for \"%s\"]", pathName);
464 pNewEntry->onLoadResult = kOnLoadOkay;
466 pNewEntry->onLoadResult = kOnLoadFailed;
468 pNewEntry->onLoadThreadId = 0;
471 * Broadcast a wakeup to anybody sleeping on the condition variable.
473 dvmLockMutex(&pNewEntry->onLoadLock);
474 pthread_cond_broadcast(&pNewEntry->onLoadCond);
475 dvmUnlockMutex(&pNewEntry->onLoadLock);
482 * Un-register JNI native methods.
484 * There are two relevant fields in struct Method, "nativeFunc" and
485 * "insns". The former holds a function pointer to a "bridge" function
486 * (or, for internal native, the actual implementation). The latter holds
487 * a pointer to the actual JNI method.
489 * The obvious approach is to reset both fields to their initial state
490 * (nativeFunc points at dvmResolveNativeMethod, insns holds NULL), but
491 * that creates some unpleasant race conditions. In particular, if another
492 * thread is executing inside the call bridge for the method in question,
493 * and we reset insns to NULL, the VM will crash. (See the comments above
494 * dvmSetNativeFunc() for additional commentary.)
496 * We can't rely on being able to update two 32-bit fields in one atomic
497 * operation (e.g. no 64-bit atomic ops on ARMv5TE), so we want to change
498 * only one field. It turns out we can simply reset nativeFunc to its
499 * initial state, leaving insns alone, because dvmResolveNativeMethod
500 * ignores "insns" entirely.
502 * When the method is re-registered, both fields will be updated, but
503 * dvmSetNativeFunc guarantees that "insns" is updated first. This means
504 * we shouldn't be in a situation where we have a "live" call bridge and
505 * a stale implementation pointer.
507 static void unregisterJNINativeMethods(Method* methods, size_t count)
512 Method* meth = &methods[count];
513 if (!dvmIsNativeMethod(meth))
515 if (dvmIsAbstractMethod(meth)) /* avoid abstract method stubs */
519 * Strictly speaking this ought to test the function pointer against
520 * the various JNI bridge functions to ensure that we only undo
521 * methods that were registered through JNI. In practice, any
522 * native method with a non-NULL "insns" is a registered JNI method.
524 * If we inadvertently unregister an internal-native, it'll get
525 * re-resolved on the next call; unregistering an unregistered
526 * JNI method is a no-op. So we don't really need to test for
530 ALOGD("Unregistering JNI method %s.%s:%s",
531 meth->clazz->descriptor, meth->name, meth->shorty);
532 dvmSetNativeFunc(meth, dvmResolveNativeMethod, NULL);
537 * Un-register all JNI native methods from a class.
539 void dvmUnregisterJNINativeMethods(ClassObject* clazz)
541 unregisterJNINativeMethods(clazz->directMethods, clazz->directMethodCount);
542 unregisterJNINativeMethods(clazz->virtualMethods, clazz->virtualMethodCount);
547 * ===========================================================================
548 * Signature-based method lookup
549 * ===========================================================================
553 * Create the pre-mangled form of the class+method string.
555 * Returns a newly-allocated string, and sets "*pLen" to the length.
557 static char* createJniNameString(const char* classDescriptor,
558 const char* methodName, int* pLen)
561 size_t descriptorLength = strlen(classDescriptor);
563 *pLen = 4 + descriptorLength + strlen(methodName);
565 result = (char*)malloc(*pLen +1);
570 * Add one to classDescriptor to skip the "L", and then replace
571 * the final ";" with a "/" after the sprintf() call.
573 sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
574 result[5 + (descriptorLength - 2)] = '/';
580 * Returns a newly-allocated, mangled copy of "str".
582 * "str" is a "modified UTF-8" string. We convert it to UTF-16 first to
585 static char* mangleString(const char* str, int len)
587 //ALOGI("mangling '%s' %d", str, len);
589 assert(str[len] == '\0');
591 size_t charLen = dvmUtf8Len(str);
592 u2* utf16 = (u2*) malloc(sizeof(u2) * charLen);
596 dvmConvertUtf8ToUtf16(utf16, str);
599 * Compute the length of the mangled string.
601 size_t mangleLen = 0;
602 for (size_t i = 0; i < charLen; i++) {
605 if (ch == '$' || ch > 127) {
621 char* mangle = (char*) malloc(mangleLen +1);
622 if (mangle == NULL) {
628 for (size_t i = 0; i < charLen; i++) {
631 if (ch == '$' || ch > 127) {
632 sprintf(cp, "_0%04x", ch);
665 * Create the mangled form of the parameter types.
667 static char* createMangledSignature(const DexProto* proto)
669 DexStringCache sigCache;
673 dexStringCacheInit(&sigCache);
674 interim = dexProtoGetParameterDescriptors(proto, &sigCache);
675 result = mangleString(interim, strlen(interim));
676 dexStringCacheRelease(&sigCache);
682 * (This is a dvmHashForeach callback.)
684 * Search for a matching method in this shared library.
686 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
688 static int findMethodInLib(void* vlib, void* vmethod)
690 const SharedLib* pLib = (const SharedLib*) vlib;
691 const Method* meth = (const Method*) vmethod;
692 char* preMangleCM = NULL;
693 char* mangleCM = NULL;
694 char* mangleSig = NULL;
695 char* mangleCMSig = NULL;
699 if (meth->clazz->classLoader != pLib->classLoader) {
700 ALOGV("+++ not scanning '%s' for '%s' (wrong CL)",
701 pLib->pathName, meth->name);
704 ALOGV("+++ scanning '%s' for '%s'", pLib->pathName, meth->name);
707 * First, we try it without the signature.
710 createJniNameString(meth->clazz->descriptor, meth->name, &len);
711 if (preMangleCM == NULL)
714 mangleCM = mangleString(preMangleCM, len);
715 if (mangleCM == NULL)
718 ALOGV("+++ calling dlsym(%s)", mangleCM);
719 func = dlsym(pLib->handle, mangleCM);
722 createMangledSignature(&meth->prototype);
723 if (mangleSig == NULL)
726 mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
727 if (mangleCMSig == NULL)
730 sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
732 ALOGV("+++ calling dlsym(%s)", mangleCMSig);
733 func = dlsym(pLib->handle, mangleCMSig);
735 ALOGV("Found '%s' with dlsym", mangleCMSig);
738 ALOGV("Found '%s' with dlsym", mangleCM);
750 * See if the requested method lives in any of the currently-loaded
751 * shared libraries. We do this by checking each of them for the expected
754 static void* lookupSharedLibMethod(const Method* method)
756 if (gDvm.nativeLibs == NULL) {
757 ALOGE("Unexpected init state: nativeLibs not ready");
760 return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,