blob: be719a7f0c69dc025f25b7956bf1599bb6be343d [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 */
Carl Shapiro1e1433e2011-04-20 16:51:38 -070036bool dvmNativeStartup()
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080037{
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 */
Carl Shapiro1e1433e2011-04-20 16:51:38 -070048void dvmNativeShutdown()
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080049{
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;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080074
75 /*
76 * If this is a static method, it could be called before the class
77 * has been initialized.
78 */
79 if (dvmIsStaticMethod(method)) {
80 if (!dvmIsClassInitialized(clazz) && !dvmInitClass(clazz)) {
81 assert(dvmCheckException(dvmThreadSelf()));
82 return;
83 }
84 } else {
85 assert(dvmIsClassInitialized(clazz) ||
86 dvmIsClassInitializing(clazz));
87 }
88
89 /* start with our internal-native methods */
Carl Shapirod5c36b92011-04-15 18:38:06 -070090 DalvikNativeFunc infunc = dvmLookupInternalNativeMethod(method);
91 if (infunc != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080092 /* resolution always gets the same answer, so no race here */
93 IF_LOGVV() {
94 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
Dan Bornstein60fc8062011-05-26 10:11:58 -070095 LOGVV("+++ resolved native %s.%s %s, invoking",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080096 clazz->descriptor, method->name, desc);
97 free(desc);
98 }
99 if (dvmIsSynchronizedMethod(method)) {
Steve Blockc1a4ab92012-01-06 19:16:58 +0000100 ALOGE("ERROR: internal-native can't be declared 'synchronized'");
101 ALOGE("Failing on %s.%s", method->clazz->descriptor, method->name);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800102 dvmAbort(); // harsh, but this is VM-internal problem
103 }
Carl Shapirod5c36b92011-04-15 18:38:06 -0700104 DalvikBridgeFunc dfunc = (DalvikBridgeFunc) infunc;
Andy McFadden1e83b4d2010-07-15 17:20:24 -0700105 dvmSetNativeFunc((Method*) method, dfunc, NULL);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800106 dfunc(args, pResult, method, self);
107 return;
108 }
109
110 /* now scan any DLLs we have loaded for JNI signatures */
Carl Shapirod5c36b92011-04-15 18:38:06 -0700111 void* func = lookupSharedLibMethod(method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800112 if (func != NULL) {
Andy McFadden59b61772009-05-13 16:44:34 -0700113 /* found it, point it at the JNI bridge and then call it */
114 dvmUseJNIBridge((Method*) method, func);
Andy McFadden0083d372009-08-21 14:44:04 -0700115 (*method->nativeFunc)(args, pResult, method, self);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800116 return;
117 }
118
Steve Blocke8e1ddc2012-01-05 23:21:27 +0000119 IF_ALOGW() {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800120 char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
Andy McFadden5cc74502012-01-20 14:05:24 -0800121 ALOGW("No implementation found for native %s.%s:%s",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800122 clazz->descriptor, method->name, desc);
123 free(desc);
124 }
125
Andy McFadden5cc74502012-01-20 14:05:24 -0800126 dvmThrowUnsatisfiedLinkError("Native method not found", method);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800127}
128
129
130/*
131 * ===========================================================================
132 * Native shared library support
133 * ===========================================================================
134 */
135
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.)
139
Carl Shapirod862faa2011-04-27 23:00:01 -0700140enum OnLoadState {
Andy McFadden70318882009-07-09 17:01:04 -0700141 kOnLoadPending = 0, /* initial state, must be zero */
142 kOnLoadFailed,
143 kOnLoadOkay,
Carl Shapirod862faa2011-04-27 23:00:01 -0700144};
Andy McFadden70318882009-07-09 17:01:04 -0700145
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800146/*
147 * We add one of these to the hash table for every library we load. The
148 * hash is on the "pathName" field.
149 */
Carl Shapirod862faa2011-04-27 23:00:01 -0700150struct SharedLib {
Andy McFadden70318882009-07-09 17:01:04 -0700151 char* pathName; /* absolute path to library */
152 void* handle; /* from dlopen */
153 Object* classLoader; /* ClassLoader we are associated with */
154
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 */
Carl Shapirod862faa2011-04-27 23:00:01 -0700159};
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800160
161/*
162 * (This is a dvmHashTableLookup callback.)
163 *
164 * Find an entry that matches the string.
165 */
166static int hashcmpNameStr(const void* ventry, const void* vname)
167{
168 const SharedLib* pLib = (const SharedLib*) ventry;
169 const char* name = (const char*) vname;
170
171 return strcmp(pLib->pathName, name);
172}
173
174/*
175 * (This is a dvmHashTableLookup callback.)
176 *
177 * Find an entry that matches the new entry.
Andy McFadden70318882009-07-09 17:01:04 -0700178 *
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.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800181 */
182static int hashcmpSharedLib(const void* ventry, const void* vnewEntry)
183{
184 const SharedLib* pLib = (const SharedLib*) ventry;
185 const SharedLib* pNewLib = (const SharedLib*) vnewEntry;
186
Steve Block062bf502011-12-20 16:22:13 +0000187 ALOGD("--- comparing %p '%s' %p '%s'",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800188 pLib, pLib->pathName, pNewLib, pNewLib->pathName);
189 return strcmp(pLib->pathName, pNewLib->pathName);
190}
191
192/*
193 * Check to see if an entry with the same pathname already exists.
194 */
Andy McFadden70318882009-07-09 17:01:04 -0700195static SharedLib* findSharedLibEntry(const char* pathName)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800196{
197 u4 hash = dvmComputeUtf8Hash(pathName);
198 void* ent;
199
200 ent = dvmHashTableLookup(gDvm.nativeLibs, hash, (void*)pathName,
201 hashcmpNameStr, false);
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800202 return (SharedLib*)ent;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800203}
204
205/*
206 * Add the new entry to the table.
207 *
Andy McFadden70318882009-07-09 17:01:04 -0700208 * Returns the table entry, which will not be the same as "pLib" if the
209 * entry already exists.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800210 */
Andy McFadden70318882009-07-09 17:01:04 -0700211static SharedLib* addSharedLibEntry(SharedLib* pLib)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800212{
213 u4 hash = dvmComputeUtf8Hash(pLib->pathName);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800214
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 */
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800220 return (SharedLib*)dvmHashTableLookup(gDvm.nativeLibs, hash, pLib,
221 hashcmpSharedLib, true);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800222}
223
224/*
225 * Free up an entry. (This is a dvmHashTableFree callback.)
226 */
227static 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 */
248char* 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
Andy McFadden70318882009-07-09 17:01:04 -0700260/*
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.
263 */
264static bool checkOnLoadResult(SharedLib* pEntry)
265{
266 Thread* self = dvmThreadSelf();
267 if (pEntry->onLoadThreadId == self->threadId) {
268 /*
269 * Check this so we don't end up waiting for ourselves. We need
270 * to return "true" so the caller can continue.
271 */
Steve Block43084172012-01-04 20:04:51 +0000272 ALOGI("threadid=%d: recursive native library load attempt (%s)",
Andy McFadden70318882009-07-09 17:01:04 -0700273 self->threadId, pEntry->pathName);
274 return true;
275 }
276
Steve Block92c1f6f2011-10-20 11:55:54 +0100277 ALOGV("+++ retrieving %s OnLoad status", pEntry->pathName);
Andy McFadden70318882009-07-09 17:01:04 -0700278 bool result;
279
280 dvmLockMutex(&pEntry->onLoadLock);
281 while (pEntry->onLoadResult == kOnLoadPending) {
Steve Block062bf502011-12-20 16:22:13 +0000282 ALOGD("threadid=%d: waiting for %s OnLoad status",
Andy McFadden70318882009-07-09 17:01:04 -0700283 self->threadId, pEntry->pathName);
Carl Shapiro5617ad32010-07-02 10:50:57 -0700284 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
Andy McFadden70318882009-07-09 17:01:04 -0700285 pthread_cond_wait(&pEntry->onLoadCond, &pEntry->onLoadLock);
286 dvmChangeStatus(self, oldStatus);
287 }
288 if (pEntry->onLoadResult == kOnLoadOkay) {
Steve Block92c1f6f2011-10-20 11:55:54 +0100289 ALOGV("+++ earlier OnLoad(%s) okay", pEntry->pathName);
Andy McFadden70318882009-07-09 17:01:04 -0700290 result = true;
291 } else {
Steve Block92c1f6f2011-10-20 11:55:54 +0100292 ALOGV("+++ earlier OnLoad(%s) failed", pEntry->pathName);
Andy McFadden70318882009-07-09 17:01:04 -0700293 result = false;
294 }
295 dvmUnlockMutex(&pEntry->onLoadLock);
296 return result;
297}
298
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800299typedef int (*OnLoadFunc)(JavaVM*, void*);
300
301/*
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.
305 *
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.
310 *
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.
313 *
Elliott Hughesf584b4a2010-09-30 15:51:31 -0700314 * 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.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800317 */
Elliott Hughesf584b4a2010-09-30 15:51:31 -0700318bool dvmLoadNativeCode(const char* pathName, Object* classLoader,
319 char** detail)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800320{
Andy McFadden70318882009-07-09 17:01:04 -0700321 SharedLib* pEntry;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800322 void* handle;
Andy McFaddendced7942009-11-17 13:13:34 -0800323 bool verbose;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800324
Andy McFaddendced7942009-11-17 13:13:34 -0800325 /* reduce noise by not chattering about system libraries */
Dima Zavinb14f4052010-09-23 22:38:45 -0700326 verbose = !!strncmp(pathName, "/system", sizeof("/system")-1);
327 verbose = verbose && !!strncmp(pathName, "/vendor", sizeof("/vendor")-1);
Andy McFaddendced7942009-11-17 13:13:34 -0800328
329 if (verbose)
Steve Block062bf502011-12-20 16:22:13 +0000330 ALOGD("Trying to load lib %s %p", pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800331
Elliott Hughesf584b4a2010-09-30 15:51:31 -0700332 *detail = NULL;
333
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800334 /*
335 * See if we've already loaded it. If we have, and the class loader
336 * matches, return successfully without doing anything.
337 */
338 pEntry = findSharedLibEntry(pathName);
339 if (pEntry != NULL) {
340 if (pEntry->classLoader != classLoader) {
Steve Blocke8e1ddc2012-01-05 23:21:27 +0000341 ALOGW("Shared lib '%s' already opened by CL %p; can't open in %p",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800342 pathName, pEntry->classLoader, classLoader);
343 return false;
344 }
Andy McFaddendced7942009-11-17 13:13:34 -0800345 if (verbose) {
Steve Block062bf502011-12-20 16:22:13 +0000346 ALOGD("Shared lib '%s' already loaded in same CL %p",
Andy McFaddendced7942009-11-17 13:13:34 -0800347 pathName, classLoader);
348 }
Andy McFadden70318882009-07-09 17:01:04 -0700349 if (!checkOnLoadResult(pEntry))
350 return false;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800351 return true;
352 }
353
354 /*
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.)
358 *
The Android Open Source Project99409882009-03-18 22:20:24 -0700359 * Failures here are expected when java.library.path has several entries
360 * and we have to hunt for the lib.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800361 *
Andy McFaddendced7942009-11-17 13:13:34 -0800362 * The current version of the dynamic linker prints detailed information
363 * about dlopen() failures. Some things to check if the message is
364 * cryptic:
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800365 * - 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)
The Android Open Source Project99409882009-03-18 22:20:24 -0700368 * - check to see if the library is valid (e.g. not zero bytes long)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800369 * - check config/prelink-linux-arm.map to ensure that the library
370 * is listed and is not being overrun by the previous entry (if
The Android Open Source Project99409882009-03-18 22:20:24 -0700371 * 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
Andy McFadden2aa43612009-06-17 16:29:30 -0700376 *
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.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800380 */
Andy McFadden2aa43612009-06-17 16:29:30 -0700381 Thread* self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -0700382 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800383 handle = dlopen(pathName, RTLD_LAZY);
Andy McFadden2aa43612009-06-17 16:29:30 -0700384 dvmChangeStatus(self, oldStatus);
385
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800386 if (handle == NULL) {
Elliott Hughesf584b4a2010-09-30 15:51:31 -0700387 *detail = strdup(dlerror());
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800388 return false;
389 }
390
Andy McFadden70318882009-07-09 17:01:04 -0700391 /* create a new entry */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800392 SharedLib* pNewEntry;
Andy McFadden70318882009-07-09 17:01:04 -0700393 pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800394 pNewEntry->pathName = strdup(pathName);
395 pNewEntry->handle = handle;
396 pNewEntry->classLoader = classLoader;
Andy McFadden70318882009-07-09 17:01:04 -0700397 dvmInitMutex(&pNewEntry->onLoadLock);
398 pthread_cond_init(&pNewEntry->onLoadCond, NULL);
399 pNewEntry->onLoadThreadId = self->threadId;
400
401 /* try to add it to the list */
402 SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
403
404 if (pNewEntry != pActualEntry) {
Steve Block43084172012-01-04 20:04:51 +0000405 ALOGI("WOW: we lost a race to add a shared lib (%s CL=%p)",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800406 pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800407 freeSharedLibEntry(pNewEntry);
Andy McFadden70318882009-07-09 17:01:04 -0700408 return checkOnLoadResult(pActualEntry);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800409 } else {
Andy McFaddendced7942009-11-17 13:13:34 -0800410 if (verbose)
Steve Block062bf502011-12-20 16:22:13 +0000411 ALOGD("Added shared lib %s %p", pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800412
Andy McFadden70318882009-07-09 17:01:04 -0700413 bool result = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800414 void* vonLoad;
415 int version;
416
417 vonLoad = dlsym(handle, "JNI_OnLoad");
418 if (vonLoad == NULL) {
Steve Block062bf502011-12-20 16:22:13 +0000419 ALOGD("No JNI_OnLoad found in %s %p, skipping init",
Andy McFaddendced7942009-11-17 13:13:34 -0800420 pathName, classLoader);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800421 } else {
422 /*
423 * Call JNI_OnLoad. We have to override the current class
424 * loader, which will always be "null" since the stuff at the
Andy McFadden70318882009-07-09 17:01:04 -0700425 * top of the stack is around Runtime.loadLibrary(). (See
426 * the comments in the JNI FindClass function.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800427 */
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800428 OnLoadFunc func = (OnLoadFunc)vonLoad;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800429 Object* prevOverride = self->classLoaderOverride;
430
431 self->classLoaderOverride = classLoader;
Andy McFadden2aa43612009-06-17 16:29:30 -0700432 oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
Elliott Hughes5719d5c2011-06-22 13:24:06 -0700433 if (gDvm.verboseJni) {
Steve Block43084172012-01-04 20:04:51 +0000434 ALOGI("[Calling JNI_OnLoad for \"%s\"]", pathName);
Elliott Hughes5719d5c2011-06-22 13:24:06 -0700435 }
Elliott Hughesd5c80e02011-04-27 12:23:43 -0700436 version = (*func)(gDvmJni.jniVm, NULL);
Andy McFadden2aa43612009-06-17 16:29:30 -0700437 dvmChangeStatus(self, oldStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800438 self->classLoaderOverride = prevOverride;
439
440 if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
441 version != JNI_VERSION_1_6)
442 {
Steve Blocke8e1ddc2012-01-05 23:21:27 +0000443 ALOGW("JNI_OnLoad returned bad version (%d) in %s %p",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800444 version, pathName, classLoader);
Andy McFadden70318882009-07-09 17:01:04 -0700445 /*
446 * It's unwise to call dlclose() here, but we can mark it
447 * as bad and ensure that future load attempts will fail.
448 *
449 * We don't know how far JNI_OnLoad got, so there could
450 * be some partially-initialized stuff accessible through
451 * newly-registered native method calls. We could try to
452 * unregister them, but that doesn't seem worthwhile.
453 */
454 result = false;
455 } else {
Elliott Hughes5719d5c2011-06-22 13:24:06 -0700456 if (gDvm.verboseJni) {
Steve Block43084172012-01-04 20:04:51 +0000457 ALOGI("[Returned from JNI_OnLoad for \"%s\"]", pathName);
Elliott Hughes5719d5c2011-06-22 13:24:06 -0700458 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800459 }
460 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800461
Andy McFadden70318882009-07-09 17:01:04 -0700462 if (result)
463 pNewEntry->onLoadResult = kOnLoadOkay;
464 else
465 pNewEntry->onLoadResult = kOnLoadFailed;
466
467 pNewEntry->onLoadThreadId = 0;
468
469 /*
470 * Broadcast a wakeup to anybody sleeping on the condition variable.
471 */
472 dvmLockMutex(&pNewEntry->onLoadLock);
473 pthread_cond_broadcast(&pNewEntry->onLoadCond);
474 dvmUnlockMutex(&pNewEntry->onLoadLock);
475 return result;
476 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800477}
478
479
480/*
Andy McFadden1e83b4d2010-07-15 17:20:24 -0700481 * Un-register JNI native methods.
482 *
483 * There are two relevant fields in struct Method, "nativeFunc" and
484 * "insns". The former holds a function pointer to a "bridge" function
485 * (or, for internal native, the actual implementation). The latter holds
486 * a pointer to the actual JNI method.
487 *
488 * The obvious approach is to reset both fields to their initial state
489 * (nativeFunc points at dvmResolveNativeMethod, insns holds NULL), but
490 * that creates some unpleasant race conditions. In particular, if another
491 * thread is executing inside the call bridge for the method in question,
492 * and we reset insns to NULL, the VM will crash. (See the comments above
493 * dvmSetNativeFunc() for additional commentary.)
494 *
495 * We can't rely on being able to update two 32-bit fields in one atomic
496 * operation (e.g. no 64-bit atomic ops on ARMv5TE), so we want to change
497 * only one field. It turns out we can simply reset nativeFunc to its
498 * initial state, leaving insns alone, because dvmResolveNativeMethod
499 * ignores "insns" entirely.
500 *
501 * When the method is re-registered, both fields will be updated, but
502 * dvmSetNativeFunc guarantees that "insns" is updated first. This means
503 * we shouldn't be in a situation where we have a "live" call bridge and
504 * a stale implementation pointer.
505 */
506static void unregisterJNINativeMethods(Method* methods, size_t count)
507{
508 while (count != 0) {
509 count--;
510
511 Method* meth = &methods[count];
512 if (!dvmIsNativeMethod(meth))
513 continue;
514 if (dvmIsAbstractMethod(meth)) /* avoid abstract method stubs */
515 continue;
516
517 /*
518 * Strictly speaking this ought to test the function pointer against
519 * the various JNI bridge functions to ensure that we only undo
520 * methods that were registered through JNI. In practice, any
521 * native method with a non-NULL "insns" is a registered JNI method.
522 *
523 * If we inadvertently unregister an internal-native, it'll get
524 * re-resolved on the next call; unregistering an unregistered
525 * JNI method is a no-op. So we don't really need to test for
526 * anything.
527 */
528
Steve Block062bf502011-12-20 16:22:13 +0000529 ALOGD("Unregistering JNI method %s.%s:%s",
Andy McFadden1e83b4d2010-07-15 17:20:24 -0700530 meth->clazz->descriptor, meth->name, meth->shorty);
531 dvmSetNativeFunc(meth, dvmResolveNativeMethod, NULL);
532 }
533}
534
535/*
536 * Un-register all JNI native methods from a class.
537 */
538void dvmUnregisterJNINativeMethods(ClassObject* clazz)
539{
540 unregisterJNINativeMethods(clazz->directMethods, clazz->directMethodCount);
541 unregisterJNINativeMethods(clazz->virtualMethods, clazz->virtualMethodCount);
542}
543
544
545/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800546 * ===========================================================================
547 * Signature-based method lookup
548 * ===========================================================================
549 */
550
551/*
552 * Create the pre-mangled form of the class+method string.
553 *
554 * Returns a newly-allocated string, and sets "*pLen" to the length.
555 */
556static char* createJniNameString(const char* classDescriptor,
557 const char* methodName, int* pLen)
558{
559 char* result;
560 size_t descriptorLength = strlen(classDescriptor);
561
562 *pLen = 4 + descriptorLength + strlen(methodName);
563
Carl Shapirofc75f3e2010-12-07 11:43:38 -0800564 result = (char*)malloc(*pLen +1);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800565 if (result == NULL)
566 return NULL;
567
568 /*
569 * Add one to classDescriptor to skip the "L", and then replace
570 * the final ";" with a "/" after the sprintf() call.
571 */
572 sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
573 result[5 + (descriptorLength - 2)] = '/';
574
575 return result;
576}
577
578/*
579 * Returns a newly-allocated, mangled copy of "str".
580 *
581 * "str" is a "modified UTF-8" string. We convert it to UTF-16 first to
582 * make life simpler.
583 */
584static char* mangleString(const char* str, int len)
585{
Steve Block43084172012-01-04 20:04:51 +0000586 //ALOGI("mangling '%s' %d", str, len);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800587
588 assert(str[len] == '\0');
589
Carl Shapirod5c36b92011-04-15 18:38:06 -0700590 size_t charLen = dvmUtf8Len(str);
591 u2* utf16 = (u2*) malloc(sizeof(u2) * charLen);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800592 if (utf16 == NULL)
Carl Shapirod5c36b92011-04-15 18:38:06 -0700593 return NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800594
595 dvmConvertUtf8ToUtf16(utf16, str);
596
597 /*
598 * Compute the length of the mangled string.
599 */
Carl Shapirod5c36b92011-04-15 18:38:06 -0700600 size_t mangleLen = 0;
601 for (size_t i = 0; i < charLen; i++) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800602 u2 ch = utf16[i];
603
Brian McKennadfdaa872009-07-19 20:49:26 +1000604 if (ch == '$' || ch > 127) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800605 mangleLen += 6;
606 } else {
607 switch (ch) {
608 case '_':
609 case ';':
610 case '[':
611 mangleLen += 2;
612 break;
613 default:
614 mangleLen++;
615 break;
616 }
617 }
618 }
619
Carl Shapirod5c36b92011-04-15 18:38:06 -0700620 char* mangle = (char*) malloc(mangleLen +1);
621 if (mangle == NULL) {
622 free(utf16);
623 return NULL;
624 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800625
Carl Shapirod5c36b92011-04-15 18:38:06 -0700626 char* cp = mangle;
627 for (size_t i = 0; i < charLen; i++) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800628 u2 ch = utf16[i];
629
Brian McKennadfdaa872009-07-19 20:49:26 +1000630 if (ch == '$' || ch > 127) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800631 sprintf(cp, "_0%04x", ch);
632 cp += 6;
633 } else {
634 switch (ch) {
635 case '_':
636 *cp++ = '_';
637 *cp++ = '1';
638 break;
639 case ';':
640 *cp++ = '_';
641 *cp++ = '2';
642 break;
643 case '[':
644 *cp++ = '_';
645 *cp++ = '3';
646 break;
647 case '/':
648 *cp++ = '_';
649 break;
650 default:
651 *cp++ = (char) ch;
652 break;
653 }
654 }
655 }
656
657 *cp = '\0';
658
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800659 free(utf16);
660 return mangle;
661}
662
663/*
664 * Create the mangled form of the parameter types.
665 */
666static char* createMangledSignature(const DexProto* proto)
667{
668 DexStringCache sigCache;
669 const char* interim;
670 char* result;
671
672 dexStringCacheInit(&sigCache);
673 interim = dexProtoGetParameterDescriptors(proto, &sigCache);
674 result = mangleString(interim, strlen(interim));
675 dexStringCacheRelease(&sigCache);
676
677 return result;
678}
679
680/*
681 * (This is a dvmHashForeach callback.)
682 *
683 * Search for a matching method in this shared library.
Andy McFadden70318882009-07-09 17:01:04 -0700684 *
685 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800686 */
687static int findMethodInLib(void* vlib, void* vmethod)
688{
689 const SharedLib* pLib = (const SharedLib*) vlib;
690 const Method* meth = (const Method*) vmethod;
691 char* preMangleCM = NULL;
692 char* mangleCM = NULL;
693 char* mangleSig = NULL;
694 char* mangleCMSig = NULL;
695 void* func = NULL;
696 int len;
697
698 if (meth->clazz->classLoader != pLib->classLoader) {
Steve Block92c1f6f2011-10-20 11:55:54 +0100699 ALOGV("+++ not scanning '%s' for '%s' (wrong CL)",
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800700 pLib->pathName, meth->name);
701 return 0;
702 } else
Steve Block92c1f6f2011-10-20 11:55:54 +0100703 ALOGV("+++ scanning '%s' for '%s'", pLib->pathName, meth->name);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800704
705 /*
706 * First, we try it without the signature.
707 */
708 preMangleCM =
709 createJniNameString(meth->clazz->descriptor, meth->name, &len);
710 if (preMangleCM == NULL)
711 goto bail;
712
713 mangleCM = mangleString(preMangleCM, len);
714 if (mangleCM == NULL)
715 goto bail;
716
Steve Block92c1f6f2011-10-20 11:55:54 +0100717 ALOGV("+++ calling dlsym(%s)", mangleCM);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800718 func = dlsym(pLib->handle, mangleCM);
719 if (func == NULL) {
720 mangleSig =
721 createMangledSignature(&meth->prototype);
722 if (mangleSig == NULL)
723 goto bail;
724
725 mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
726 if (mangleCMSig == NULL)
727 goto bail;
728
729 sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
730
Steve Block92c1f6f2011-10-20 11:55:54 +0100731 ALOGV("+++ calling dlsym(%s)", mangleCMSig);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800732 func = dlsym(pLib->handle, mangleCMSig);
733 if (func != NULL) {
Steve Block92c1f6f2011-10-20 11:55:54 +0100734 ALOGV("Found '%s' with dlsym", mangleCMSig);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800735 }
736 } else {
Steve Block92c1f6f2011-10-20 11:55:54 +0100737 ALOGV("Found '%s' with dlsym", mangleCM);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800738 }
739
740bail:
741 free(preMangleCM);
742 free(mangleCM);
743 free(mangleSig);
744 free(mangleCMSig);
745 return (int) func;
746}
747
748/*
749 * See if the requested method lives in any of the currently-loaded
750 * shared libraries. We do this by checking each of them for the expected
751 * method signature.
752 */
753static void* lookupSharedLibMethod(const Method* method)
754{
755 if (gDvm.nativeLibs == NULL) {
Steve Blockc1a4ab92012-01-06 19:16:58 +0000756 ALOGE("Unexpected init state: nativeLibs not ready");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800757 dvmAbort();
758 }
759 return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,
760 (void*) method);
761}