blob: 967482cfcf3a17c0e1afdd4ae222e941127b6d14 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
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 */
Andy McFadden59b61772009-05-13 16:44:34 -070016
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080017/*
18 * Native method resolution.
19 *
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
22 * alternative to JNI.
23 */
24#include "Dalvik.h"
25
26#include <stdlib.h>
27#include <dlfcn.h>
28
29static void freeSharedLibEntry(void* ptr);
30static void* lookupSharedLibMethod(const Method* method);
31
32
33/*
34 * Initialize the native code loader.
35 */
36bool dvmNativeStartup(void)
37{
38 gDvm.nativeLibs = dvmHashTableCreate(4, freeSharedLibEntry);
39 if (gDvm.nativeLibs == NULL)
40 return false;
41
42 return true;
43}
44
45/*
46 * Free up our tables.
47 */
48void dvmNativeShutdown(void)
49{
50 dvmHashTableFree(gDvm.nativeLibs);
51 gDvm.nativeLibs = NULL;
52}
53
54
55/*
56 * Resolve a native method and invoke it.
57 *
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.
61 *
62 * Initializes method's class if necessary.
63 *
64 * An exception is thrown on resolution failure.
Andy McFadden59b61772009-05-13 16:44:34 -070065 *
66 * (This should not be taking "const Method*", because it modifies the
67 * structure, but the declaration needs to match the DalvikBridgeFunc
68 * type definition.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080069 */
70void dvmResolveNativeMethod(const u4* args, JValue* pResult,
71 const Method* method, Thread* self)
72{
73 ClassObject* clazz = method->clazz;
74 void* func;
75
76 /*
77 * If this is a static method, it could be called before the class
78 * has been initialized.
79 */
80 if (dvmIsStaticMethod(method)) {
81 if (!dvmIsClassInitialized(clazz) && !dvmInitClass(clazz)) {
82 assert(dvmCheckException(dvmThreadSelf()));
83 return;
84 }
85 } else {
86 assert(dvmIsClassInitialized(clazz) ||
87 dvmIsClassInitializing(clazz));
88 }
89
90 /* start with our internal-native methods */
91 func = dvmLookupInternalNativeMethod(method);
92 if (func != NULL) {
93 /* resolution always gets the same answer, so no race here */
94 IF_LOGVV() {
95 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
96 LOGVV("+++ resolved native %s.%s %s, invoking\n",
97 clazz->descriptor, method->name, desc);
98 free(desc);
99 }
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
104 }
105 DalvikBridgeFunc dfunc = (DalvikBridgeFunc) func;
106 dvmSetNativeFunc(method, dfunc, NULL);
107 assert(method->insns == NULL);
108 dfunc(args, pResult, method, self);
109 return;
110 }
111
112 /* now scan any DLLs we have loaded for JNI signatures */
113 func = lookupSharedLibMethod(method);
114 if (func != NULL) {
Andy McFadden59b61772009-05-13 16:44:34 -0700115 /* found it, point it at the JNI bridge and then call it */
116 dvmUseJNIBridge((Method*) method, func);
Andy McFadden0083d372009-08-21 14:44:04 -0700117 (*method->nativeFunc)(args, pResult, method, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800118 return;
119 }
120
121 IF_LOGW() {
122 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
123 LOGW("No implementation found for native %s.%s %s\n",
124 clazz->descriptor, method->name, desc);
125 free(desc);
126 }
127
128 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", method->name);
129}
130
131
132/*
133 * ===========================================================================
134 * Native shared library support
135 * ===========================================================================
136 */
137
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.)
141
Andy McFadden70318882009-07-09 17:01:04 -0700142typedef enum OnLoadState {
143 kOnLoadPending = 0, /* initial state, must be zero */
144 kOnLoadFailed,
145 kOnLoadOkay,
146} OnLoadState;
147
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800148/*
149 * We add one of these to the hash table for every library we load. The
150 * hash is on the "pathName" field.
151 */
152typedef struct SharedLib {
Andy McFadden70318882009-07-09 17:01:04 -0700153 char* pathName; /* absolute path to library */
154 void* handle; /* from dlopen */
155 Object* classLoader; /* ClassLoader we are associated with */
156
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 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800161} SharedLib;
162
163/*
164 * (This is a dvmHashTableLookup callback.)
165 *
166 * Find an entry that matches the string.
167 */
168static int hashcmpNameStr(const void* ventry, const void* vname)
169{
170 const SharedLib* pLib = (const SharedLib*) ventry;
171 const char* name = (const char*) vname;
172
173 return strcmp(pLib->pathName, name);
174}
175
176/*
177 * (This is a dvmHashTableLookup callback.)
178 *
179 * Find an entry that matches the new entry.
Andy McFadden70318882009-07-09 17:01:04 -0700180 *
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.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800183 */
184static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
185{
186 const SharedLib* pLib = (const SharedLib*) ventry;
187 const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
188
189 LOGD("--- comparing %p '%s' %p '%s'\n",
190 pLib, pLib->pathName, pNewLib, pNewLib->pathName);
191 return strcmp(pLib->pathName, pNewLib->pathName);
192}
193
194/*
195 * Check to see if an entry with the same pathname already exists.
196 */
Andy McFadden70318882009-07-09 17:01:04 -0700197static SharedLib* findSharedLibEntry(const char* pathName)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800198{
199 u4 hash = dvmComputeUtf8Hash(pathName);
200 void* ent;
201
202 ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
203 hashcmpNameStr, false);
204 return ent;
205}
206
207/*
208 * Add the new entry to the table.
209 *
Andy McFadden70318882009-07-09 17:01:04 -0700210 * Returns the table entry, which will not be the same as "pLib" if the
211 * entry already exists.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800212 */
Andy McFadden70318882009-07-09 17:01:04 -0700213static SharedLib* addSharedLibEntry(SharedLib* pLib)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800214{
215 u4 hash = dvmComputeUtf8Hash(pLib->pathName);
216 void* ent;
217
218 /*
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.
222 */
Andy McFadden70318882009-07-09 17:01:04 -0700223 return dvmHashTableLookup(gDvm.nativeLibs, hash, pLib, hashcmpSharedLib,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800224 true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800225}
226
227/*
228 * Free up an entry. (This is a dvmHashTableFree callback.)
229 */
230static void freeSharedLibEntry(void* ptr)
231{
232 SharedLib* pLib = (SharedLib*) ptr;
233
234 /*
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.
237 */
238 if (false)
239 dlclose(pLib->handle);
240 free(pLib->pathName);
241 free(pLib);
242}
243
244/*
245 * Convert library name to system-dependent form, e.g. "jpeg" becomes
246 * "libjpeg.so".
247 *
248 * (Should we have this take buffer+len and avoid the alloc? It gets
249 * called very rarely.)
250 */
251char* dvmCreateSystemLibraryName(char* libName)
252{
253 char buf[256];
254 int len;
255
256 len = snprintf(buf, sizeof(buf), OS_SHARED_LIB_FORMAT_STR, libName);
257 if (len >= (int) sizeof(buf))
258 return NULL;
259 else
260 return strdup(buf);
261}
262
263
264#if 0
265/*
266 * Find a library, given the lib's system-dependent name (e.g. "libjpeg.so").
267 *
268 * We need to search through the path defined by the java.library.path
269 * property.
270 *
271 * Returns NULL if the library was not found.
272 */
273static char* findLibrary(const char* libSysName)
274{
275 char* javaLibraryPath = NULL;
276 char* testName = NULL;
277 char* start;
278 char* cp;
279 bool done;
280
281 javaLibraryPath = dvmGetProperty("java.library.path");
282 if (javaLibraryPath == NULL)
283 goto bail;
284
285 LOGVV("+++ path is '%s'\n", javaLibraryPath);
286
287 start = cp = javaLibraryPath;
288 while (cp != NULL) {
289 char pathBuf[256];
290 int len;
291
292 cp = strchr(start, ':');
293 if (cp != NULL)
294 *cp = '\0';
295
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 */
301 } else {
302 LOGVV("+++ trying '%s'\n", pathBuf);
303 if (access(pathBuf, R_OK) == 0) {
304 testName = strdup(pathBuf);
305 break;
306 }
307 }
308
309 start = cp +1;
310 }
311
312bail:
313 free(javaLibraryPath);
314 return testName;
315}
316
317/*
318 * Load a native shared library, given the system-independent piece of
319 * the library name.
320 *
321 * Throws an exception on failure.
322 */
323void dvmLoadNativeLibrary(StringObject* libNameObj, Object* classLoader)
324{
325 char* libName = NULL;
326 char* libSysName = NULL;
327 char* libPath = NULL;
328
329 /*
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.
333 */
334 if (classLoader != NULL) {
335 Method* findLibrary;
336 Object* findLibResult;
337
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;",
344 "findLibrary");
345 goto bail;
346 }
347
348 findLibResult = (Object*)(u4) dvmCallMethod(findLibrary, classLoader,
349 libNameObj);
350 if (dvmCheckException()) {
351 LOGV("returning early on exception\n");
352 goto bail;
353 }
354 if (findLibResult != NULL) {
355 /* success! */
356 libPath = dvmCreateCstrFromString(libNameObj);
357 LOGI("Found library through CL: '%s'\n", libPath);
358 dvmLoadNativeCode(libPath, classLoader);
359 goto bail;
360 }
361 }
362
363 libName = dvmCreateCstrFromString(libNameObj);
364 if (libName == NULL)
365 goto bail;
366 libSysName = dvmCreateSystemLibraryName(libName);
367 if (libSysName == NULL)
368 goto bail;
369
370 libPath = findLibrary(libSysName);
371 if (libPath != NULL) {
372 LOGD("Found library through path: '%s'\n", libPath);
373 dvmLoadNativeCode(libPath, classLoader);
374 } else {
375 LOGW("Unable to locate shared lib matching '%s'\n", libSysName);
376 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", libName);
377 }
378
379bail:
380 free(libName);
381 free(libSysName);
382 free(libPath);
383}
384#endif
385
Andy McFadden70318882009-07-09 17:01:04 -0700386
387/*
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.
390 */
391static bool checkOnLoadResult(SharedLib* pEntry)
392{
393 Thread* self = dvmThreadSelf();
394 if (pEntry->onLoadThreadId == self->threadId) {
395 /*
396 * Check this so we don't end up waiting for ourselves. We need
397 * to return "true" so the caller can continue.
398 */
399 LOGI("threadid=%d: recursive native library load attempt (%s)\n",
400 self->threadId, pEntry->pathName);
401 return true;
402 }
403
404 LOGV("+++ retrieving %s OnLoad status\n", pEntry->pathName);
405 bool result;
406
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);
414 }
415 if (pEntry->onLoadResult == kOnLoadOkay) {
416 LOGV("+++ earlier OnLoad(%s) okay\n", pEntry->pathName);
417 result = true;
418 } else {
419 LOGV("+++ earlier OnLoad(%s) failed\n", pEntry->pathName);
420 result = false;
421 }
422 dvmUnlockMutex(&pEntry->onLoadLock);
423 return result;
424}
425
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800426typedef int (*OnLoadFunc)(JavaVM*, void*);
427
428/*
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.
432 *
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.
437 *
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.
440 *
441 * Returns "true" on success.
442 */
443bool dvmLoadNativeCode(const char* pathName, Object* classLoader)
444{
Andy McFadden70318882009-07-09 17:01:04 -0700445 SharedLib* pEntry;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800446 void* handle;
Andy McFaddendced7942009-11-17 13:13:34 -0800447 bool verbose;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800448
Andy McFaddendced7942009-11-17 13:13:34 -0800449 /* reduce noise by not chattering about system libraries */
450 verbose = strncmp(pathName, "/system", sizeof("/system")-1) != 0;
451
452 if (verbose)
453 LOGD("Trying to load lib %s %p\n", pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800454
455 /*
456 * See if we've already loaded it. If we have, and the class loader
457 * matches, return successfully without doing anything.
458 */
459 pEntry = findSharedLibEntry(pathName);
460 if (pEntry != NULL) {
461 if (pEntry->classLoader != classLoader) {
462 LOGW("Shared lib '%s' already opened by CL %p; can't open in %p\n",
463 pathName, pEntry->classLoader, classLoader);
464 return false;
465 }
Andy McFaddendced7942009-11-17 13:13:34 -0800466 if (verbose) {
467 LOGD("Shared lib '%s' already loaded in same CL %p\n",
468 pathName, classLoader);
469 }
Andy McFadden70318882009-07-09 17:01:04 -0700470 if (!checkOnLoadResult(pEntry))
471 return false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800472 return true;
473 }
474
475 /*
476 * Open the shared library. Because we're using a full path, the system
477 * doesn't have to search through LD_LIBRARY_PATH. (It may do so to
478 * resolve this library's dependencies though.)
479 *
The Android Open Source Project99409882009-03-18 22:20:24 -0700480 * Failures here are expected when java.library.path has several entries
481 * and we have to hunt for the lib.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800482 *
Andy McFaddendced7942009-11-17 13:13:34 -0800483 * The current version of the dynamic linker prints detailed information
484 * about dlopen() failures. Some things to check if the message is
485 * cryptic:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800486 * - make sure the library exists on the device
487 * - verify that the right path is being opened (the debug log message
488 * above can help with that)
The Android Open Source Project99409882009-03-18 22:20:24 -0700489 * - check to see if the library is valid (e.g. not zero bytes long)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800490 * - check config/prelink-linux-arm.map to ensure that the library
491 * is listed and is not being overrun by the previous entry (if
The Android Open Source Project99409882009-03-18 22:20:24 -0700492 * loading suddenly stops working on a prelinked library, this is
493 * a good one to check)
494 * - write a trivial app that calls sleep() then dlopen(), attach
495 * to it with "strace -p <pid>" while it sleeps, and watch for
496 * attempts to open nonexistent dependent shared libs
Andy McFadden2aa43612009-06-17 16:29:30 -0700497 *
498 * This can execute slowly for a large library on a busy system, so we
499 * want to switch from RUNNING to VMWAIT while it executes. This allows
500 * the GC to ignore us.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800501 */
Andy McFadden2aa43612009-06-17 16:29:30 -0700502 Thread* self = dvmThreadSelf();
503 int oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800504 handle = dlopen(pathName, RTLD_LAZY);
Andy McFadden2aa43612009-06-17 16:29:30 -0700505 dvmChangeStatus(self, oldStatus);
506
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800507 if (handle == NULL) {
508 LOGI("Unable to dlopen(%s): %s\n", pathName, dlerror());
509 return false;
510 }
511
Andy McFadden70318882009-07-09 17:01:04 -0700512 /* create a new entry */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800513 SharedLib* pNewEntry;
Andy McFadden70318882009-07-09 17:01:04 -0700514 pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800515 pNewEntry->pathName = strdup(pathName);
516 pNewEntry->handle = handle;
517 pNewEntry->classLoader = classLoader;
Andy McFadden70318882009-07-09 17:01:04 -0700518 dvmInitMutex(&pNewEntry->onLoadLock);
519 pthread_cond_init(&pNewEntry->onLoadCond, NULL);
520 pNewEntry->onLoadThreadId = self->threadId;
521
522 /* try to add it to the list */
523 SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
524
525 if (pNewEntry != pActualEntry) {
526 LOGI("WOW: we lost a race to add a shared lib (%s CL=%p)\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800527 pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800528 freeSharedLibEntry(pNewEntry);
Andy McFadden70318882009-07-09 17:01:04 -0700529 return checkOnLoadResult(pActualEntry);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800530 } else {
Andy McFaddendced7942009-11-17 13:13:34 -0800531 if (verbose)
532 LOGD("Added shared lib %s %p\n", pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800533
Andy McFadden70318882009-07-09 17:01:04 -0700534 bool result = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800535 void* vonLoad;
536 int version;
537
538 vonLoad = dlsym(handle, "JNI_OnLoad");
539 if (vonLoad == NULL) {
Andy McFaddendced7942009-11-17 13:13:34 -0800540 LOGD("No JNI_OnLoad found in %s %p, skipping init\n",
541 pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800542 } else {
543 /*
544 * Call JNI_OnLoad. We have to override the current class
545 * loader, which will always be "null" since the stuff at the
Andy McFadden70318882009-07-09 17:01:04 -0700546 * top of the stack is around Runtime.loadLibrary(). (See
547 * the comments in the JNI FindClass function.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800548 */
549 OnLoadFunc func = vonLoad;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800550 Object* prevOverride = self->classLoaderOverride;
551
552 self->classLoaderOverride = classLoader;
Andy McFadden2aa43612009-06-17 16:29:30 -0700553 oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
Andy McFadden70318882009-07-09 17:01:04 -0700554 LOGV("+++ calling JNI_OnLoad(%s)\n", pathName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800555 version = (*func)(gDvm.vmList, NULL);
Andy McFadden2aa43612009-06-17 16:29:30 -0700556 dvmChangeStatus(self, oldStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800557 self->classLoaderOverride = prevOverride;
558
559 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
560 version != JNI_VERSION_1_6)
561 {
562 LOGW("JNI_OnLoad returned bad version (%d) in %s %p\n",
563 version, pathName, classLoader);
Andy McFadden70318882009-07-09 17:01:04 -0700564 /*
565 * It's unwise to call dlclose() here, but we can mark it
566 * as bad and ensure that future load attempts will fail.
567 *
568 * We don't know how far JNI_OnLoad got, so there could
569 * be some partially-initialized stuff accessible through
570 * newly-registered native method calls. We could try to
571 * unregister them, but that doesn't seem worthwhile.
572 */
573 result = false;
574 } else {
575 LOGV("+++ finished JNI_OnLoad %s\n", pathName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800576 }
577 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800578
Andy McFadden70318882009-07-09 17:01:04 -0700579 if (result)
580 pNewEntry->onLoadResult = kOnLoadOkay;
581 else
582 pNewEntry->onLoadResult = kOnLoadFailed;
583
584 pNewEntry->onLoadThreadId = 0;
585
586 /*
587 * Broadcast a wakeup to anybody sleeping on the condition variable.
588 */
589 dvmLockMutex(&pNewEntry->onLoadLock);
590 pthread_cond_broadcast(&pNewEntry->onLoadCond);
591 dvmUnlockMutex(&pNewEntry->onLoadLock);
592 return result;
593 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800594}
595
596
597/*
598 * ===========================================================================
599 * Signature-based method lookup
600 * ===========================================================================
601 */
602
603/*
604 * Create the pre-mangled form of the class+method string.
605 *
606 * Returns a newly-allocated string, and sets "*pLen" to the length.
607 */
608static char* createJniNameString(const char* classDescriptor,
609 const char* methodName, int* pLen)
610{
611 char* result;
612 size_t descriptorLength = strlen(classDescriptor);
613
614 *pLen = 4 + descriptorLength + strlen(methodName);
615
616 result = malloc(*pLen +1);
617 if (result == NULL)
618 return NULL;
619
620 /*
621 * Add one to classDescriptor to skip the "L", and then replace
622 * the final ";" with a "/" after the sprintf() call.
623 */
624 sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
625 result[5 + (descriptorLength - 2)] = '/';
626
627 return result;
628}
629
630/*
631 * Returns a newly-allocated, mangled copy of "str".
632 *
633 * "str" is a "modified UTF-8" string. We convert it to UTF-16 first to
634 * make life simpler.
635 */
636static char* mangleString(const char* str, int len)
637{
638 u2* utf16 = NULL;
639 char* mangle = NULL;
640 int charLen;
641
642 //LOGI("mangling '%s' %d\n", str, len);
643
644 assert(str[len] == '\0');
645
646 charLen = dvmUtf8Len(str);
647 utf16 = (u2*) malloc(sizeof(u2) * charLen);
648 if (utf16 == NULL)
649 goto bail;
650
651 dvmConvertUtf8ToUtf16(utf16, str);
652
653 /*
654 * Compute the length of the mangled string.
655 */
656 int i, mangleLen = 0;
657
658 for (i = 0; i < charLen; i++) {
659 u2 ch = utf16[i];
660
Brian McKennadfdaa872009-07-19 20:49:26 +1000661 if (ch == '$' || ch > 127) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800662 mangleLen += 6;
663 } else {
664 switch (ch) {
665 case '_':
666 case ';':
667 case '[':
668 mangleLen += 2;
669 break;
670 default:
671 mangleLen++;
672 break;
673 }
674 }
675 }
676
677 char* cp;
678
679 mangle = (char*) malloc(mangleLen +1);
680 if (mangle == NULL)
681 goto bail;
682
683 for (i = 0, cp = mangle; i < charLen; i++) {
684 u2 ch = utf16[i];
685
Brian McKennadfdaa872009-07-19 20:49:26 +1000686 if (ch == '$' || ch > 127) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800687 sprintf(cp, "_0%04x", ch);
688 cp += 6;
689 } else {
690 switch (ch) {
691 case '_':
692 *cp++ = '_';
693 *cp++ = '1';
694 break;
695 case ';':
696 *cp++ = '_';
697 *cp++ = '2';
698 break;
699 case '[':
700 *cp++ = '_';
701 *cp++ = '3';
702 break;
703 case '/':
704 *cp++ = '_';
705 break;
706 default:
707 *cp++ = (char) ch;
708 break;
709 }
710 }
711 }
712
713 *cp = '\0';
714
715bail:
716 free(utf16);
717 return mangle;
718}
719
720/*
721 * Create the mangled form of the parameter types.
722 */
723static char* createMangledSignature(const DexProto* proto)
724{
725 DexStringCache sigCache;
726 const char* interim;
727 char* result;
728
729 dexStringCacheInit(&sigCache);
730 interim = dexProtoGetParameterDescriptors(proto, &sigCache);
731 result = mangleString(interim, strlen(interim));
732 dexStringCacheRelease(&sigCache);
733
734 return result;
735}
736
737/*
738 * (This is a dvmHashForeach callback.)
739 *
740 * Search for a matching method in this shared library.
Andy McFadden70318882009-07-09 17:01:04 -0700741 *
742 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800743 */
744static int findMethodInLib(void* vlib, void* vmethod)
745{
746 const SharedLib* pLib = (const SharedLib*) vlib;
747 const Method* meth = (const Method*) vmethod;
748 char* preMangleCM = NULL;
749 char* mangleCM = NULL;
750 char* mangleSig = NULL;
751 char* mangleCMSig = NULL;
752 void* func = NULL;
753 int len;
754
755 if (meth->clazz->classLoader != pLib->classLoader) {
Andy McFaddendced7942009-11-17 13:13:34 -0800756 LOGV("+++ not scanning '%s' for '%s' (wrong CL)\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800757 pLib->pathName, meth->name);
758 return 0;
759 } else
760 LOGV("+++ scanning '%s' for '%s'\n", pLib->pathName, meth->name);
761
762 /*
763 * First, we try it without the signature.
764 */
765 preMangleCM =
766 createJniNameString(meth->clazz->descriptor, meth->name, &len);
767 if (preMangleCM == NULL)
768 goto bail;
769
770 mangleCM = mangleString(preMangleCM, len);
771 if (mangleCM == NULL)
772 goto bail;
773
774 LOGV("+++ calling dlsym(%s)\n", mangleCM);
775 func = dlsym(pLib->handle, mangleCM);
776 if (func == NULL) {
777 mangleSig =
778 createMangledSignature(&meth->prototype);
779 if (mangleSig == NULL)
780 goto bail;
781
782 mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
783 if (mangleCMSig == NULL)
784 goto bail;
785
786 sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
787
788 LOGV("+++ calling dlsym(%s)\n", mangleCMSig);
789 func = dlsym(pLib->handle, mangleCMSig);
790 if (func != NULL) {
791 LOGV("Found '%s' with dlsym\n", mangleCMSig);
792 }
793 } else {
794 LOGV("Found '%s' with dlsym\n", mangleCM);
795 }
796
797bail:
798 free(preMangleCM);
799 free(mangleCM);
800 free(mangleSig);
801 free(mangleCMSig);
802 return (int) func;
803}
804
805/*
806 * See if the requested method lives in any of the currently-loaded
807 * shared libraries. We do this by checking each of them for the expected
808 * method signature.
809 */
810static void* lookupSharedLibMethod(const Method* method)
811{
812 if (gDvm.nativeLibs == NULL) {
813 LOGE("Unexpected init state: nativeLibs not ready\n");
814 dvmAbort();
815 }
816 return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,
817 (void*) method);
818}
819