1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
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 unless the method is unregistered.
61 *
62 * Initializes method's class if necessary.
63 *
64 * An exception is thrown on resolution failure.
65 *
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.)
69 */
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*) method, dfunc, NULL);
107        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) {
114        /* found it, point it at the JNI bridge and then call it */
115        dvmUseJNIBridge((Method*) method, func);
116        (*method->nativeFunc)(args, pResult, method, self);
117        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
141typedef enum OnLoadState {
142    kOnLoadPending = 0,     /* initial state, must be zero */
143    kOnLoadFailed,
144    kOnLoadOkay,
145} OnLoadState;
146
147/*
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 {
152    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 */
160} 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.
179 *
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.
182 */
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 */
196static SharedLib* findSharedLibEntry(const char* pathName)
197{
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 *
209 * Returns the table entry, which will not be the same as "pLib" if the
210 * entry already exists.
211 */
212static SharedLib* addSharedLibEntry(SharedLib* pLib)
213{
214    u4 hash = dvmComputeUtf8Hash(pLib->pathName);
215
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     */
221    return dvmHashTableLookup(gDvm.nativeLibs, hash, pLib, hashcmpSharedLib,
222                true);
223}
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 * Check the result of an earlier call to JNI_OnLoad on this library.  If
263 * the call has not yet finished in another thread, wait for it.
264 */
265static bool checkOnLoadResult(SharedLib* pEntry)
266{
267    Thread* self = dvmThreadSelf();
268    if (pEntry->onLoadThreadId == self->threadId) {
269        /*
270         * Check this so we don't end up waiting for ourselves.  We need
271         * to return "true" so the caller can continue.
272         */
273        LOGI("threadid=%d: recursive native library load attempt (%s)\n",
274            self->threadId, pEntry->pathName);
275        return true;
276    }
277
278    LOGV("+++ retrieving %s OnLoad status\n", pEntry->pathName);
279    bool result;
280
281    dvmLockMutex(&pEntry->onLoadLock);
282    while (pEntry->onLoadResult == kOnLoadPending) {
283        LOGD("threadid=%d: waiting for %s OnLoad status\n",
284            self->threadId, pEntry->pathName);
285        ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
286        pthread_cond_wait(&pEntry->onLoadCond, &pEntry->onLoadLock);
287        dvmChangeStatus(self, oldStatus);
288    }
289    if (pEntry->onLoadResult == kOnLoadOkay) {
290        LOGV("+++ earlier OnLoad(%s) okay\n", pEntry->pathName);
291        result = true;
292    } else {
293        LOGV("+++ earlier OnLoad(%s) failed\n", pEntry->pathName);
294        result = false;
295    }
296    dvmUnlockMutex(&pEntry->onLoadLock);
297    return result;
298}
299
300typedef int (*OnLoadFunc)(JavaVM*, void*);
301
302/*
303 * Load native code from the specified absolute pathname.  Per the spec,
304 * if we've already loaded a library with the specified pathname, we
305 * return without doing anything.
306 *
307 * TODO? for better results we should absolutify the pathname.  For fully
308 * correct results we should stat to get the inode and compare that.  The
309 * existing implementation is fine so long as everybody is using
310 * System.loadLibrary.
311 *
312 * The library will be associated with the specified class loader.  The JNI
313 * spec says we can't load the same library into more than one class loader.
314 *
315 * Returns "true" on success. On failure, sets *detail to a
316 * human-readable description of the error or NULL if no detail is
317 * available; ownership of the string is transferred to the caller.
318 */
319bool dvmLoadNativeCode(const char* pathName, Object* classLoader,
320        char** detail)
321{
322    SharedLib* pEntry;
323    void* handle;
324    bool verbose;
325
326    /* reduce noise by not chattering about system libraries */
327    verbose = !!strncmp(pathName, "/system", sizeof("/system")-1);
328    verbose = verbose && !!strncmp(pathName, "/vendor", sizeof("/vendor")-1);
329
330    if (verbose)
331        LOGD("Trying to load lib %s %p\n", pathName, classLoader);
332
333    *detail = NULL;
334
335    /*
336     * See if we've already loaded it.  If we have, and the class loader
337     * matches, return successfully without doing anything.
338     */
339    pEntry = findSharedLibEntry(pathName);
340    if (pEntry != NULL) {
341        if (pEntry->classLoader != classLoader) {
342            LOGW("Shared lib '%s' already opened by CL %p; can't open in %p\n",
343                pathName, pEntry->classLoader, classLoader);
344            return false;
345        }
346        if (verbose) {
347            LOGD("Shared lib '%s' already loaded in same CL %p\n",
348                pathName, classLoader);
349        }
350        if (!checkOnLoadResult(pEntry))
351            return false;
352        return true;
353    }
354
355    /*
356     * Open the shared library.  Because we're using a full path, the system
357     * doesn't have to search through LD_LIBRARY_PATH.  (It may do so to
358     * resolve this library's dependencies though.)
359     *
360     * Failures here are expected when java.library.path has several entries
361     * and we have to hunt for the lib.
362     *
363     * The current version of the dynamic linker prints detailed information
364     * about dlopen() failures.  Some things to check if the message is
365     * cryptic:
366     *   - make sure the library exists on the device
367     *   - verify that the right path is being opened (the debug log message
368     *     above can help with that)
369     *   - check to see if the library is valid (e.g. not zero bytes long)
370     *   - check config/prelink-linux-arm.map to ensure that the library
371     *     is listed and is not being overrun by the previous entry (if
372     *     loading suddenly stops working on a prelinked library, this is
373     *     a good one to check)
374     *   - write a trivial app that calls sleep() then dlopen(), attach
375     *     to it with "strace -p <pid>" while it sleeps, and watch for
376     *     attempts to open nonexistent dependent shared libs
377     *
378     * This can execute slowly for a large library on a busy system, so we
379     * want to switch from RUNNING to VMWAIT while it executes.  This allows
380     * the GC to ignore us.
381     */
382    Thread* self = dvmThreadSelf();
383    ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
384    handle = dlopen(pathName, RTLD_LAZY);
385    dvmChangeStatus(self, oldStatus);
386
387    if (handle == NULL) {
388        *detail = strdup(dlerror());
389        return false;
390    }
391
392    /* create a new entry */
393    SharedLib* pNewEntry;
394    pNewEntry = (SharedLib*) calloc(1, sizeof(SharedLib));
395    pNewEntry->pathName = strdup(pathName);
396    pNewEntry->handle = handle;
397    pNewEntry->classLoader = classLoader;
398    dvmInitMutex(&pNewEntry->onLoadLock);
399    pthread_cond_init(&pNewEntry->onLoadCond, NULL);
400    pNewEntry->onLoadThreadId = self->threadId;
401
402    /* try to add it to the list */
403    SharedLib* pActualEntry = addSharedLibEntry(pNewEntry);
404
405    if (pNewEntry != pActualEntry) {
406        LOGI("WOW: we lost a race to add a shared lib (%s CL=%p)\n",
407            pathName, classLoader);
408        freeSharedLibEntry(pNewEntry);
409        return checkOnLoadResult(pActualEntry);
410    } else {
411        if (verbose)
412            LOGD("Added shared lib %s %p\n", pathName, classLoader);
413
414        bool result = true;
415        void* vonLoad;
416        int version;
417
418        vonLoad = dlsym(handle, "JNI_OnLoad");
419        if (vonLoad == NULL) {
420            LOGD("No JNI_OnLoad found in %s %p, skipping init\n",
421                pathName, classLoader);
422        } else {
423            /*
424             * Call JNI_OnLoad.  We have to override the current class
425             * loader, which will always be "null" since the stuff at the
426             * top of the stack is around Runtime.loadLibrary().  (See
427             * the comments in the JNI FindClass function.)
428             */
429            OnLoadFunc func = vonLoad;
430            Object* prevOverride = self->classLoaderOverride;
431
432            self->classLoaderOverride = classLoader;
433            oldStatus = dvmChangeStatus(self, THREAD_NATIVE);
434            LOGV("+++ calling JNI_OnLoad(%s)\n", pathName);
435            version = (*func)(gDvm.vmList, NULL);
436            dvmChangeStatus(self, oldStatus);
437            self->classLoaderOverride = prevOverride;
438
439            if (version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 &&
440                version != JNI_VERSION_1_6)
441            {
442                LOGW("JNI_OnLoad returned bad version (%d) in %s %p\n",
443                    version, pathName, classLoader);
444                /*
445                 * It's unwise to call dlclose() here, but we can mark it
446                 * as bad and ensure that future load attempts will fail.
447                 *
448                 * We don't know how far JNI_OnLoad got, so there could
449                 * be some partially-initialized stuff accessible through
450                 * newly-registered native method calls.  We could try to
451                 * unregister them, but that doesn't seem worthwhile.
452                 */
453                result = false;
454            } else {
455                LOGV("+++ finished JNI_OnLoad %s\n", pathName);
456            }
457        }
458
459        if (result)
460            pNewEntry->onLoadResult = kOnLoadOkay;
461        else
462            pNewEntry->onLoadResult = kOnLoadFailed;
463
464        pNewEntry->onLoadThreadId = 0;
465
466        /*
467         * Broadcast a wakeup to anybody sleeping on the condition variable.
468         */
469        dvmLockMutex(&pNewEntry->onLoadLock);
470        pthread_cond_broadcast(&pNewEntry->onLoadCond);
471        dvmUnlockMutex(&pNewEntry->onLoadLock);
472        return result;
473    }
474}
475
476
477/*
478 * Un-register JNI native methods.
479 *
480 * There are two relevant fields in struct Method, "nativeFunc" and
481 * "insns".  The former holds a function pointer to a "bridge" function
482 * (or, for internal native, the actual implementation).  The latter holds
483 * a pointer to the actual JNI method.
484 *
485 * The obvious approach is to reset both fields to their initial state
486 * (nativeFunc points at dvmResolveNativeMethod, insns holds NULL), but
487 * that creates some unpleasant race conditions.  In particular, if another
488 * thread is executing inside the call bridge for the method in question,
489 * and we reset insns to NULL, the VM will crash.  (See the comments above
490 * dvmSetNativeFunc() for additional commentary.)
491 *
492 * We can't rely on being able to update two 32-bit fields in one atomic
493 * operation (e.g. no 64-bit atomic ops on ARMv5TE), so we want to change
494 * only one field.  It turns out we can simply reset nativeFunc to its
495 * initial state, leaving insns alone, because dvmResolveNativeMethod
496 * ignores "insns" entirely.
497 *
498 * When the method is re-registered, both fields will be updated, but
499 * dvmSetNativeFunc guarantees that "insns" is updated first.  This means
500 * we shouldn't be in a situation where we have a "live" call bridge and
501 * a stale implementation pointer.
502 */
503static void unregisterJNINativeMethods(Method* methods, size_t count)
504{
505    while (count != 0) {
506        count--;
507
508        Method* meth = &methods[count];
509        if (!dvmIsNativeMethod(meth))
510            continue;
511        if (dvmIsAbstractMethod(meth))      /* avoid abstract method stubs */
512            continue;
513
514        /*
515         * Strictly speaking this ought to test the function pointer against
516         * the various JNI bridge functions to ensure that we only undo
517         * methods that were registered through JNI.  In practice, any
518         * native method with a non-NULL "insns" is a registered JNI method.
519         *
520         * If we inadvertently unregister an internal-native, it'll get
521         * re-resolved on the next call; unregistering an unregistered
522         * JNI method is a no-op.  So we don't really need to test for
523         * anything.
524         */
525
526        LOGD("Unregistering JNI method %s.%s:%s\n",
527            meth->clazz->descriptor, meth->name, meth->shorty);
528        dvmSetNativeFunc(meth, dvmResolveNativeMethod, NULL);
529    }
530}
531
532/*
533 * Un-register all JNI native methods from a class.
534 */
535void dvmUnregisterJNINativeMethods(ClassObject* clazz)
536{
537    unregisterJNINativeMethods(clazz->directMethods, clazz->directMethodCount);
538    unregisterJNINativeMethods(clazz->virtualMethods, clazz->virtualMethodCount);
539}
540
541
542/*
543 * ===========================================================================
544 *      Signature-based method lookup
545 * ===========================================================================
546 */
547
548/*
549 * Create the pre-mangled form of the class+method string.
550 *
551 * Returns a newly-allocated string, and sets "*pLen" to the length.
552 */
553static char* createJniNameString(const char* classDescriptor,
554    const char* methodName, int* pLen)
555{
556    char* result;
557    size_t descriptorLength = strlen(classDescriptor);
558
559    *pLen = 4 + descriptorLength + strlen(methodName);
560
561    result = malloc(*pLen +1);
562    if (result == NULL)
563        return NULL;
564
565    /*
566     * Add one to classDescriptor to skip the "L", and then replace
567     * the final ";" with a "/" after the sprintf() call.
568     */
569    sprintf(result, "Java/%s%s", classDescriptor + 1, methodName);
570    result[5 + (descriptorLength - 2)] = '/';
571
572    return result;
573}
574
575/*
576 * Returns a newly-allocated, mangled copy of "str".
577 *
578 * "str" is a "modified UTF-8" string.  We convert it to UTF-16 first to
579 * make life simpler.
580 */
581static char* mangleString(const char* str, int len)
582{
583    u2* utf16 = NULL;
584    char* mangle = NULL;
585    int charLen;
586
587    //LOGI("mangling '%s' %d\n", str, len);
588
589    assert(str[len] == '\0');
590
591    charLen = dvmUtf8Len(str);
592    utf16 = (u2*) malloc(sizeof(u2) * charLen);
593    if (utf16 == NULL)
594        goto bail;
595
596    dvmConvertUtf8ToUtf16(utf16, str);
597
598    /*
599     * Compute the length of the mangled string.
600     */
601    int i, mangleLen = 0;
602
603    for (i = 0; i < charLen; i++) {
604        u2 ch = utf16[i];
605
606        if (ch == '$' || ch > 127) {
607            mangleLen += 6;
608        } else {
609            switch (ch) {
610            case '_':
611            case ';':
612            case '[':
613                mangleLen += 2;
614                break;
615            default:
616                mangleLen++;
617                break;
618            }
619        }
620    }
621
622    char* cp;
623
624    mangle = (char*) malloc(mangleLen +1);
625    if (mangle == NULL)
626        goto bail;
627
628    for (i = 0, cp = mangle; i < charLen; i++) {
629        u2 ch = utf16[i];
630
631        if (ch == '$' || ch > 127) {
632            sprintf(cp, "_0%04x", ch);
633            cp += 6;
634        } else {
635            switch (ch) {
636            case '_':
637                *cp++ = '_';
638                *cp++ = '1';
639                break;
640            case ';':
641                *cp++ = '_';
642                *cp++ = '2';
643                break;
644            case '[':
645                *cp++ = '_';
646                *cp++ = '3';
647                break;
648            case '/':
649                *cp++ = '_';
650                break;
651            default:
652                *cp++ = (char) ch;
653                break;
654            }
655        }
656    }
657
658    *cp = '\0';
659
660bail:
661    free(utf16);
662    return mangle;
663}
664
665/*
666 * Create the mangled form of the parameter types.
667 */
668static char* createMangledSignature(const DexProto* proto)
669{
670    DexStringCache sigCache;
671    const char* interim;
672    char* result;
673
674    dexStringCacheInit(&sigCache);
675    interim = dexProtoGetParameterDescriptors(proto, &sigCache);
676    result = mangleString(interim, strlen(interim));
677    dexStringCacheRelease(&sigCache);
678
679    return result;
680}
681
682/*
683 * (This is a dvmHashForeach callback.)
684 *
685 * Search for a matching method in this shared library.
686 *
687 * TODO: we may want to skip libraries for which JNI_OnLoad failed.
688 */
689static int findMethodInLib(void* vlib, void* vmethod)
690{
691    const SharedLib* pLib = (const SharedLib*) vlib;
692    const Method* meth = (const Method*) vmethod;
693    char* preMangleCM = NULL;
694    char* mangleCM = NULL;
695    char* mangleSig = NULL;
696    char* mangleCMSig = NULL;
697    void* func = NULL;
698    int len;
699
700    if (meth->clazz->classLoader != pLib->classLoader) {
701        LOGV("+++ not scanning '%s' for '%s' (wrong CL)\n",
702            pLib->pathName, meth->name);
703        return 0;
704    } else
705        LOGV("+++ scanning '%s' for '%s'\n", pLib->pathName, meth->name);
706
707    /*
708     * First, we try it without the signature.
709     */
710    preMangleCM =
711        createJniNameString(meth->clazz->descriptor, meth->name, &len);
712    if (preMangleCM == NULL)
713        goto bail;
714
715    mangleCM = mangleString(preMangleCM, len);
716    if (mangleCM == NULL)
717        goto bail;
718
719    LOGV("+++ calling dlsym(%s)\n", mangleCM);
720    func = dlsym(pLib->handle, mangleCM);
721    if (func == NULL) {
722        mangleSig =
723            createMangledSignature(&meth->prototype);
724        if (mangleSig == NULL)
725            goto bail;
726
727        mangleCMSig = (char*) malloc(strlen(mangleCM) + strlen(mangleSig) +3);
728        if (mangleCMSig == NULL)
729            goto bail;
730
731        sprintf(mangleCMSig, "%s__%s", mangleCM, mangleSig);
732
733        LOGV("+++ calling dlsym(%s)\n", mangleCMSig);
734        func = dlsym(pLib->handle, mangleCMSig);
735        if (func != NULL) {
736            LOGV("Found '%s' with dlsym\n", mangleCMSig);
737        }
738    } else {
739        LOGV("Found '%s' with dlsym\n", mangleCM);
740    }
741
742bail:
743    free(preMangleCM);
744    free(mangleCM);
745    free(mangleSig);
746    free(mangleCMSig);
747    return (int) func;
748}
749
750/*
751 * See if the requested method lives in any of the currently-loaded
752 * shared libraries.  We do this by checking each of them for the expected
753 * method signature.
754 */
755static void* lookupSharedLibMethod(const Method* method)
756{
757    if (gDvm.nativeLibs == NULL) {
758        LOGE("Unexpected init state: nativeLibs not ready\n");
759        dvmAbort();
760    }
761    return (void*) dvmHashForeach(gDvm.nativeLibs, findMethodInLib,
762        (void*) method);
763}
764
765
766static void appendValue(char type, const JValue value, char* buf, size_t n,
767        bool appendComma)
768{
769    size_t len = strlen(buf);
770    if (len >= n - 32) { // 32 should be longer than anything we could append.
771        buf[len - 1] = '.';
772        buf[len - 2] = '.';
773        buf[len - 3] = '.';
774        return;
775    }
776    char* p = buf + len;
777    switch (type) {
778    case 'B':
779        if (value.b >= 0 && value.b < 10) {
780            sprintf(p, "%d", value.b);
781        } else {
782            sprintf(p, "0x%x (%d)", value.b, value.b);
783        }
784        break;
785    case 'C':
786        if (value.c < 0x7f && value.c >= ' ') {
787            sprintf(p, "U+%x ('%c')", value.c, value.c);
788        } else {
789            sprintf(p, "U+%x", value.c);
790        }
791        break;
792    case 'D':
793        sprintf(p, "%g", value.d);
794        break;
795    case 'F':
796        sprintf(p, "%g", value.f);
797        break;
798    case 'I':
799        sprintf(p, "%d", value.i);
800        break;
801    case 'L':
802        sprintf(p, "0x%x", value.i);
803        break;
804    case 'J':
805        sprintf(p, "%lld", value.j);
806        break;
807    case 'S':
808        sprintf(p, "%d", value.s);
809        break;
810    case 'V':
811        strcpy(p, "void");
812        break;
813    case 'Z':
814        strcpy(p, value.z ? "true" : "false");
815        break;
816    default:
817        sprintf(p, "unknown type '%c'", type);
818        break;
819    }
820
821    if (appendComma) {
822        strcat(p, ", ");
823    }
824}
825
826#define LOGI_NATIVE(...) LOG(LOG_INFO, LOG_TAG "-native", __VA_ARGS__)
827
828void dvmLogNativeMethodEntry(const Method* method, const u4* args)
829{
830    char thisString[32] = { 0 };
831    const u4* sp = args; // &args[method->registersSize - method->insSize];
832    if (!dvmIsStaticMethod(method)) {
833        sprintf(thisString, "this=0x%08x ", *sp++);
834    }
835
836    char argsString[128]= { 0 };
837    const char* desc = &method->shorty[1];
838    while (*desc != '\0') {
839        char argType = *desc++;
840        JValue value;
841        if (argType == 'D' || argType == 'J') {
842            value.j = dvmGetArgLong(sp, 0);
843            sp += 2;
844        } else {
845            value.i = *sp++;
846        }
847        appendValue(argType, value, argsString, sizeof(argsString),
848        *desc != '\0');
849    }
850
851    char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
852    LOGI_NATIVE("-> %s.%s%s %s(%s)", method->clazz->descriptor, method->name,
853            signature, thisString, argsString);
854    free(signature);
855}
856
857void dvmLogNativeMethodExit(const Method* method, Thread* self,
858        const JValue returnValue)
859{
860    char* signature = dexProtoCopyMethodDescriptor(&method->prototype);
861    if (dvmCheckException(self)) {
862        Object* exception = dvmGetException(self);
863        LOGI_NATIVE("<- %s.%s%s threw %s", method->clazz->descriptor,
864                method->name, signature, exception->clazz->descriptor);
865    } else {
866        char returnValueString[128] = { 0 };
867        char returnType = method->shorty[0];
868        appendValue(returnType, returnValue,
869                returnValueString, sizeof(returnValueString), false);
870        LOGI_NATIVE("<- %s.%s%s returned %s", method->clazz->descriptor,
871                method->name, signature, returnValueString);
872    }
873    free(signature);
874}
875