OSDN Git Service

Remove races from JNI_OnLoad invocation.
[android-x86/dalvik.git] / vm / Native.c
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 /*
17  * Native method resolution.
18  *
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
21  * alternative to JNI.
22  */
23 #include "Dalvik.h"
24
25 #include <stdlib.h>
26 #include <dlfcn.h>
27
28 static void freeSharedLibEntry(void* ptr);
29 static void* lookupSharedLibMethod(const Method* method);
30
31
32 /*
33  * Initialize the native code loader.
34  */
35 bool dvmNativeStartup(void)
36 {
37     gDvm.nativeLibs = dvmHashTableCreate(4, freeSharedLibEntry);
38     if (gDvm.nativeLibs == NULL)
39         return false;
40
41     return true;
42 }
43
44 /*
45  * Free up our tables.
46  */
47 void dvmNativeShutdown(void)
48 {
49     dvmHashTableFree(gDvm.nativeLibs);
50     gDvm.nativeLibs = NULL;
51 }
52
53
54 /*
55  * Resolve a native method and invoke it.
56  *
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
59  * here again.
60  *
61  * Initializes method's class if necessary.
62  *
63  * An exception is thrown on resolution failure.
64  */
65 void dvmResolveNativeMethod(const u4* args, JValue* pResult,
66     const Method* method, Thread* self)
67 {
68     ClassObject* clazz = method->clazz;
69     void* func;
70
71     /*
72      * If this is a static method, it could be called before the class
73      * has been initialized.
74      */
75     if (dvmIsStaticMethod(method)) {
76         if (!dvmIsClassInitialized(clazz) && !dvmInitClass(clazz)) {
77             assert(dvmCheckException(dvmThreadSelf()));
78             return;
79         }
80     } else {
81         assert(dvmIsClassInitialized(clazz) ||
82                dvmIsClassInitializing(clazz));
83     }
84
85     /* start with our internal-native methods */
86     func = dvmLookupInternalNativeMethod(method);
87     if (func != NULL) {
88         /* resolution always gets the same answer, so no race here */
89         IF_LOGVV() {
90             char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
91             LOGVV("+++ resolved native %s.%s %s, invoking\n",
92                 clazz->descriptor, method->name, desc);
93             free(desc);
94         }
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
99         }
100         DalvikBridgeFunc dfunc = (DalvikBridgeFunc) func;
101         dvmSetNativeFunc(method, dfunc, NULL);
102         assert(method->insns == NULL);
103         dfunc(args, pResult, method, self);
104         return;
105     }
106
107     /* now scan any DLLs we have loaded for JNI signatures */
108     func = lookupSharedLibMethod(method);
109     if (func != NULL) {
110         if (dvmIsSynchronizedMethod(method))
111             dvmSetNativeFunc(method, dvmCallSynchronizedJNIMethod, func);
112         else
113             dvmSetNativeFunc(method, dvmCallJNIMethod, func);
114         dvmCallJNIMethod(args, pResult, method, self);
115         return;
116     }
117
118     IF_LOGW() {
119         char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
120         LOGW("No implementation found for native %s.%s %s\n",
121             clazz->descriptor, method->name, desc);
122         free(desc);
123     }
124
125     dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", method->name);
126 }
127
128
129 /*
130  * ===========================================================================
131  *      Native shared library support
132  * ===========================================================================
133  */
134
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.)
138
139 typedef enum OnLoadState {
140     kOnLoadPending = 0,     /* initial state, must be zero */
141     kOnLoadFailed,
142     kOnLoadOkay,
143 } OnLoadState;
144
145 /*
146  * We add one of these to the hash table for every library we load.  The
147  * hash is on the "pathName" field.
148  */
149 typedef struct SharedLib {
150     char*       pathName;           /* absolute path to library */
151     void*       handle;             /* from dlopen */
152     Object*     classLoader;        /* ClassLoader we are associated with */
153
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 */
158 } SharedLib;
159
160 /*
161  * (This is a dvmHashTableLookup callback.)
162  *
163  * Find an entry that matches the string.
164  */
165 static int hashcmpNameStr(const void* ventry, const void* vname)
166 {
167     const SharedLib* pLib = (const SharedLib*) ventry;
168     const char* name = (const char*) vname;
169
170     return strcmp(pLib->pathName, name);
171 }
172
173 /*
174  * (This is a dvmHashTableLookup callback.)
175  *
176  * Find an entry that matches the new entry.
177  *
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.
180  */
181 static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
182 {
183     const SharedLib* pLib = (const SharedLib*) ventry;
184     const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
185
186     LOGD("--- comparing %p '%s' %p '%s'\n",
187         pLib, pLib->pathName, pNewLib, pNewLib->pathName);
188     return strcmp(pLib->pathName, pNewLib->pathName);
189 }
190
191 /*
192  * Check to see if an entry with the same pathname already exists.
193  */
194 static SharedLib* findSharedLibEntry(const char* pathName)
195 {
196     u4 hash = dvmComputeUtf8Hash(pathName);
197     void* ent;
198
199     ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
200                 hashcmpNameStr, false);
201     return ent;
202 }
203
204 /*
205  * Add the new entry to the table.
206  *
207  * Returns the table entry, which will not be the same as "pLib" if the
208  * entry already exists.
209  */
210 static SharedLib* addSharedLibEntry(SharedLib* pLib)
211 {
212     u4 hash = dvmComputeUtf8Hash(pLib->pathName);
213     void* ent;
214
215     /*
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.
219      */
220     return dvmHashTableLookup(gDvm.nativeLibs, hash, pLib, hashcmpSharedLib,
221                 true);
222 }
223
224 /*
225  * Free up an entry.  (This is a dvmHashTableFree callback.)
226  */
227 static void freeSharedLibEntry(void* ptr)
228 {
229     SharedLib* pLib = (SharedLib*) ptr;
230
231     /*
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.
234      */
235     if (false)
236         dlclose(pLib->handle);
237     free(pLib->pathName);
238     free(pLib);
239 }
240
241 /*
242  * Convert library name to system-dependent form, e.g. "jpeg" becomes
243  * "libjpeg.so".
244  *
245  * (Should we have this take buffer+len and avoid the alloc?  It gets
246  * called very rarely.)
247  */
248 char* dvmCreateSystemLibraryName(char* libName)
249 {
250     char buf[256];
251     int len;
252
253     len = snprintf(buf, sizeof(buf), OS_SHARED_LIB_FORMAT_STR, libName);
254     if (len >= (int) sizeof(buf))
255         return NULL;
256     else
257         return strdup(buf);
258 }
259
260
261 #if 0
262 /*
263  * Find a library, given the lib's system-dependent name (e.g. "libjpeg.so").
264  *
265  * We need to search through the path defined by the java.library.path
266  * property.
267  *
268  * Returns NULL if the library was not found.
269  */
270 static char* findLibrary(const char* libSysName)
271 {
272     char* javaLibraryPath = NULL;
273     char* testName = NULL;
274     char* start;
275     char* cp;
276     bool done;
277
278     javaLibraryPath = dvmGetProperty("java.library.path");
279     if (javaLibraryPath == NULL)
280         goto bail;
281
282     LOGVV("+++ path is '%s'\n", javaLibraryPath);
283
284     start = cp = javaLibraryPath;
285     while (cp != NULL) {
286         char pathBuf[256];
287         int len;
288
289         cp = strchr(start, ':');
290         if (cp != NULL)
291             *cp = '\0';
292
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 */
298         } else {
299             LOGVV("+++  trying '%s'\n", pathBuf);
300             if (access(pathBuf, R_OK) == 0) {
301                 testName = strdup(pathBuf);
302                 break;
303             }
304         }
305
306         start = cp +1;
307     }
308
309 bail:
310     free(javaLibraryPath);
311     return testName;
312 }
313
314 /*
315  * Load a native shared library, given the system-independent piece of
316  * the library name.
317  *
318  * Throws an exception on failure.
319  */
320 void dvmLoadNativeLibrary(StringObject* libNameObj, Object* classLoader)
321 {
322     char* libName = NULL;
323     char* libSysName = NULL;
324     char* libPath = NULL;
325
326     /*
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.
330      */
331     if (classLoader != NULL) {
332         Method* findLibrary;
333         Object* findLibResult;
334
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;",
341                 "findLibrary");
342             goto bail;
343         }
344
345         findLibResult = (Object*)(u4) dvmCallMethod(findLibrary, classLoader,
346                                             libNameObj);
347         if (dvmCheckException()) {
348             LOGV("returning early on exception\n");
349             goto bail;
350         }
351         if (findLibResult != NULL) {
352             /* success! */
353             libPath = dvmCreateCstrFromString(libNameObj);
354             LOGI("Found library through CL: '%s'\n", libPath);
355             dvmLoadNativeCode(libPath, classLoader);
356             goto bail;
357         }
358     }
359
360     libName = dvmCreateCstrFromString(libNameObj);
361     if (libName == NULL)
362         goto bail;
363     libSysName = dvmCreateSystemLibraryName(libName);
364     if (libSysName == NULL)
365         goto bail;
366
367     libPath = findLibrary(libSysName);
368     if (libPath != NULL) {
369         LOGD("Found library through path: '%s'\n", libPath);
370         dvmLoadNativeCode(libPath, classLoader);
371     } else {
372         LOGW("Unable to locate shared lib matching '%s'\n", libSysName);
373         dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", libName);
374     }
375
376 bail:
377     free(libName);
378     free(libSysName);
379     free(libPath);
380 }
381 #endif
382
383
384 /*
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.
387  */
388 static bool checkOnLoadResult(SharedLib* pEntry)
389 {
390     Thread* self = dvmThreadSelf();
391     if (pEntry->onLoadThreadId == self->threadId) {
392         /*
393          * Check this so we don't end up waiting for ourselves.  We need
394          * to return "true" so the caller can continue.
395          */
396         LOGI("threadid=%d: recursive native library load attempt (%s)\n",
397             self->threadId, pEntry->pathName);
398         return true;
399     }
400
401     LOGV("+++ retrieving %s OnLoad status\n", pEntry->pathName);
402     bool result;
403
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);
411     }
412     if (pEntry->onLoadResult == kOnLoadOkay) {
413         LOGV("+++ earlier OnLoad(%s) okay\n", pEntry->pathName);
414         result = true;
415     } else {
416         LOGV("+++ earlier OnLoad(%s) failed\n", pEntry->pathName);
417         result = false;
418     }
419     dvmUnlockMutex(&pEntry->onLoadLock);
420     return result;
421 }
422
423 typedef int (*OnLoadFunc)(JavaVM*, void*);
424
425 /*
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.
429  *
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.
434  *
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.
437  *
438  * Returns "true" on success.
439  */
440 bool dvmLoadNativeCode(const char* pathName, Object* classLoader)
441 {
442     SharedLib* pEntry;
443     void* handle;
444
445     LOGD("Trying to load lib %s %p\n", pathName, classLoader);
446
447     /*
448      * See if we've already loaded it.  If we have, and the class loader
449      * matches, return successfully without doing anything.
450      */
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);
456             return false;
457         }
458         LOGD("Shared lib '%s' already loaded in same CL %p\n",
459             pathName, classLoader);
460         if (!checkOnLoadResult(pEntry))
461             return false;
462         return true;
463     }
464
465     /*
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.)
469      *
470      * Failures here are expected when java.library.path has several entries.
471      *
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
487      *
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.
491      */
492     Thread* self = dvmThreadSelf();
493     int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
494     handle = dlopen(pathName, RTLD_LAZY);
495     dvmChangeStatus(self, oldStatus);
496
497     if (handle == NULL) {
498         LOGI("Unable to dlopen(%s): %s\n", pathName, dlerror());
499         return false;
500     }
501
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;
511
512     /* try to add it to the list */
513     SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
514
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);
520     } else {
521         LOGD("Added shared lib %s %p\n", pathName, classLoader);
522
523         bool result = true;
524         void* vonLoad;
525         int version;
526
527         vonLoad = dlsym(handle, "JNI_OnLoad");
528         if (vonLoad == NULL) {
529             LOGD("No JNI_OnLoad found in %s %p\n", pathName, classLoader);
530         } else {
531             /*
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.)
536              */
537             OnLoadFunc func = vonLoad;
538             Object* prevOverride = self->classLoaderOverride;
539
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;
546
547             if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
548                 version != JNI_VERSION_1_6)
549             {
550                 LOGW("JNI_OnLoad returned bad version (%d) in %s %p\n",
551                     version, pathName, classLoader);
552                 /*
553                  * It's unwise to call dlclose() here, but we can mark it
554                  * as bad and ensure that future load attempts will fail.
555                  *
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.
560                  */
561                 result = false;
562             } else {
563                 LOGV("+++ finished JNI_OnLoad %s\n", pathName);
564             }
565         }
566
567         if (result)
568             pNewEntry->onLoadResult = kOnLoadOkay;
569         else
570             pNewEntry->onLoadResult = kOnLoadFailed;
571
572         pNewEntry->onLoadThreadId = 0;
573
574         /*
575          * Broadcast a wakeup to anybody sleeping on the condition variable.
576          */
577         dvmLockMutex(&pNewEntry->onLoadLock);
578         pthread_cond_broadcast(&pNewEntry->onLoadCond);
579         dvmUnlockMutex(&pNewEntry->onLoadLock);
580         return result;
581     }
582 }
583
584
585 /*
586  * ===========================================================================
587  *      Signature-based method lookup
588  * ===========================================================================
589  */
590
591 /*
592  * Create the pre-mangled form of the class+method string.
593  *
594  * Returns a newly-allocated string, and sets "*pLen" to the length.
595  */
596 static char* createJniNameString(const char* classDescriptor,
597     const char* methodName, int* pLen)
598 {
599     char* result;
600     size_t descriptorLength = strlen(classDescriptor);
601
602     *pLen = 4 + descriptorLength + strlen(methodName);
603
604     result = malloc(*pLen +1);
605     if (result == NULL)
606         return NULL;
607
608     /*
609      * Add one to classDescriptor to skip the "L", and then replace
610      * the final ";" with a "/" after the sprintf() call.
611      */
612     sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
613     result[5 + (descriptorLength - 2)] = '/';
614
615     return result;
616 }
617
618 /*
619  * Returns a newly-allocated, mangled copy of "str".
620  *
621  * "str" is a "modified UTF-8" string.  We convert it to UTF-16 first to
622  * make life simpler.
623  */
624 static char* mangleString(const char* str, int len)
625 {
626     u2* utf16 = NULL;
627     char* mangle = NULL;
628     int charLen;
629
630     //LOGI("mangling '%s' %d\n", str, len);
631
632     assert(str[len] == '\0');
633
634     charLen = dvmUtf8Len(str);
635     utf16 = (u2*) malloc(sizeof(u2) * charLen);
636     if (utf16 == NULL)
637         goto bail;
638
639     dvmConvertUtf8ToUtf16(utf16, str);
640
641     /*
642      * Compute the length of the mangled string.
643      */
644     int i, mangleLen = 0;
645
646     for (i = 0; i < charLen; i++) {
647         u2 ch = utf16[i];
648
649         if (ch > 127) {
650             mangleLen += 6;
651         } else {
652             switch (ch) {
653             case '_':
654             case ';':
655             case '[':
656                 mangleLen += 2;
657                 break;
658             default:
659                 mangleLen++;
660                 break;
661             }
662         }
663     }
664
665     char* cp;
666
667     mangle = (char*) malloc(mangleLen +1);
668     if (mangle == NULL)
669         goto bail;
670
671     for (i = 0, cp = mangle; i < charLen; i++) {
672         u2 ch = utf16[i];
673
674         if (ch > 127) {
675             sprintf(cp, "_0%04x", ch);
676             cp += 6;
677         } else {
678             switch (ch) {
679             case '_':
680                 *cp++ = '_';
681                 *cp++ = '1';
682                 break;
683             case ';':
684                 *cp++ = '_';
685                 *cp++ = '2';
686                 break;
687             case '[':
688                 *cp++ = '_';
689                 *cp++ = '3';
690                 break;
691             case '/':
692                 *cp++ = '_';
693                 break;
694             default:
695                 *cp++ = (char) ch;
696                 break;
697             }
698         }
699     }
700
701     *cp = '\0';
702
703 bail:
704     free(utf16);
705     return mangle;
706 }
707
708 /*
709  * Create the mangled form of the parameter types.
710  */
711 static char* createMangledSignature(const DexProto* proto)
712 {
713     DexStringCache sigCache;
714     const char* interim;
715     char* result;
716
717     dexStringCacheInit(&sigCache);
718     interim = dexProtoGetParameterDescriptors(proto, &sigCache);
719     result = mangleString(interim, strlen(interim));
720     dexStringCacheRelease(&sigCache);
721
722     return result;
723 }
724
725 /*
726  * (This is a dvmHashForeach callback.)
727  *
728  * Search for a matching method in this shared library.
729  *
730  * TODO: we may want to skip libraries for which JNI_OnLoad failed.
731  */
732 static int findMethodInLib(void* vlib, void* vmethod)
733 {
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;
740     void* func = NULL;
741     int len;
742
743     if (meth->clazz->classLoader != pLib->classLoader) {
744         LOGD("+++ not scanning '%s' for '%s' (wrong CL)\n",
745             pLib->pathName, meth->name);
746         return 0;
747     } else
748         LOGV("+++ scanning '%s' for '%s'\n", pLib->pathName, meth->name);
749
750     /*
751      * First, we try it without the signature.
752      */
753     preMangleCM =
754         createJniNameString(meth->clazz->descriptor, meth->name, &len);
755     if (preMangleCM == NULL)
756         goto bail;
757
758     mangleCM = mangleString(preMangleCM, len);
759     if (mangleCM == NULL)
760         goto bail;
761
762     LOGV("+++ calling dlsym(%s)\n", mangleCM);
763     func = dlsym(pLib->handle, mangleCM);
764     if (func == NULL) {
765         mangleSig =
766             createMangledSignature(&meth->prototype);
767         if (mangleSig == NULL)
768             goto bail;
769
770         mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
771         if (mangleCMSig == NULL)
772             goto bail;
773
774         sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
775
776         LOGV("+++ calling dlsym(%s)\n", mangleCMSig);
777         func = dlsym(pLib->handle, mangleCMSig);
778         if (func != NULL) {
779             LOGV("Found '%s' with dlsym\n", mangleCMSig);
780         }
781     } else {
782         LOGV("Found '%s' with dlsym\n", mangleCM);
783     }
784
785 bail:
786     free(preMangleCM);
787     free(mangleCM);
788     free(mangleSig);
789     free(mangleCMSig);
790     return (int) func;
791 }
792
793 /*
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
796  * method signature.
797  */
798 static void* lookupSharedLibMethod(const Method* method)
799 {
800     if (gDvm.nativeLibs == NULL) {
801         LOGE("Unexpected init state: nativeLibs not ready\n");
802         dvmAbort();
803     }
804     return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,
805         (void*) method);
806 }
807