1/*
2 * Copyright (C) 2006 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#define LOG_TAG "JavaBinder"
18//#define LOG_NDEBUG 0
19
20#include "android_os_Parcel.h"
21#include "android_util_Binder.h"
22
23#include "JNIHelp.h"
24
25#include <fcntl.h>
26#include <inttypes.h>
27#include <stdio.h>
28#include <sys/stat.h>
29#include <sys/types.h>
30#include <unistd.h>
31
32#include <utils/Atomic.h>
33#include <binder/IInterface.h>
34#include <binder/IPCThreadState.h>
35#include <utils/Log.h>
36#include <utils/SystemClock.h>
37#include <utils/List.h>
38#include <utils/KeyedVector.h>
39#include <log/logger.h>
40#include <binder/Parcel.h>
41#include <binder/ProcessState.h>
42#include <binder/IServiceManager.h>
43#include <utils/threads.h>
44#include <utils/String8.h>
45
46#include <ScopedUtfChars.h>
47#include <ScopedLocalRef.h>
48
49#include <android_runtime/AndroidRuntime.h>
50
51//#undef ALOGV
52//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
53
54#define DEBUG_DEATH 0
55#if DEBUG_DEATH
56#define LOGDEATH ALOGD
57#else
58#define LOGDEATH ALOGV
59#endif
60
61using namespace android;
62
63// ----------------------------------------------------------------------------
64
65static struct bindernative_offsets_t
66{
67    // Class state.
68    jclass mClass;
69    jmethodID mExecTransact;
70
71    // Object state.
72    jfieldID mObject;
73
74} gBinderOffsets;
75
76// ----------------------------------------------------------------------------
77
78static struct binderinternal_offsets_t
79{
80    // Class state.
81    jclass mClass;
82    jmethodID mForceGc;
83
84} gBinderInternalOffsets;
85
86// ----------------------------------------------------------------------------
87
88static struct debug_offsets_t
89{
90    // Class state.
91    jclass mClass;
92
93} gDebugOffsets;
94
95// ----------------------------------------------------------------------------
96
97static struct error_offsets_t
98{
99    jclass mClass;
100} gErrorOffsets;
101
102// ----------------------------------------------------------------------------
103
104static struct binderproxy_offsets_t
105{
106    // Class state.
107    jclass mClass;
108    jmethodID mConstructor;
109    jmethodID mSendDeathNotice;
110
111    // Object state.
112    jfieldID mObject;
113    jfieldID mSelf;
114    jfieldID mOrgue;
115
116} gBinderProxyOffsets;
117
118static struct class_offsets_t
119{
120    jmethodID mGetName;
121} gClassOffsets;
122
123// ----------------------------------------------------------------------------
124
125static struct log_offsets_t
126{
127    // Class state.
128    jclass mClass;
129    jmethodID mLogE;
130} gLogOffsets;
131
132static struct parcel_file_descriptor_offsets_t
133{
134    jclass mClass;
135    jmethodID mConstructor;
136} gParcelFileDescriptorOffsets;
137
138static struct strict_mode_callback_offsets_t
139{
140    jclass mClass;
141    jmethodID mCallback;
142} gStrictModeCallbackOffsets;
143
144// ****************************************************************************
145// ****************************************************************************
146// ****************************************************************************
147
148static volatile int32_t gNumRefsCreated = 0;
149static volatile int32_t gNumProxyRefs = 0;
150static volatile int32_t gNumLocalRefs = 0;
151static volatile int32_t gNumDeathRefs = 0;
152
153static void incRefsCreated(JNIEnv* env)
154{
155    int old = android_atomic_inc(&gNumRefsCreated);
156    if (old == 200) {
157        android_atomic_and(0, &gNumRefsCreated);
158        env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
159                gBinderInternalOffsets.mForceGc);
160    } else {
161        ALOGV("Now have %d binder ops", old);
162    }
163}
164
165static JavaVM* jnienv_to_javavm(JNIEnv* env)
166{
167    JavaVM* vm;
168    return env->GetJavaVM(&vm) >= 0 ? vm : NULL;
169}
170
171static JNIEnv* javavm_to_jnienv(JavaVM* vm)
172{
173    JNIEnv* env;
174    return vm->GetEnv((void **)&env, JNI_VERSION_1_4) >= 0 ? env : NULL;
175}
176
177static void report_exception(JNIEnv* env, jthrowable excep, const char* msg)
178{
179    env->ExceptionClear();
180
181    jstring tagstr = env->NewStringUTF(LOG_TAG);
182    jstring msgstr = NULL;
183    if (tagstr != NULL) {
184        msgstr = env->NewStringUTF(msg);
185    }
186
187    if ((tagstr == NULL) || (msgstr == NULL)) {
188        env->ExceptionClear();      /* assume exception (OOM?) was thrown */
189        ALOGE("Unable to call Log.e()\n");
190        ALOGE("%s", msg);
191        goto bail;
192    }
193
194    env->CallStaticIntMethod(
195        gLogOffsets.mClass, gLogOffsets.mLogE, tagstr, msgstr, excep);
196    if (env->ExceptionCheck()) {
197        /* attempting to log the failure has failed */
198        ALOGW("Failed trying to log exception, msg='%s'\n", msg);
199        env->ExceptionClear();
200    }
201
202    if (env->IsInstanceOf(excep, gErrorOffsets.mClass)) {
203        /*
204         * It's an Error: Reraise the exception, detach this thread, and
205         * wait for the fireworks. Die even more blatantly after a minute
206         * if the gentler attempt doesn't do the trick.
207         *
208         * The GetJavaVM function isn't on the "approved" list of JNI calls
209         * that can be made while an exception is pending, so we want to
210         * get the VM ptr, throw the exception, and then detach the thread.
211         */
212        JavaVM* vm = jnienv_to_javavm(env);
213        env->Throw(excep);
214        vm->DetachCurrentThread();
215        sleep(60);
216        ALOGE("Forcefully exiting");
217        exit(1);
218        *((int *) 1) = 1;
219    }
220
221bail:
222    /* discard local refs created for us by VM */
223    env->DeleteLocalRef(tagstr);
224    env->DeleteLocalRef(msgstr);
225}
226
227class JavaBBinderHolder;
228
229class JavaBBinder : public BBinder
230{
231public:
232    JavaBBinder(JNIEnv* env, jobject object)
233        : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))
234    {
235        ALOGV("Creating JavaBBinder %p\n", this);
236        android_atomic_inc(&gNumLocalRefs);
237        incRefsCreated(env);
238    }
239
240    bool    checkSubclass(const void* subclassID) const
241    {
242        return subclassID == &gBinderOffsets;
243    }
244
245    jobject object() const
246    {
247        return mObject;
248    }
249
250protected:
251    virtual ~JavaBBinder()
252    {
253        ALOGV("Destroying JavaBBinder %p\n", this);
254        android_atomic_dec(&gNumLocalRefs);
255        JNIEnv* env = javavm_to_jnienv(mVM);
256        env->DeleteGlobalRef(mObject);
257    }
258
259    virtual status_t onTransact(
260        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0)
261    {
262        JNIEnv* env = javavm_to_jnienv(mVM);
263
264        ALOGV("onTransact() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
265
266        IPCThreadState* thread_state = IPCThreadState::self();
267        const int32_t strict_policy_before = thread_state->getStrictModePolicy();
268
269        //printf("Transact from %p to Java code sending: ", this);
270        //data.print();
271        //printf("\n");
272        jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
273            code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);
274        jthrowable excep = env->ExceptionOccurred();
275
276        if (excep) {
277            report_exception(env, excep,
278                "*** Uncaught remote exception!  "
279                "(Exceptions are not yet supported across processes.)");
280            res = JNI_FALSE;
281
282            /* clean up JNI local ref -- we don't return to Java code */
283            env->DeleteLocalRef(excep);
284        }
285
286        // Check if the strict mode state changed while processing the
287        // call.  The Binder state will be restored by the underlying
288        // Binder system in IPCThreadState, however we need to take care
289        // of the parallel Java state as well.
290        if (thread_state->getStrictModePolicy() != strict_policy_before) {
291            set_dalvik_blockguard_policy(env, strict_policy_before);
292        }
293
294        jthrowable excep2 = env->ExceptionOccurred();
295        if (excep2) {
296            report_exception(env, excep2,
297                "*** Uncaught exception in onBinderStrictModePolicyChange");
298            /* clean up JNI local ref -- we don't return to Java code */
299            env->DeleteLocalRef(excep2);
300        }
301
302        // Need to always call through the native implementation of
303        // SYSPROPS_TRANSACTION.
304        if (code == SYSPROPS_TRANSACTION) {
305            BBinder::onTransact(code, data, reply, flags);
306        }
307
308        //aout << "onTransact to Java code; result=" << res << endl
309        //    << "Transact from " << this << " to Java code returning "
310        //    << reply << ": " << *reply << endl;
311        return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
312    }
313
314    virtual status_t dump(int fd, const Vector<String16>& args)
315    {
316        return 0;
317    }
318
319private:
320    JavaVM* const   mVM;
321    jobject const   mObject;
322};
323
324// ----------------------------------------------------------------------------
325
326class JavaBBinderHolder : public RefBase
327{
328public:
329    sp<JavaBBinder> get(JNIEnv* env, jobject obj)
330    {
331        AutoMutex _l(mLock);
332        sp<JavaBBinder> b = mBinder.promote();
333        if (b == NULL) {
334            b = new JavaBBinder(env, obj);
335            mBinder = b;
336            ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
337                 b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
338        }
339
340        return b;
341    }
342
343    sp<JavaBBinder> getExisting()
344    {
345        AutoMutex _l(mLock);
346        return mBinder.promote();
347    }
348
349private:
350    Mutex           mLock;
351    wp<JavaBBinder> mBinder;
352};
353
354// ----------------------------------------------------------------------------
355
356// Per-IBinder death recipient bookkeeping.  This is how we reconcile local jobject
357// death recipient references passed in through JNI with the permanent corresponding
358// JavaDeathRecipient objects.
359
360class JavaDeathRecipient;
361
362class DeathRecipientList : public RefBase {
363    List< sp<JavaDeathRecipient> > mList;
364    Mutex mLock;
365
366public:
367    DeathRecipientList();
368    ~DeathRecipientList();
369
370    void add(const sp<JavaDeathRecipient>& recipient);
371    void remove(const sp<JavaDeathRecipient>& recipient);
372    sp<JavaDeathRecipient> find(jobject recipient);
373};
374
375// ----------------------------------------------------------------------------
376
377class JavaDeathRecipient : public IBinder::DeathRecipient
378{
379public:
380    JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
381        : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
382          mObjectWeak(NULL), mList(list)
383    {
384        // These objects manage their own lifetimes so are responsible for final bookkeeping.
385        // The list holds a strong reference to this object.
386        LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
387        list->add(this);
388
389        android_atomic_inc(&gNumDeathRefs);
390        incRefsCreated(env);
391    }
392
393    void binderDied(const wp<IBinder>& who)
394    {
395        LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
396        if (mObject != NULL) {
397            JNIEnv* env = javavm_to_jnienv(mVM);
398
399            env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
400                    gBinderProxyOffsets.mSendDeathNotice, mObject);
401            jthrowable excep = env->ExceptionOccurred();
402            if (excep) {
403                report_exception(env, excep,
404                        "*** Uncaught exception returned from death notification!");
405            }
406
407            // Demote from strong ref to weak after binderDied() has been delivered,
408            // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
409            mObjectWeak = env->NewWeakGlobalRef(mObject);
410            env->DeleteGlobalRef(mObject);
411            mObject = NULL;
412        }
413    }
414
415    void clearReference()
416    {
417        sp<DeathRecipientList> list = mList.promote();
418        if (list != NULL) {
419            LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
420            list->remove(this);
421        } else {
422            LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
423        }
424    }
425
426    bool matches(jobject obj) {
427        bool result;
428        JNIEnv* env = javavm_to_jnienv(mVM);
429
430        if (mObject != NULL) {
431            result = env->IsSameObject(obj, mObject);
432        } else {
433            jobject me = env->NewLocalRef(mObjectWeak);
434            result = env->IsSameObject(obj, me);
435            env->DeleteLocalRef(me);
436        }
437        return result;
438    }
439
440    void warnIfStillLive() {
441        if (mObject != NULL) {
442            // Okay, something is wrong -- we have a hard reference to a live death
443            // recipient on the VM side, but the list is being torn down.
444            JNIEnv* env = javavm_to_jnienv(mVM);
445            ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
446            ScopedLocalRef<jstring> nameRef(env,
447                    (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
448            ScopedUtfChars nameUtf(env, nameRef.get());
449            if (nameUtf.c_str() != NULL) {
450                ALOGW("BinderProxy is being destroyed but the application did not call "
451                        "unlinkToDeath to unlink all of its death recipients beforehand.  "
452                        "Releasing leaked death recipient: %s", nameUtf.c_str());
453            } else {
454                ALOGW("BinderProxy being destroyed; unable to get DR object name");
455                env->ExceptionClear();
456            }
457        }
458    }
459
460protected:
461    virtual ~JavaDeathRecipient()
462    {
463        //ALOGI("Removing death ref: recipient=%p\n", mObject);
464        android_atomic_dec(&gNumDeathRefs);
465        JNIEnv* env = javavm_to_jnienv(mVM);
466        if (mObject != NULL) {
467            env->DeleteGlobalRef(mObject);
468        } else {
469            env->DeleteWeakGlobalRef(mObjectWeak);
470        }
471    }
472
473private:
474    JavaVM* const mVM;
475    jobject mObject;
476    jweak mObjectWeak; // will be a weak ref to the same VM-side DeathRecipient after binderDied()
477    wp<DeathRecipientList> mList;
478};
479
480// ----------------------------------------------------------------------------
481
482DeathRecipientList::DeathRecipientList() {
483    LOGDEATH("New DRL @ %p", this);
484}
485
486DeathRecipientList::~DeathRecipientList() {
487    LOGDEATH("Destroy DRL @ %p", this);
488    AutoMutex _l(mLock);
489
490    // Should never happen -- the JavaDeathRecipient objects that have added themselves
491    // to the list are holding references on the list object.  Only when they are torn
492    // down can the list header be destroyed.
493    if (mList.size() > 0) {
494        List< sp<JavaDeathRecipient> >::iterator iter;
495        for (iter = mList.begin(); iter != mList.end(); iter++) {
496            (*iter)->warnIfStillLive();
497        }
498    }
499}
500
501void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
502    AutoMutex _l(mLock);
503
504    LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
505    mList.push_back(recipient);
506}
507
508void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
509    AutoMutex _l(mLock);
510
511    List< sp<JavaDeathRecipient> >::iterator iter;
512    for (iter = mList.begin(); iter != mList.end(); iter++) {
513        if (*iter == recipient) {
514            LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
515            mList.erase(iter);
516            return;
517        }
518    }
519}
520
521sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
522    AutoMutex _l(mLock);
523
524    List< sp<JavaDeathRecipient> >::iterator iter;
525    for (iter = mList.begin(); iter != mList.end(); iter++) {
526        if ((*iter)->matches(recipient)) {
527            return *iter;
528        }
529    }
530    return NULL;
531}
532
533// ----------------------------------------------------------------------------
534
535namespace android {
536
537static void proxy_cleanup(const void* id, void* obj, void* cleanupCookie)
538{
539    android_atomic_dec(&gNumProxyRefs);
540    JNIEnv* env = javavm_to_jnienv((JavaVM*)cleanupCookie);
541    env->DeleteGlobalRef((jobject)obj);
542}
543
544static Mutex mProxyLock;
545
546jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
547{
548    if (val == NULL) return NULL;
549
550    if (val->checkSubclass(&gBinderOffsets)) {
551        // One of our own!
552        jobject object = static_cast<JavaBBinder*>(val.get())->object();
553        LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
554        return object;
555    }
556
557    // For the rest of the function we will hold this lock, to serialize
558    // looking/creation of Java proxies for native Binder proxies.
559    AutoMutex _l(mProxyLock);
560
561    // Someone else's...  do we know about it?
562    jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
563    if (object != NULL) {
564        jobject res = jniGetReferent(env, object);
565        if (res != NULL) {
566            ALOGV("objectForBinder %p: found existing %p!\n", val.get(), res);
567            return res;
568        }
569        LOGDEATH("Proxy object %p of IBinder %p no longer in working set!!!", object, val.get());
570        android_atomic_dec(&gNumProxyRefs);
571        val->detachObject(&gBinderProxyOffsets);
572        env->DeleteGlobalRef(object);
573    }
574
575    object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
576    if (object != NULL) {
577        LOGDEATH("objectForBinder %p: created new proxy %p !\n", val.get(), object);
578        // The proxy holds a reference to the native object.
579        env->SetLongField(object, gBinderProxyOffsets.mObject, (jlong)val.get());
580        val->incStrong((void*)javaObjectForIBinder);
581
582        // The native object needs to hold a weak reference back to the
583        // proxy, so we can retrieve the same proxy if it is still active.
584        jobject refObject = env->NewGlobalRef(
585                env->GetObjectField(object, gBinderProxyOffsets.mSelf));
586        val->attachObject(&gBinderProxyOffsets, refObject,
587                jnienv_to_javavm(env), proxy_cleanup);
588
589        // Also remember the death recipients registered on this proxy
590        sp<DeathRecipientList> drl = new DeathRecipientList;
591        drl->incStrong((void*)javaObjectForIBinder);
592        env->SetLongField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast<jlong>(drl.get()));
593
594        // Note that a new object reference has been created.
595        android_atomic_inc(&gNumProxyRefs);
596        incRefsCreated(env);
597    }
598
599    return object;
600}
601
602sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
603{
604    if (obj == NULL) return NULL;
605
606    if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
607        JavaBBinderHolder* jbh = (JavaBBinderHolder*)
608            env->GetLongField(obj, gBinderOffsets.mObject);
609        return jbh != NULL ? jbh->get(env, obj) : NULL;
610    }
611
612    if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
613        return (IBinder*)
614            env->GetLongField(obj, gBinderProxyOffsets.mObject);
615    }
616
617    ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
618    return NULL;
619}
620
621jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
622{
623    return env->NewObject(
624            gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
625}
626
627void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
628{
629    // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
630    // to sync our state back to it.  See the comments in StrictMode.java.
631    env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
632                              gStrictModeCallbackOffsets.mCallback,
633                              strict_policy);
634}
635
636void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
637        bool canThrowRemoteException)
638{
639    switch (err) {
640        case UNKNOWN_ERROR:
641            jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
642            break;
643        case NO_MEMORY:
644            jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
645            break;
646        case INVALID_OPERATION:
647            jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
648            break;
649        case BAD_VALUE:
650            jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
651            break;
652        case BAD_INDEX:
653            jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
654            break;
655        case BAD_TYPE:
656            jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
657            break;
658        case NAME_NOT_FOUND:
659            jniThrowException(env, "java/util/NoSuchElementException", NULL);
660            break;
661        case PERMISSION_DENIED:
662            jniThrowException(env, "java/lang/SecurityException", NULL);
663            break;
664        case NOT_ENOUGH_DATA:
665            jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
666            break;
667        case NO_INIT:
668            jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
669            break;
670        case ALREADY_EXISTS:
671            jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
672            break;
673        case DEAD_OBJECT:
674            // DeadObjectException is a checked exception, only throw from certain methods.
675            jniThrowException(env, canThrowRemoteException
676                    ? "android/os/DeadObjectException"
677                            : "java/lang/RuntimeException", NULL);
678            break;
679        case UNKNOWN_TRANSACTION:
680            jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
681            break;
682        case FAILED_TRANSACTION:
683            ALOGE("!!! FAILED BINDER TRANSACTION !!!");
684            // TransactionTooLargeException is a checked exception, only throw from certain methods.
685            // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
686            //        but it is not the only one.  The Binder driver can return BR_FAILED_REPLY
687            //        for other reasons also, such as if the transaction is malformed or
688            //        refers to an FD that has been closed.  We should change the driver
689            //        to enable us to distinguish these cases in the future.
690            jniThrowException(env, canThrowRemoteException
691                    ? "android/os/TransactionTooLargeException"
692                            : "java/lang/RuntimeException", NULL);
693            break;
694        case FDS_NOT_ALLOWED:
695            jniThrowException(env, "java/lang/RuntimeException",
696                    "Not allowed to write file descriptors here");
697            break;
698        case -EBADF:
699            jniThrowException(env, "java/lang/RuntimeException",
700                    "Bad file descriptor");
701            break;
702        case -ENFILE:
703            jniThrowException(env, "java/lang/RuntimeException",
704                    "File table overflow");
705            break;
706        case -EMFILE:
707            jniThrowException(env, "java/lang/RuntimeException",
708                    "Too many open files");
709            break;
710        case -EFBIG:
711            jniThrowException(env, "java/lang/RuntimeException",
712                    "File too large");
713            break;
714        case -ENOSPC:
715            jniThrowException(env, "java/lang/RuntimeException",
716                    "No space left on device");
717            break;
718        case -ESPIPE:
719            jniThrowException(env, "java/lang/RuntimeException",
720                    "Illegal seek");
721            break;
722        case -EROFS:
723            jniThrowException(env, "java/lang/RuntimeException",
724                    "Read-only file system");
725            break;
726        case -EMLINK:
727            jniThrowException(env, "java/lang/RuntimeException",
728                    "Too many links");
729            break;
730        default:
731            ALOGE("Unknown binder error code. 0x%" PRIx32, err);
732            String8 msg;
733            msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
734            // RemoteException is a checked exception, only throw from certain methods.
735            jniThrowException(env, canThrowRemoteException
736                    ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
737            break;
738    }
739}
740
741}
742
743// ----------------------------------------------------------------------------
744
745static jint android_os_Binder_getCallingPid(JNIEnv* env, jobject clazz)
746{
747    return IPCThreadState::self()->getCallingPid();
748}
749
750static jint android_os_Binder_getCallingUid(JNIEnv* env, jobject clazz)
751{
752    return IPCThreadState::self()->getCallingUid();
753}
754
755static jlong android_os_Binder_clearCallingIdentity(JNIEnv* env, jobject clazz)
756{
757    return IPCThreadState::self()->clearCallingIdentity();
758}
759
760static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
761{
762    // XXX temporary sanity check to debug crashes.
763    int uid = (int)(token>>32);
764    if (uid > 0 && uid < 999) {
765        // In Android currently there are no uids in this range.
766        char buf[128];
767        sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
768        jniThrowException(env, "java/lang/IllegalStateException", buf);
769        return;
770    }
771    IPCThreadState::self()->restoreCallingIdentity(token);
772}
773
774static void android_os_Binder_setThreadStrictModePolicy(JNIEnv* env, jobject clazz, jint policyMask)
775{
776    IPCThreadState::self()->setStrictModePolicy(policyMask);
777}
778
779static jint android_os_Binder_getThreadStrictModePolicy(JNIEnv* env, jobject clazz)
780{
781    return IPCThreadState::self()->getStrictModePolicy();
782}
783
784static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
785{
786    IPCThreadState::self()->flushCommands();
787}
788
789static void android_os_Binder_init(JNIEnv* env, jobject obj)
790{
791    JavaBBinderHolder* jbh = new JavaBBinderHolder();
792    if (jbh == NULL) {
793        jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
794        return;
795    }
796    ALOGV("Java Binder %p: acquiring first ref on holder %p", obj, jbh);
797    jbh->incStrong((void*)android_os_Binder_init);
798    env->SetLongField(obj, gBinderOffsets.mObject, (jlong)jbh);
799}
800
801static void android_os_Binder_destroy(JNIEnv* env, jobject obj)
802{
803    JavaBBinderHolder* jbh = (JavaBBinderHolder*)
804        env->GetLongField(obj, gBinderOffsets.mObject);
805    if (jbh != NULL) {
806        env->SetLongField(obj, gBinderOffsets.mObject, 0);
807        ALOGV("Java Binder %p: removing ref on holder %p", obj, jbh);
808        jbh->decStrong((void*)android_os_Binder_init);
809    } else {
810        // Encountering an uninitialized binder is harmless.  All it means is that
811        // the Binder was only partially initialized when its finalizer ran and called
812        // destroy().  The Binder could be partially initialized for several reasons.
813        // For example, a Binder subclass constructor might have thrown an exception before
814        // it could delegate to its superclass's constructor.  Consequently init() would
815        // not have been called and the holder pointer would remain NULL.
816        ALOGV("Java Binder %p: ignoring uninitialized binder", obj);
817    }
818}
819
820// ----------------------------------------------------------------------------
821
822static const JNINativeMethod gBinderMethods[] = {
823     /* name, signature, funcPtr */
824    { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
825    { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
826    { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
827    { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
828    { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
829    { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
830    { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
831    { "init", "()V", (void*)android_os_Binder_init },
832    { "destroy", "()V", (void*)android_os_Binder_destroy }
833};
834
835const char* const kBinderPathName = "android/os/Binder";
836
837static int int_register_android_os_Binder(JNIEnv* env)
838{
839    jclass clazz;
840
841    clazz = env->FindClass(kBinderPathName);
842    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Binder");
843
844    gBinderOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
845    gBinderOffsets.mExecTransact
846        = env->GetMethodID(clazz, "execTransact", "(IJJI)Z");
847    assert(gBinderOffsets.mExecTransact);
848
849    gBinderOffsets.mObject
850        = env->GetFieldID(clazz, "mObject", "J");
851    assert(gBinderOffsets.mObject);
852
853    return AndroidRuntime::registerNativeMethods(
854        env, kBinderPathName,
855        gBinderMethods, NELEM(gBinderMethods));
856}
857
858// ****************************************************************************
859// ****************************************************************************
860// ****************************************************************************
861
862namespace android {
863
864jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
865{
866    return gNumLocalRefs;
867}
868
869jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
870{
871    return gNumProxyRefs;
872}
873
874jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
875{
876    return gNumDeathRefs;
877}
878
879}
880
881// ****************************************************************************
882// ****************************************************************************
883// ****************************************************************************
884
885static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
886{
887    sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
888    return javaObjectForIBinder(env, b);
889}
890
891static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
892{
893    sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
894    android::IPCThreadState::self()->joinThreadPool();
895}
896
897static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
898        jobject clazz, jboolean disable)
899{
900    IPCThreadState::disableBackgroundScheduling(disable ? true : false);
901}
902
903static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
904{
905    ALOGV("Gc has executed, clearing binder ops");
906    android_atomic_and(0, &gNumRefsCreated);
907}
908
909// ----------------------------------------------------------------------------
910
911static const JNINativeMethod gBinderInternalMethods[] = {
912     /* name, signature, funcPtr */
913    { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
914    { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
915    { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
916    { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc }
917};
918
919const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
920
921static int int_register_android_os_BinderInternal(JNIEnv* env)
922{
923    jclass clazz;
924
925    clazz = env->FindClass(kBinderInternalPathName);
926    LOG_FATAL_IF(clazz == NULL, "Unable to find class com.android.internal.os.BinderInternal");
927
928    gBinderInternalOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
929    gBinderInternalOffsets.mForceGc
930        = env->GetStaticMethodID(clazz, "forceBinderGc", "()V");
931    assert(gBinderInternalOffsets.mForceGc);
932
933    return AndroidRuntime::registerNativeMethods(
934        env, kBinderInternalPathName,
935        gBinderInternalMethods, NELEM(gBinderInternalMethods));
936}
937
938// ****************************************************************************
939// ****************************************************************************
940// ****************************************************************************
941
942static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
943{
944    IBinder* target = (IBinder*)
945        env->GetLongField(obj, gBinderProxyOffsets.mObject);
946    if (target == NULL) {
947        return JNI_FALSE;
948    }
949    status_t err = target->pingBinder();
950    return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
951}
952
953static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
954{
955    IBinder* target = (IBinder*) env->GetLongField(obj, gBinderProxyOffsets.mObject);
956    if (target != NULL) {
957        const String16& desc = target->getInterfaceDescriptor();
958        return env->NewString(desc.string(), desc.size());
959    }
960    jniThrowException(env, "java/lang/RuntimeException",
961            "No binder found for object");
962    return NULL;
963}
964
965static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
966{
967    IBinder* target = (IBinder*)
968        env->GetLongField(obj, gBinderProxyOffsets.mObject);
969    if (target == NULL) {
970        return JNI_FALSE;
971    }
972    bool alive = target->isBinderAlive();
973    return alive ? JNI_TRUE : JNI_FALSE;
974}
975
976static int getprocname(pid_t pid, char *buf, size_t len) {
977    char filename[32];
978    FILE *f;
979
980    snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
981    f = fopen(filename, "r");
982    if (!f) {
983        *buf = '\0';
984        return 1;
985    }
986    if (!fgets(buf, len, f)) {
987        *buf = '\0';
988        fclose(f);
989        return 2;
990    }
991    fclose(f);
992    return 0;
993}
994
995static bool push_eventlog_string(char** pos, const char* end, const char* str) {
996    jint len = strlen(str);
997    int space_needed = 1 + sizeof(len) + len;
998    if (end - *pos < space_needed) {
999        ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
1000             end - *pos, space_needed);
1001        return false;
1002    }
1003    **pos = EVENT_TYPE_STRING;
1004    (*pos)++;
1005    memcpy(*pos, &len, sizeof(len));
1006    *pos += sizeof(len);
1007    memcpy(*pos, str, len);
1008    *pos += len;
1009    return true;
1010}
1011
1012static bool push_eventlog_int(char** pos, const char* end, jint val) {
1013    int space_needed = 1 + sizeof(val);
1014    if (end - *pos < space_needed) {
1015        ALOGW("not enough space for int.  remain=%" PRIdPTR "; needed=%d",
1016             end - *pos, space_needed);
1017        return false;
1018    }
1019    **pos = EVENT_TYPE_INT;
1020    (*pos)++;
1021    memcpy(*pos, &val, sizeof(val));
1022    *pos += sizeof(val);
1023    return true;
1024}
1025
1026// From frameworks/base/core/java/android/content/EventLogTags.logtags:
1027#define ENABLE_BINDER_SAMPLE 0
1028#define LOGTAG_BINDER_OPERATION 52004
1029
1030static void conditionally_log_binder_call(int64_t start_millis,
1031                                          IBinder* target, jint code) {
1032    int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1033
1034    int sample_percent;
1035    if (duration_ms >= 500) {
1036        sample_percent = 100;
1037    } else {
1038        sample_percent = 100 * duration_ms / 500;
1039        if (sample_percent == 0) {
1040            return;
1041        }
1042        if (sample_percent < (random() % 100 + 1)) {
1043            return;
1044        }
1045    }
1046
1047    char process_name[40];
1048    getprocname(getpid(), process_name, sizeof(process_name));
1049    String8 desc(target->getInterfaceDescriptor());
1050
1051    char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1052    buf[0] = EVENT_TYPE_LIST;
1053    buf[1] = 5;
1054    char* pos = &buf[2];
1055    char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1];  // leave room for final \n
1056    if (!push_eventlog_string(&pos, end, desc.string())) return;
1057    if (!push_eventlog_int(&pos, end, code)) return;
1058    if (!push_eventlog_int(&pos, end, duration_ms)) return;
1059    if (!push_eventlog_string(&pos, end, process_name)) return;
1060    if (!push_eventlog_int(&pos, end, sample_percent)) return;
1061    *(pos++) = '\n';   // conventional with EVENT_TYPE_LIST apparently.
1062    android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1063}
1064
1065// We only measure binder call durations to potentially log them if
1066// we're on the main thread.  Unfortunately sim-eng doesn't seem to
1067// have gettid, so we just ignore this and don't log if we can't
1068// get the thread id.
1069static bool should_time_binder_calls() {
1070#ifdef HAVE_GETTID
1071  return (getpid() == androidGetTid());
1072#else
1073#warning no gettid(), so not logging Binder calls...
1074  return false;
1075#endif
1076}
1077
1078static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
1079        jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
1080{
1081    if (dataObj == NULL) {
1082        jniThrowNullPointerException(env, NULL);
1083        return JNI_FALSE;
1084    }
1085
1086    Parcel* data = parcelForJavaObject(env, dataObj);
1087    if (data == NULL) {
1088        return JNI_FALSE;
1089    }
1090    Parcel* reply = parcelForJavaObject(env, replyObj);
1091    if (reply == NULL && replyObj != NULL) {
1092        return JNI_FALSE;
1093    }
1094
1095    IBinder* target = (IBinder*)
1096        env->GetLongField(obj, gBinderProxyOffsets.mObject);
1097    if (target == NULL) {
1098        jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1099        return JNI_FALSE;
1100    }
1101
1102    ALOGV("Java code calling transact on %p in Java object %p with code %" PRId32 "\n",
1103            target, obj, code);
1104
1105#if ENABLE_BINDER_SAMPLE
1106    // Only log the binder call duration for things on the Java-level main thread.
1107    // But if we don't
1108    const bool time_binder_calls = should_time_binder_calls();
1109
1110    int64_t start_millis;
1111    if (time_binder_calls) {
1112        start_millis = uptimeMillis();
1113    }
1114#endif
1115    //printf("Transact from Java code to %p sending: ", target); data->print();
1116    status_t err = target->transact(code, *data, reply, flags);
1117    //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
1118#if ENABLE_BINDER_SAMPLE
1119    if (time_binder_calls) {
1120        conditionally_log_binder_call(start_millis, target, code);
1121    }
1122#endif
1123
1124    if (err == NO_ERROR) {
1125        return JNI_TRUE;
1126    } else if (err == UNKNOWN_TRANSACTION) {
1127        return JNI_FALSE;
1128    }
1129
1130    signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
1131    return JNI_FALSE;
1132}
1133
1134static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
1135        jobject recipient, jint flags) // throws RemoteException
1136{
1137    if (recipient == NULL) {
1138        jniThrowNullPointerException(env, NULL);
1139        return;
1140    }
1141
1142    IBinder* target = (IBinder*)
1143        env->GetLongField(obj, gBinderProxyOffsets.mObject);
1144    if (target == NULL) {
1145        ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
1146        assert(false);
1147    }
1148
1149    LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
1150
1151    if (!target->localBinder()) {
1152        DeathRecipientList* list = (DeathRecipientList*)
1153                env->GetLongField(obj, gBinderProxyOffsets.mOrgue);
1154        sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
1155        status_t err = target->linkToDeath(jdr, NULL, flags);
1156        if (err != NO_ERROR) {
1157            // Failure adding the death recipient, so clear its reference
1158            // now.
1159            jdr->clearReference();
1160            signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
1161        }
1162    }
1163}
1164
1165static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1166                                                 jobject recipient, jint flags)
1167{
1168    jboolean res = JNI_FALSE;
1169    if (recipient == NULL) {
1170        jniThrowNullPointerException(env, NULL);
1171        return res;
1172    }
1173
1174    IBinder* target = (IBinder*)
1175        env->GetLongField(obj, gBinderProxyOffsets.mObject);
1176    if (target == NULL) {
1177        ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
1178        return JNI_FALSE;
1179    }
1180
1181    LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
1182
1183    if (!target->localBinder()) {
1184        status_t err = NAME_NOT_FOUND;
1185
1186        // If we find the matching recipient, proceed to unlink using that
1187        DeathRecipientList* list = (DeathRecipientList*)
1188                env->GetLongField(obj, gBinderProxyOffsets.mOrgue);
1189        sp<JavaDeathRecipient> origJDR = list->find(recipient);
1190        LOGDEATH("   unlink found list %p and JDR %p", list, origJDR.get());
1191        if (origJDR != NULL) {
1192            wp<IBinder::DeathRecipient> dr;
1193            err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1194            if (err == NO_ERROR && dr != NULL) {
1195                sp<IBinder::DeathRecipient> sdr = dr.promote();
1196                JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1197                if (jdr != NULL) {
1198                    jdr->clearReference();
1199                }
1200            }
1201        }
1202
1203        if (err == NO_ERROR || err == DEAD_OBJECT) {
1204            res = JNI_TRUE;
1205        } else {
1206            jniThrowException(env, "java/util/NoSuchElementException",
1207                              "Death link does not exist");
1208        }
1209    }
1210
1211    return res;
1212}
1213
1214static void android_os_BinderProxy_destroy(JNIEnv* env, jobject obj)
1215{
1216    IBinder* b = (IBinder*)
1217            env->GetLongField(obj, gBinderProxyOffsets.mObject);
1218    DeathRecipientList* drl = (DeathRecipientList*)
1219            env->GetLongField(obj, gBinderProxyOffsets.mOrgue);
1220
1221    LOGDEATH("Destroying BinderProxy %p: binder=%p drl=%p\n", obj, b, drl);
1222    env->SetLongField(obj, gBinderProxyOffsets.mObject, 0);
1223    env->SetLongField(obj, gBinderProxyOffsets.mOrgue, 0);
1224    drl->decStrong((void*)javaObjectForIBinder);
1225    b->decStrong((void*)javaObjectForIBinder);
1226
1227    IPCThreadState::self()->flushCommands();
1228}
1229
1230// ----------------------------------------------------------------------------
1231
1232static const JNINativeMethod gBinderProxyMethods[] = {
1233     /* name, signature, funcPtr */
1234    {"pingBinder",          "()Z", (void*)android_os_BinderProxy_pingBinder},
1235    {"isBinderAlive",       "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1236    {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
1237    {"transactNative",      "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
1238    {"linkToDeath",         "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1239    {"unlinkToDeath",       "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
1240    {"destroy",             "()V", (void*)android_os_BinderProxy_destroy},
1241};
1242
1243const char* const kBinderProxyPathName = "android/os/BinderProxy";
1244
1245static int int_register_android_os_BinderProxy(JNIEnv* env)
1246{
1247    jclass clazz;
1248
1249    clazz = env->FindClass("java/lang/Error");
1250    LOG_FATAL_IF(clazz == NULL, "Unable to find class java.lang.Error");
1251    gErrorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1252
1253    clazz = env->FindClass(kBinderProxyPathName);
1254    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.BinderProxy");
1255
1256    gBinderProxyOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1257    gBinderProxyOffsets.mConstructor
1258        = env->GetMethodID(clazz, "<init>", "()V");
1259    assert(gBinderProxyOffsets.mConstructor);
1260    gBinderProxyOffsets.mSendDeathNotice
1261        = env->GetStaticMethodID(clazz, "sendDeathNotice", "(Landroid/os/IBinder$DeathRecipient;)V");
1262    assert(gBinderProxyOffsets.mSendDeathNotice);
1263
1264    gBinderProxyOffsets.mObject
1265        = env->GetFieldID(clazz, "mObject", "J");
1266    assert(gBinderProxyOffsets.mObject);
1267    gBinderProxyOffsets.mSelf
1268        = env->GetFieldID(clazz, "mSelf", "Ljava/lang/ref/WeakReference;");
1269    assert(gBinderProxyOffsets.mSelf);
1270    gBinderProxyOffsets.mOrgue
1271        = env->GetFieldID(clazz, "mOrgue", "J");
1272    assert(gBinderProxyOffsets.mOrgue);
1273
1274    clazz = env->FindClass("java/lang/Class");
1275    LOG_FATAL_IF(clazz == NULL, "Unable to find java.lang.Class");
1276    gClassOffsets.mGetName = env->GetMethodID(clazz, "getName", "()Ljava/lang/String;");
1277    assert(gClassOffsets.mGetName);
1278
1279    return AndroidRuntime::registerNativeMethods(
1280        env, kBinderProxyPathName,
1281        gBinderProxyMethods, NELEM(gBinderProxyMethods));
1282}
1283
1284// ****************************************************************************
1285// ****************************************************************************
1286// ****************************************************************************
1287
1288int register_android_os_Binder(JNIEnv* env)
1289{
1290    if (int_register_android_os_Binder(env) < 0)
1291        return -1;
1292    if (int_register_android_os_BinderInternal(env) < 0)
1293        return -1;
1294    if (int_register_android_os_BinderProxy(env) < 0)
1295        return -1;
1296
1297    jclass clazz;
1298
1299    clazz = env->FindClass("android/util/Log");
1300    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.util.Log");
1301    gLogOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1302    gLogOffsets.mLogE = env->GetStaticMethodID(
1303        clazz, "e", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
1304    assert(gLogOffsets.mLogE);
1305
1306    clazz = env->FindClass("android/os/ParcelFileDescriptor");
1307    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor");
1308    gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1309    gParcelFileDescriptorOffsets.mConstructor
1310        = env->GetMethodID(clazz, "<init>", "(Ljava/io/FileDescriptor;)V");
1311
1312    clazz = env->FindClass("android/os/StrictMode");
1313    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.StrictMode");
1314    gStrictModeCallbackOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1315    gStrictModeCallbackOffsets.mCallback = env->GetStaticMethodID(
1316        clazz, "onBinderStrictModePolicyChange", "(I)V");
1317    LOG_FATAL_IF(gStrictModeCallbackOffsets.mCallback == NULL,
1318                 "Unable to find strict mode callback.");
1319
1320    return 0;
1321}
1322