blob: 4793ab3cda31bd175fb65b505f4d298fc594cabb [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
Andy McFadden1e83b4d2010-07-15 17:20:24 -070060 * here again unless the method is unregistered.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080061 *
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;
Andy McFadden1e83b4d2010-07-15 17:20:24 -0700106 dvmSetNativeFunc((Method*) method, dfunc, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800107 dfunc(args, pResult, method, self);
108 return;
109 }
110
111 /* now scan any DLLs we have loaded for JNI signatures */
112 func = lookupSharedLibMethod(method);
113 if (func != NULL) {
Andy McFadden59b61772009-05-13 16:44:34 -0700114 /* found it, point it at the JNI bridge and then call it */
115 dvmUseJNIBridge((Method*) method, func);
Andy McFadden0083d372009-08-21 14:44:04 -0700116 (*method->nativeFunc)(args, pResult, method, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800117 return;
118 }
119
120 IF_LOGW() {
121 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
122 LOGW("No implementation found for native %s.%s %s\n",
123 clazz->descriptor, method->name, desc);
124 free(desc);
125 }
126
127 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", method->name);
128}
129
130
131/*
132 * ===========================================================================
133 * Native shared library support
134 * ===========================================================================
135 */
136
137// TODO? if a ClassLoader is unloaded, we need to unload all DLLs that
138// are associated with it. (Or not -- can't determine if native code
139// is still using parts of it.)
140
Andy McFadden70318882009-07-09 17:01:04 -0700141typedef enum OnLoadState {
142 kOnLoadPending = 0, /* initial state, must be zero */
143 kOnLoadFailed,
144 kOnLoadOkay,
145} OnLoadState;
146
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800147/*
148 * We add one of these to the hash table for every library we load. The
149 * hash is on the "pathName" field.
150 */
151typedef struct SharedLib {
Andy McFadden70318882009-07-09 17:01:04 -0700152 char* pathName; /* absolute path to library */
153 void* handle; /* from dlopen */
154 Object* classLoader; /* ClassLoader we are associated with */
155
156 pthread_mutex_t onLoadLock; /* guards remaining items */
157 pthread_cond_t onLoadCond; /* wait for JNI_OnLoad in other thread */
158 u4 onLoadThreadId; /* recursive invocation guard */
159 OnLoadState onLoadResult; /* result of earlier JNI_OnLoad */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800160} SharedLib;
161
162/*
163 * (This is a dvmHashTableLookup callback.)
164 *
165 * Find an entry that matches the string.
166 */
167static int hashcmpNameStr(const void* ventry, const void* vname)
168{
169 const SharedLib* pLib = (const SharedLib*) ventry;
170 const char* name = (const char*) vname;
171
172 return strcmp(pLib->pathName, name);
173}
174
175/*
176 * (This is a dvmHashTableLookup callback.)
177 *
178 * Find an entry that matches the new entry.
Andy McFadden70318882009-07-09 17:01:04 -0700179 *
180 * We don't compare the class loader here, because you're not allowed to
181 * have the same shared library associated with more than one CL.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800182 */
183static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
184{
185 const SharedLib* pLib = (const SharedLib*) ventry;
186 const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
187
188 LOGD("--- comparing %p '%s' %p '%s'\n",
189 pLib, pLib->pathName, pNewLib, pNewLib->pathName);
190 return strcmp(pLib->pathName, pNewLib->pathName);
191}
192
193/*
194 * Check to see if an entry with the same pathname already exists.
195 */
Andy McFadden70318882009-07-09 17:01:04 -0700196static SharedLib* findSharedLibEntry(const char* pathName)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800197{
198 u4 hash = dvmComputeUtf8Hash(pathName);
199 void* ent;
200
201 ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
202 hashcmpNameStr, false);
203 return ent;
204}
205
206/*
207 * Add the new entry to the table.
208 *
Andy McFadden70318882009-07-09 17:01:04 -0700209 * Returns the table entry, which will not be the same as "pLib" if the
210 * entry already exists.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800211 */
Andy McFadden70318882009-07-09 17:01:04 -0700212static SharedLib* addSharedLibEntry(SharedLib* pLib)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800213{
214 u4 hash = dvmComputeUtf8Hash(pLib->pathName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800215
216 /*
217 * Do the lookup with the "add" flag set. If we add it, we will get
218 * our own pointer back. If somebody beat us to the punch, we'll get
219 * their pointer back instead.
220 */
Andy McFadden70318882009-07-09 17:01:04 -0700221 return dvmHashTableLookup(gDvm.nativeLibs, hash, pLib, hashcmpSharedLib,
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800222 true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800223}
224
225/*
226 * Free up an entry. (This is a dvmHashTableFree callback.)
227 */
228static void freeSharedLibEntry(void* ptr)
229{
230 SharedLib* pLib = (SharedLib*) ptr;
231
232 /*
233 * Calling dlclose() here is somewhat dangerous, because it's possible
234 * that a thread outside the VM is still accessing the code we loaded.
235 */
236 if (false)
237 dlclose(pLib->handle);
238 free(pLib->pathName);
239 free(pLib);
240}
241
242/*
243 * Convert library name to system-dependent form, e.g. "jpeg" becomes
244 * "libjpeg.so".
245 *
246 * (Should we have this take buffer+len and avoid the alloc? It gets
247 * called very rarely.)
248 */
249char* dvmCreateSystemLibraryName(char* libName)
250{
251 char buf[256];
252 int len;
253
254 len = snprintf(buf, sizeof(buf), OS_SHARED_LIB_FORMAT_STR, libName);
255 if (len >= (int) sizeof(buf))
256 return NULL;
257 else
258 return strdup(buf);
259}
260
261
262#if 0
263/*
264 * Find a library, given the lib's system-dependent name (e.g. "libjpeg.so").
265 *
266 * We need to search through the path defined by the java.library.path
267 * property.
268 *
269 * Returns NULL if the library was not found.
270 */
271static char* findLibrary(const char* libSysName)
272{
273 char* javaLibraryPath = NULL;
274 char* testName = NULL;
275 char* start;
276 char* cp;
277 bool done;
278
279 javaLibraryPath = dvmGetProperty("java.library.path");
280 if (javaLibraryPath == NULL)
281 goto bail;
282
283 LOGVV("+++ path is '%s'\n", javaLibraryPath);
284
285 start = cp = javaLibraryPath;
286 while (cp != NULL) {
287 char pathBuf[256];
288 int len;
289
290 cp = strchr(start, ':');
291 if (cp != NULL)
292 *cp = '\0';
293
294 len = snprintf(pathBuf, sizeof(pathBuf), "%s/%s", start, libSysName);
295 if (len >= (int) sizeof(pathBuf)) {
296 LOGW("Path overflowed %d bytes: '%s' / '%s'\n",
297 len, start, libSysName);
298 /* keep going, next one might fit */
299 } else {
300 LOGVV("+++ trying '%s'\n", pathBuf);
301 if (access(pathBuf, R_OK) == 0) {
302 testName = strdup(pathBuf);
303 break;
304 }
305 }
306
307 start = cp +1;
308 }
309
310bail:
311 free(javaLibraryPath);
312 return testName;
313}
314
315/*
316 * Load a native shared library, given the system-independent piece of
317 * the library name.
318 *
319 * Throws an exception on failure.
320 */
321void dvmLoadNativeLibrary(StringObject* libNameObj, Object* classLoader)
322{
323 char* libName = NULL;
324 char* libSysName = NULL;
325 char* libPath = NULL;
326
327 /*
328 * If "classLoader" isn't NULL, call the class loader's "findLibrary"
329 * method with the lib name. If it returns a non-NULL result, we use
330 * that as the pathname.
331 */
332 if (classLoader != NULL) {
333 Method* findLibrary;
334 Object* findLibResult;
335
336 findLibrary = dvmFindVirtualMethodByDescriptor(classLoader->clazz,
337 "findLibrary", "(Ljava/lang/String;)Ljava/lang/String;");
338 if (findLibrary == NULL) {
339 LOGW("Could not find findLibrary() in %s\n",
340 classLoader->clazz->name);
341 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;",
342 "findLibrary");
343 goto bail;
344 }
345
346 findLibResult = (Object*)(u4) dvmCallMethod(findLibrary, classLoader,
347 libNameObj);
348 if (dvmCheckException()) {
349 LOGV("returning early on exception\n");
350 goto bail;
351 }
352 if (findLibResult != NULL) {
353 /* success! */
354 libPath = dvmCreateCstrFromString(libNameObj);
355 LOGI("Found library through CL: '%s'\n", libPath);
356 dvmLoadNativeCode(libPath, classLoader);
357 goto bail;
358 }
359 }
360
361 libName = dvmCreateCstrFromString(libNameObj);
362 if (libName == NULL)
363 goto bail;
364 libSysName = dvmCreateSystemLibraryName(libName);
365 if (libSysName == NULL)
366 goto bail;
367
368 libPath = findLibrary(libSysName);
369 if (libPath != NULL) {
370 LOGD("Found library through path: '%s'\n", libPath);
371 dvmLoadNativeCode(libPath, classLoader);
372 } else {
373 LOGW("Unable to locate shared lib matching '%s'\n", libSysName);
374 dvmThrowException("Ljava/lang/UnsatisfiedLinkError;", libName);
375 }
376
377bail:
378 free(libName);
379 free(libSysName);
380 free(libPath);
381}
382#endif
383
Andy McFadden70318882009-07-09 17:01:04 -0700384
385/*
386 * Check the result of an earlier call to JNI_OnLoad on this library. If
387 * the call has not yet finished in another thread, wait for it.
388 */
389static bool checkOnLoadResult(SharedLib* pEntry)
390{
391 Thread* self = dvmThreadSelf();
392 if (pEntry->onLoadThreadId == self->threadId) {
393 /*
394 * Check this so we don't end up waiting for ourselves. We need
395 * to return "true" so the caller can continue.
396 */
397 LOGI("threadid=%d: recursive native library load attempt (%s)\n",
398 self->threadId, pEntry->pathName);
399 return true;
400 }
401
402 LOGV("+++ retrieving %s OnLoad status\n", pEntry->pathName);
403 bool result;
404
405 dvmLockMutex(&pEntry->onLoadLock);
406 while (pEntry->onLoadResult == kOnLoadPending) {
407 LOGD("threadid=%d: waiting for %s OnLoad status\n",
408 self->threadId, pEntry->pathName);
Carl Shapiro5617ad32010-07-02 10:50:57 -0700409 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
Andy McFadden70318882009-07-09 17:01:04 -0700410 pthread_cond_wait(&pEntry->onLoadCond, &pEntry->onLoadLock);
411 dvmChangeStatus(self, oldStatus);
412 }
413 if (pEntry->onLoadResult == kOnLoadOkay) {
414 LOGV("+++ earlier OnLoad(%s) okay\n", pEntry->pathName);
415 result = true;
416 } else {
417 LOGV("+++ earlier OnLoad(%s) failed\n", pEntry->pathName);
418 result = false;
419 }
420 dvmUnlockMutex(&pEntry->onLoadLock);
421 return result;
422}
423
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800424typedef int (*OnLoadFunc)(JavaVM*, void*);
425
426/*
427 * Load native code from the specified absolute pathname. Per the spec,
428 * if we've already loaded a library with the specified pathname, we
429 * return without doing anything.
430 *
431 * TODO? for better results we should absolutify the pathname. For fully
432 * correct results we should stat to get the inode and compare that. The
433 * existing implementation is fine so long as everybody is using
434 * System.loadLibrary.
435 *
436 * The library will be associated with the specified class loader. The JNI
437 * spec says we can't load the same library into more than one class loader.
438 *
439 * Returns "true" on success.
440 */
441bool dvmLoadNativeCode(const char* pathName, Object* classLoader)
442{
Andy McFadden70318882009-07-09 17:01:04 -0700443 SharedLib* pEntry;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800444 void* handle;
Andy McFaddendced7942009-11-17 13:13:34 -0800445 bool verbose;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800446
Andy McFaddendced7942009-11-17 13:13:34 -0800447 /* reduce noise by not chattering about system libraries */
448 verbose = strncmp(pathName, "/system", sizeof("/system")-1) != 0;
449
450 if (verbose)
451 LOGD("Trying to load lib %s %p\n", pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800452
453 /*
454 * See if we've already loaded it. If we have, and the class loader
455 * matches, return successfully without doing anything.
456 */
457 pEntry = findSharedLibEntry(pathName);
458 if (pEntry != NULL) {
459 if (pEntry->classLoader != classLoader) {
460 LOGW("Shared lib '%s' already opened by CL %p; can't open in %p\n",
461 pathName, pEntry->classLoader, classLoader);
462 return false;
463 }
Andy McFaddendced7942009-11-17 13:13:34 -0800464 if (verbose) {
465 LOGD("Shared lib '%s' already loaded in same CL %p\n",
466 pathName, classLoader);
467 }
Andy McFadden70318882009-07-09 17:01:04 -0700468 if (!checkOnLoadResult(pEntry))
469 return false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800470 return true;
471 }
472
473 /*
474 * Open the shared library. Because we're using a full path, the system
475 * doesn't have to search through LD_LIBRARY_PATH. (It may do so to
476 * resolve this library's dependencies though.)
477 *
The Android Open Source Project99409882009-03-18 22:20:24 -0700478 * Failures here are expected when java.library.path has several entries
479 * and we have to hunt for the lib.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800480 *
Andy McFaddendced7942009-11-17 13:13:34 -0800481 * The current version of the dynamic linker prints detailed information
482 * about dlopen() failures. Some things to check if the message is
483 * cryptic:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800484 * - make sure the library exists on the device
485 * - verify that the right path is being opened (the debug log message
486 * above can help with that)
The Android Open Source Project99409882009-03-18 22:20:24 -0700487 * - check to see if the library is valid (e.g. not zero bytes long)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800488 * - check config/prelink-linux-arm.map to ensure that the library
489 * is listed and is not being overrun by the previous entry (if
The Android Open Source Project99409882009-03-18 22:20:24 -0700490 * loading suddenly stops working on a prelinked library, this is
491 * a good one to check)
492 * - write a trivial app that calls sleep() then dlopen(), attach
493 * to it with "strace -p <pid>" while it sleeps, and watch for
494 * attempts to open nonexistent dependent shared libs
Andy McFadden2aa43612009-06-17 16:29:30 -0700495 *
496 * This can execute slowly for a large library on a busy system, so we
497 * want to switch from RUNNING to VMWAIT while it executes. This allows
498 * the GC to ignore us.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800499 */
Andy McFadden2aa43612009-06-17 16:29:30 -0700500 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -0700501 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800502 handle = dlopen(pathName, RTLD_LAZY);
Andy McFadden2aa43612009-06-17 16:29:30 -0700503 dvmChangeStatus(self, oldStatus);
504
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800505 if (handle == NULL) {
506 LOGI("Unable to dlopen(%s): %s\n", pathName, dlerror());
507 return false;
508 }
509
Andy McFadden70318882009-07-09 17:01:04 -0700510 /* create a new entry */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800511 SharedLib* pNewEntry;
Andy McFadden70318882009-07-09 17:01:04 -0700512 pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800513 pNewEntry->pathName = strdup(pathName);
514 pNewEntry->handle = handle;
515 pNewEntry->classLoader = classLoader;
Andy McFadden70318882009-07-09 17:01:04 -0700516 dvmInitMutex(&pNewEntry->onLoadLock);
517 pthread_cond_init(&pNewEntry->onLoadCond, NULL);
518 pNewEntry->onLoadThreadId = self->threadId;
519
520 /* try to add it to the list */
521 SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
522
523 if (pNewEntry != pActualEntry) {
524 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 -0800525 pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800526 freeSharedLibEntry(pNewEntry);
Andy McFadden70318882009-07-09 17:01:04 -0700527 return checkOnLoadResult(pActualEntry);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800528 } else {
Andy McFaddendced7942009-11-17 13:13:34 -0800529 if (verbose)
530 LOGD("Added shared lib %s %p\n", pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800531
Andy McFadden70318882009-07-09 17:01:04 -0700532 bool result = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800533 void* vonLoad;
534 int version;
535
536 vonLoad = dlsym(handle, "JNI_OnLoad");
537 if (vonLoad == NULL) {
Andy McFaddendced7942009-11-17 13:13:34 -0800538 LOGD("No JNI_OnLoad found in %s %p, skipping init\n",
539 pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800540 } else {
541 /*
542 * Call JNI_OnLoad. We have to override the current class
543 * loader, which will always be "null" since the stuff at the
Andy McFadden70318882009-07-09 17:01:04 -0700544 * top of the stack is around Runtime.loadLibrary(). (See
545 * the comments in the JNI FindClass function.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800546 */
547 OnLoadFunc func = vonLoad;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800548 Object* prevOverride = self->classLoaderOverride;
549
550 self->classLoaderOverride = classLoader;
Andy McFadden2aa43612009-06-17 16:29:30 -0700551 oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
Andy McFadden70318882009-07-09 17:01:04 -0700552 LOGV("+++ calling JNI_OnLoad(%s)\n", pathName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800553 version = (*func)(gDvm.vmList, NULL);
Andy McFadden2aa43612009-06-17 16:29:30 -0700554 dvmChangeStatus(self, oldStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800555 self->classLoaderOverride = prevOverride;
556
557 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
558 version != JNI_VERSION_1_6)
559 {
560 LOGW("JNI_OnLoad returned bad version (%d) in %s %p\n",
561 version, pathName, classLoader);
Andy McFadden70318882009-07-09 17:01:04 -0700562 /*
563 * It's unwise to call dlclose() here, but we can mark it
564 * as bad and ensure that future load attempts will fail.
565 *
566 * We don't know how far JNI_OnLoad got, so there could
567 * be some partially-initialized stuff accessible through
568 * newly-registered native method calls. We could try to
569 * unregister them, but that doesn't seem worthwhile.
570 */
571 result = false;
572 } else {
573 LOGV("+++ finished JNI_OnLoad %s\n", pathName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800574 }
575 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800576
Andy McFadden70318882009-07-09 17:01:04 -0700577 if (result)
578 pNewEntry->onLoadResult = kOnLoadOkay;
579 else
580 pNewEntry->onLoadResult = kOnLoadFailed;
581
582 pNewEntry->onLoadThreadId = 0;
583
584 /*
585 * Broadcast a wakeup to anybody sleeping on the condition variable.
586 */
587 dvmLockMutex(&pNewEntry->onLoadLock);
588 pthread_cond_broadcast(&pNewEntry->onLoadCond);
589 dvmUnlockMutex(&pNewEntry->onLoadLock);
590 return result;
591 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800592}
593
594
595/*
Andy McFadden1e83b4d2010-07-15 17:20:24 -0700596 * Un-register JNI native methods.
597 *
598 * There are two relevant fields in struct Method, "nativeFunc" and
599 * "insns". The former holds a function pointer to a "bridge" function
600 * (or, for internal native, the actual implementation). The latter holds
601 * a pointer to the actual JNI method.
602 *
603 * The obvious approach is to reset both fields to their initial state
604 * (nativeFunc points at dvmResolveNativeMethod, insns holds NULL), but
605 * that creates some unpleasant race conditions. In particular, if another
606 * thread is executing inside the call bridge for the method in question,
607 * and we reset insns to NULL, the VM will crash. (See the comments above
608 * dvmSetNativeFunc() for additional commentary.)
609 *
610 * We can't rely on being able to update two 32-bit fields in one atomic
611 * operation (e.g. no 64-bit atomic ops on ARMv5TE), so we want to change
612 * only one field. It turns out we can simply reset nativeFunc to its
613 * initial state, leaving insns alone, because dvmResolveNativeMethod
614 * ignores "insns" entirely.
615 *
616 * When the method is re-registered, both fields will be updated, but
617 * dvmSetNativeFunc guarantees that "insns" is updated first. This means
618 * we shouldn't be in a situation where we have a "live" call bridge and
619 * a stale implementation pointer.
620 */
621static void unregisterJNINativeMethods(Method* methods, size_t count)
622{
623 while (count != 0) {
624 count--;
625
626 Method* meth = &methods[count];
627 if (!dvmIsNativeMethod(meth))
628 continue;
629 if (dvmIsAbstractMethod(meth)) /* avoid abstract method stubs */
630 continue;
631
632 /*
633 * Strictly speaking this ought to test the function pointer against
634 * the various JNI bridge functions to ensure that we only undo
635 * methods that were registered through JNI. In practice, any
636 * native method with a non-NULL "insns" is a registered JNI method.
637 *
638 * If we inadvertently unregister an internal-native, it'll get
639 * re-resolved on the next call; unregistering an unregistered
640 * JNI method is a no-op. So we don't really need to test for
641 * anything.
642 */
643
644 LOGD("Unregistering JNI method %s.%s:%s\n",
645 meth->clazz->descriptor, meth->name, meth->shorty);
646 dvmSetNativeFunc(meth, dvmResolveNativeMethod, NULL);
647 }
648}
649
650/*
651 * Un-register all JNI native methods from a class.
652 */
653void dvmUnregisterJNINativeMethods(ClassObject* clazz)
654{
655 unregisterJNINativeMethods(clazz->directMethods, clazz->directMethodCount);
656 unregisterJNINativeMethods(clazz->virtualMethods, clazz->virtualMethodCount);
657}
658
659
660/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800661 * ===========================================================================
662 * Signature-based method lookup
663 * ===========================================================================
664 */
665
666/*
667 * Create the pre-mangled form of the class+method string.
668 *
669 * Returns a newly-allocated string, and sets "*pLen" to the length.
670 */
671static char* createJniNameString(const char* classDescriptor,
672 const char* methodName, int* pLen)
673{
674 char* result;
675 size_t descriptorLength = strlen(classDescriptor);
676
677 *pLen = 4 + descriptorLength + strlen(methodName);
678
679 result = malloc(*pLen +1);
680 if (result == NULL)
681 return NULL;
682
683 /*
684 * Add one to classDescriptor to skip the "L", and then replace
685 * the final ";" with a "/" after the sprintf() call.
686 */
687 sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
688 result[5 + (descriptorLength - 2)] = '/';
689
690 return result;
691}
692
693/*
694 * Returns a newly-allocated, mangled copy of "str".
695 *
696 * "str" is a "modified UTF-8" string. We convert it to UTF-16 first to
697 * make life simpler.
698 */
699static char* mangleString(const char* str, int len)
700{
701 u2* utf16 = NULL;
702 char* mangle = NULL;
703 int charLen;
704
705 //LOGI("mangling '%s' %d\n", str, len);
706
707 assert(str[len] == '\0');
708
709 charLen = dvmUtf8Len(str);
710 utf16 = (u2*) malloc(sizeof(u2) * charLen);
711 if (utf16 == NULL)
712 goto bail;
713
714 dvmConvertUtf8ToUtf16(utf16, str);
715
716 /*
717 * Compute the length of the mangled string.
718 */
719 int i, mangleLen = 0;
720
721 for (i = 0; i < charLen; i++) {
722 u2 ch = utf16[i];
723
Brian McKennadfdaa872009-07-19 20:49:26 +1000724 if (ch == '$' || ch > 127) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800725 mangleLen += 6;
726 } else {
727 switch (ch) {
728 case '_':
729 case ';':
730 case '[':
731 mangleLen += 2;
732 break;
733 default:
734 mangleLen++;
735 break;
736 }
737 }
738 }
739
740 char* cp;
741
742 mangle = (char*) malloc(mangleLen +1);
743 if (mangle == NULL)
744 goto bail;
745
746 for (i = 0, cp = mangle; i < charLen; i++) {
747 u2 ch = utf16[i];
748
Brian McKennadfdaa872009-07-19 20:49:26 +1000749 if (ch == '$' || ch > 127) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800750 sprintf(cp, "_0%04x", ch);
751 cp += 6;
752 } else {
753 switch (ch) {
754 case '_':
755 *cp++ = '_';
756 *cp++ = '1';
757 break;
758 case ';':
759 *cp++ = '_';
760 *cp++ = '2';
761 break;
762 case '[':
763 *cp++ = '_';
764 *cp++ = '3';
765 break;
766 case '/':
767 *cp++ = '_';
768 break;
769 default:
770 *cp++ = (char) ch;
771 break;
772 }
773 }
774 }
775
776 *cp = '\0';
777
778bail:
779 free(utf16);
780 return mangle;
781}
782
783/*
784 * Create the mangled form of the parameter types.
785 */
786static char* createMangledSignature(const DexProto* proto)
787{
788 DexStringCache sigCache;
789 const char* interim;
790 char* result;
791
792 dexStringCacheInit(&sigCache);
793 interim = dexProtoGetParameterDescriptors(proto, &sigCache);
794 result = mangleString(interim, strlen(interim));
795 dexStringCacheRelease(&sigCache);
796
797 return result;
798}
799
800/*
801 * (This is a dvmHashForeach callback.)
802 *
803 * Search for a matching method in this shared library.
Andy McFadden70318882009-07-09 17:01:04 -0700804 *
805 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800806 */
807static int findMethodInLib(void* vlib, void* vmethod)
808{
809 const SharedLib* pLib = (const SharedLib*) vlib;
810 const Method* meth = (const Method*) vmethod;
811 char* preMangleCM = NULL;
812 char* mangleCM = NULL;
813 char* mangleSig = NULL;
814 char* mangleCMSig = NULL;
815 void* func = NULL;
816 int len;
817
818 if (meth->clazz->classLoader != pLib->classLoader) {
Andy McFaddendced7942009-11-17 13:13:34 -0800819 LOGV("+++ not scanning '%s' for '%s' (wrong CL)\n",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800820 pLib->pathName, meth->name);
821 return 0;
822 } else
823 LOGV("+++ scanning '%s' for '%s'\n", pLib->pathName, meth->name);
824
825 /*
826 * First, we try it without the signature.
827 */
828 preMangleCM =
829 createJniNameString(meth->clazz->descriptor, meth->name, &len);
830 if (preMangleCM == NULL)
831 goto bail;
832
833 mangleCM = mangleString(preMangleCM, len);
834 if (mangleCM == NULL)
835 goto bail;
836
837 LOGV("+++ calling dlsym(%s)\n", mangleCM);
838 func = dlsym(pLib->handle, mangleCM);
839 if (func == NULL) {
840 mangleSig =
841 createMangledSignature(&meth->prototype);
842 if (mangleSig == NULL)
843 goto bail;
844
845 mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
846 if (mangleCMSig == NULL)
847 goto bail;
848
849 sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
850
851 LOGV("+++ calling dlsym(%s)\n", mangleCMSig);
852 func = dlsym(pLib->handle, mangleCMSig);
853 if (func != NULL) {
854 LOGV("Found '%s' with dlsym\n", mangleCMSig);
855 }
856 } else {
857 LOGV("Found '%s' with dlsym\n", mangleCM);
858 }
859
860bail:
861 free(preMangleCM);
862 free(mangleCM);
863 free(mangleSig);
864 free(mangleCMSig);
865 return (int) func;
866}
867
868/*
869 * See if the requested method lives in any of the currently-loaded
870 * shared libraries. We do this by checking each of them for the expected
871 * method signature.
872 */
873static void* lookupSharedLibMethod(const Method* method)
874{
875 if (gDvm.nativeLibs == NULL) {
876 LOGE("Unexpected init state: nativeLibs not ready\n");
877 dvmAbort();
878 }
879 return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,
880 (void*) method);
881}
Elliott Hughes8afa9df2010-07-07 14:47:25 -0700882
883
884static void appendValue(char type, const JValue value, char* buf, size_t n,
885 bool appendComma)
886{
887 size_t len = strlen(buf);
888 if (len >= n - 32) { // 32 should be longer than anything we could append.
889 buf[len - 1] = '.';
890 buf[len - 2] = '.';
891 buf[len - 3] = '.';
892 return;
893 }
894 char* p = buf + len;
895 switch (type) {
896 case 'B':
897 if (value.b >= 0 && value.b < 10) {
898 sprintf(p, "%d", value.b);
899 } else {
900 sprintf(p, "0x%x (%d)", value.b, value.b);
901 }
902 break;
903 case 'C':
904 if (value.c < 0x7f && value.c >= ' ') {
905 sprintf(p, "U+%x ('%c')", value.c, value.c);
906 } else {
907 sprintf(p, "U+%x", value.c);
908 }
909 break;
910 case 'D':
911 sprintf(p, "%g", value.d);
912 break;
913 case 'F':
914 sprintf(p, "%g", value.f);
915 break;
916 case 'I':
917 sprintf(p, "%d", value.i);
918 break;
919 case 'L':
920 sprintf(p, "0x%x", value.i);
921 break;
922 case 'J':
923 sprintf(p, "%lld", value.j);
924 break;
925 case 'S':
926 sprintf(p, "%d", value.s);
927 break;
928 case 'V':
929 strcpy(p, "void");
930 break;
931 case 'Z':
932 strcpy(p, value.z ? "true" : "false");
933 break;
934 default:
935 sprintf(p, "unknown type '%c'", type);
936 break;
937 }
938
939 if (appendComma) {
940 strcat(p, ", ");
941 }
942}
943
944#define LOGI_NATIVE(...) LOG(LOG_INFO, LOG_TAG "-native", __VA_ARGS__)
945
Elliott Hughesde66fcb2010-07-30 13:34:49 -0700946void dvmLogNativeMethodEntry(const Method* method, const u4* args)
Elliott Hughes8afa9df2010-07-07 14:47:25 -0700947{
948 char thisString[32] = { 0 };
Elliott Hughesde66fcb2010-07-30 13:34:49 -0700949 const u4* sp = args; // &args[method->registersSize - method->insSize];
Elliott Hughes8afa9df2010-07-07 14:47:25 -0700950 if (!dvmIsStaticMethod(method)) {
951 sprintf(thisString, "this=0x%08x ", *sp++);
952 }
953
954 char argsString[128]= { 0 };
955 const char* desc = &method->shorty[1];
956 while (*desc != '\0') {
957 char argType = *desc++;
958 JValue value;
959 if (argType == 'D' || argType == 'J') {
960 value.j = dvmGetArgLong(sp, 0);
961 sp += 2;
962 } else {
963 value.i = *sp++;
964 }
965 appendValue(argType, value, argsString, sizeof(argsString),
966 *desc != '\0');
967 }
968
969 char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
970 LOGI_NATIVE("-> %s.%s%s %s(%s)", method->clazz->descriptor, method->name,
971 signature, thisString, argsString);
972 free(signature);
973}
974
975void dvmLogNativeMethodExit(const Method* method, Thread* self,
976 const JValue returnValue)
977{
978 char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
979 if (dvmCheckException(self)) {
980 Object* exception = dvmGetException(self);
981 LOGI_NATIVE("<- %s.%s%s threw %s", method->clazz->descriptor,
982 method->name, signature, exception->clazz->descriptor);
983 } else {
984 char returnValueString[128] = { 0 };
985 char returnType = method->shorty[0];
986 appendValue(returnType, returnValue,
987 returnValueString, sizeof(returnValueString), false);
988 LOGI_NATIVE("<- %s.%s%s returned %s", method->clazz->descriptor,
989 method->name, signature, returnValueString);
990 }
991 free(signature);
992}