• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <atomic>
24 #include <fcntl.h>
25 #include <inttypes.h>
26 #include <mutex>
27 #include <stdio.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 
32 #include <android-base/stringprintf.h>
33 #include <binder/BpBinder.h>
34 #include <binder/IInterface.h>
35 #include <binder/IPCThreadState.h>
36 #include <binder/IServiceManager.h>
37 #include <binder/Parcel.h>
38 #include <binder/ProcessState.h>
39 #include <binder/Stability.h>
40 #include <binderthreadstate/CallerUtils.h>
41 #include <cutils/atomic.h>
42 #include <cutils/threads.h>
43 #include <log/log.h>
44 #include <utils/KeyedVector.h>
45 #include <utils/List.h>
46 #include <utils/Log.h>
47 #include <utils/String8.h>
48 #include <utils/SystemClock.h>
49 #include <utils/threads.h>
50 
51 #include <nativehelper/JNIHelp.h>
52 #include <nativehelper/ScopedLocalRef.h>
53 #include <nativehelper/ScopedUtfChars.h>
54 
55 #include "core_jni_helpers.h"
56 
57 //#undef ALOGV
58 //#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
59 
60 #define DEBUG_DEATH 0
61 #if DEBUG_DEATH
62 #define LOGDEATH ALOGD
63 #else
64 #define LOGDEATH ALOGV
65 #endif
66 
67 using namespace android;
68 
69 // ----------------------------------------------------------------------------
70 
71 static struct bindernative_offsets_t
72 {
73     // Class state.
74     jclass mClass;
75     jmethodID mExecTransact;
76     jmethodID mGetInterfaceDescriptor;
77 
78     // Object state.
79     jfieldID mObject;
80 
81 } gBinderOffsets;
82 
83 // ----------------------------------------------------------------------------
84 
85 static struct binderinternal_offsets_t
86 {
87     // Class state.
88     jclass mClass;
89     jmethodID mForceGc;
90     jmethodID mProxyLimitCallback;
91 
92 } gBinderInternalOffsets;
93 
94 static struct sparseintarray_offsets_t
95 {
96     jclass classObject;
97     jmethodID constructor;
98     jmethodID put;
99 } gSparseIntArrayOffsets;
100 
101 // ----------------------------------------------------------------------------
102 
103 static struct error_offsets_t
104 {
105     jclass mError;
106     jclass mOutOfMemory;
107     jclass mStackOverflow;
108 } gErrorOffsets;
109 
110 // ----------------------------------------------------------------------------
111 
112 static struct binderproxy_offsets_t
113 {
114     // Class state.
115     jclass mClass;
116     jmethodID mGetInstance;
117     jmethodID mSendDeathNotice;
118 
119     // Object state.
120     jfieldID mNativeData;  // Field holds native pointer to BinderProxyNativeData.
121 } gBinderProxyOffsets;
122 
123 static struct class_offsets_t
124 {
125     jmethodID mGetName;
126 } gClassOffsets;
127 
128 // ----------------------------------------------------------------------------
129 
130 static struct log_offsets_t
131 {
132     // Class state.
133     jclass mClass;
134     jmethodID mLogE;
135 } gLogOffsets;
136 
137 static struct parcel_file_descriptor_offsets_t
138 {
139     jclass mClass;
140     jmethodID mConstructor;
141 } gParcelFileDescriptorOffsets;
142 
143 static struct strict_mode_callback_offsets_t
144 {
145     jclass mClass;
146     jmethodID mCallback;
147 } gStrictModeCallbackOffsets;
148 
149 static struct thread_dispatch_offsets_t
150 {
151     // Class state.
152     jclass mClass;
153     jmethodID mDispatchUncaughtException;
154     jmethodID mCurrentThread;
155 } gThreadDispatchOffsets;
156 
157 // ****************************************************************************
158 // ****************************************************************************
159 // ****************************************************************************
160 
161 static constexpr int32_t PROXY_WARN_INTERVAL = 5000;
162 static constexpr uint32_t GC_INTERVAL = 1000;
163 
164 static std::atomic<uint32_t> gNumProxies(0);
165 static std::atomic<uint32_t> gProxiesWarned(0);
166 
167 // Number of GlobalRefs held by JavaBBinders.
168 static std::atomic<uint32_t> gNumLocalRefsCreated(0);
169 static std::atomic<uint32_t> gNumLocalRefsDeleted(0);
170 // Number of GlobalRefs held by JavaDeathRecipients.
171 static std::atomic<uint32_t> gNumDeathRefsCreated(0);
172 static std::atomic<uint32_t> gNumDeathRefsDeleted(0);
173 
174 // We collected after creating this many refs.
175 static std::atomic<uint32_t> gCollectedAtRefs(0);
176 
177 // Garbage collect if we've allocated at least GC_INTERVAL refs since the last time.
178 // TODO: Consider removing this completely. We should no longer be generating GlobalRefs
179 // that are reclaimed as a result of GC action.
180 __attribute__((no_sanitize("unsigned-integer-overflow")))
gcIfManyNewRefs(JNIEnv * env)181 static void gcIfManyNewRefs(JNIEnv* env)
182 {
183     uint32_t totalRefs = gNumLocalRefsCreated.load(std::memory_order_relaxed)
184             + gNumDeathRefsCreated.load(std::memory_order_relaxed);
185     uint32_t collectedAtRefs = gCollectedAtRefs.load(memory_order_relaxed);
186     // A bound on the number of threads that can have incremented gNum...RefsCreated before the
187     // following check is executed. Effectively a bound on #threads. Almost any value will do.
188     static constexpr uint32_t MAX_RACING = 100000;
189 
190     if (totalRefs - (collectedAtRefs + GC_INTERVAL) /* modular arithmetic! */ < MAX_RACING) {
191         // Recently passed next GC interval.
192         if (gCollectedAtRefs.compare_exchange_strong(collectedAtRefs,
193                 collectedAtRefs + GC_INTERVAL, std::memory_order_relaxed)) {
194             ALOGV("Binder forcing GC at %u created refs", totalRefs);
195             env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
196                     gBinderInternalOffsets.mForceGc);
197         }  // otherwise somebody else beat us to it.
198     } else {
199         ALOGV("Now have %d binder ops", totalRefs - collectedAtRefs);
200     }
201 }
202 
jnienv_to_javavm(JNIEnv * env)203 static JavaVM* jnienv_to_javavm(JNIEnv* env)
204 {
205     JavaVM* vm;
206     return env->GetJavaVM(&vm) >= 0 ? vm : NULL;
207 }
208 
javavm_to_jnienv(JavaVM * vm)209 static JNIEnv* javavm_to_jnienv(JavaVM* vm)
210 {
211     JNIEnv* env;
212     return vm->GetEnv((void **)&env, JNI_VERSION_1_4) >= 0 ? env : NULL;
213 }
214 
GetErrorTypeName(JNIEnv * env,jthrowable error)215 static const char* GetErrorTypeName(JNIEnv* env, jthrowable error) {
216   if (env->IsInstanceOf(error, gErrorOffsets.mOutOfMemory)) {
217     return "OutOfMemoryError";
218   }
219   if (env->IsInstanceOf(error, gErrorOffsets.mStackOverflow)) {
220     return "StackOverflowError";
221   }
222   return nullptr;
223 }
224 
225 // Report a java.lang.Error (or subclass). This will terminate the runtime by
226 // calling FatalError with a message derived from the given error.
report_java_lang_error_fatal_error(JNIEnv * env,jthrowable error,const char * msg)227 static void report_java_lang_error_fatal_error(JNIEnv* env, jthrowable error,
228         const char* msg)
229 {
230     // Report an error: reraise the exception and ask the runtime to abort.
231 
232     // Try to get the exception string. Sometimes logcat isn't available,
233     // so try to add it to the abort message.
234     std::string exc_msg;
235     {
236         ScopedLocalRef<jclass> exc_class(env, env->GetObjectClass(error));
237         jmethodID method_id = env->GetMethodID(exc_class.get(), "toString",
238                 "()Ljava/lang/String;");
239         ScopedLocalRef<jstring> jstr(
240                 env,
241                 reinterpret_cast<jstring>(
242                         env->CallObjectMethod(error, method_id)));
243         ScopedLocalRef<jthrowable> new_error(env, nullptr);
244         bool got_jstr = false;
245         if (env->ExceptionCheck()) {
246             new_error = ScopedLocalRef<jthrowable>(env, env->ExceptionOccurred());
247             env->ExceptionClear();
248         }
249         if (jstr.get() != nullptr) {
250             ScopedUtfChars jstr_utf(env, jstr.get());
251             if (jstr_utf.c_str() != nullptr) {
252                 exc_msg = jstr_utf.c_str();
253                 got_jstr = true;
254             } else {
255                 new_error = ScopedLocalRef<jthrowable>(env, env->ExceptionOccurred());
256                 env->ExceptionClear();
257             }
258         }
259         if (!got_jstr) {
260             exc_msg = "(Unknown exception message)";
261             const char* orig_type = GetErrorTypeName(env, error);
262             if (orig_type != nullptr) {
263                 exc_msg = base::StringPrintf("%s (Error was %s)", exc_msg.c_str(), orig_type);
264             }
265             const char* new_type =
266                 new_error == nullptr ? nullptr : GetErrorTypeName(env, new_error.get());
267             if (new_type != nullptr) {
268                 exc_msg = base::StringPrintf("%s (toString() error was %s)",
269                                              exc_msg.c_str(),
270                                              new_type);
271             }
272         }
273     }
274 
275     env->Throw(error);
276     ALOGE("java.lang.Error thrown during binder transaction (stack trace follows) : ");
277     env->ExceptionDescribe();
278 
279     std::string error_msg = base::StringPrintf(
280             "java.lang.Error thrown during binder transaction: %s",
281             exc_msg.c_str());
282     env->FatalError(error_msg.c_str());
283 }
284 
285 // Report a java.lang.Error (or subclass). This will terminate the runtime, either by
286 // the uncaught exception handler, or explicitly by calling
287 // report_java_lang_error_fatal_error.
report_java_lang_error(JNIEnv * env,jthrowable error,const char * msg)288 static void report_java_lang_error(JNIEnv* env, jthrowable error, const char* msg)
289 {
290     // Try to run the uncaught exception machinery.
291     jobject thread = env->CallStaticObjectMethod(gThreadDispatchOffsets.mClass,
292             gThreadDispatchOffsets.mCurrentThread);
293     if (thread != nullptr) {
294         env->CallVoidMethod(thread, gThreadDispatchOffsets.mDispatchUncaughtException,
295                 error);
296         // Should not return here, unless more errors occured.
297     }
298     // Some error occurred that meant that either dispatchUncaughtException could not be
299     // called or that it had an error itself (as this should be unreachable under normal
300     // conditions). As the binder code cannot handle Errors, attempt to log the error and
301     // abort.
302     env->ExceptionClear();
303     report_java_lang_error_fatal_error(env, error, msg);
304 }
305 
306 namespace android {
307 
binder_report_exception(JNIEnv * env,jthrowable excep,const char * msg)308 void binder_report_exception(JNIEnv* env, jthrowable excep, const char* msg) {
309     env->ExceptionClear();
310 
311     ScopedLocalRef<jstring> tagstr(env, env->NewStringUTF(LOG_TAG));
312     ScopedLocalRef<jstring> msgstr(env);
313     if (tagstr != nullptr) {
314         msgstr.reset(env->NewStringUTF(msg));
315     }
316 
317     if ((tagstr != nullptr) && (msgstr != nullptr)) {
318         env->CallStaticIntMethod(gLogOffsets.mClass, gLogOffsets.mLogE,
319                 tagstr.get(), msgstr.get(), excep);
320         if (env->ExceptionCheck()) {
321             // Attempting to log the failure has failed.
322             ALOGW("Failed trying to log exception, msg='%s'\n", msg);
323             env->ExceptionClear();
324         }
325     } else {
326         env->ExceptionClear();      /* assume exception (OOM?) was thrown */
327         ALOGE("Unable to call Log.e()\n");
328         ALOGE("%s", msg);
329     }
330 
331     if (env->IsInstanceOf(excep, gErrorOffsets.mError)) {
332         report_java_lang_error(env, excep, msg);
333     }
334 }
335 
336 } // namespace android
337 
338 class JavaBBinderHolder;
339 
340 class JavaBBinder : public BBinder
341 {
342 public:
JavaBBinder(JNIEnv * env,jobject object)343     JavaBBinder(JNIEnv* env, jobject /* Java Binder */ object)
344         : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))
345     {
346         ALOGV("Creating JavaBBinder %p\n", this);
347         gNumLocalRefsCreated.fetch_add(1, std::memory_order_relaxed);
348         gcIfManyNewRefs(env);
349     }
350 
checkSubclass(const void * subclassID) const351     bool    checkSubclass(const void* subclassID) const
352     {
353         return subclassID == &gBinderOffsets;
354     }
355 
object() const356     jobject object() const
357     {
358         return mObject;
359     }
360 
361 protected:
~JavaBBinder()362     virtual ~JavaBBinder()
363     {
364         ALOGV("Destroying JavaBBinder %p\n", this);
365         gNumLocalRefsDeleted.fetch_add(1, memory_order_relaxed);
366         JNIEnv* env = javavm_to_jnienv(mVM);
367         env->DeleteGlobalRef(mObject);
368     }
369 
getInterfaceDescriptor() const370     const String16& getInterfaceDescriptor() const override
371     {
372         call_once(mPopulateDescriptor, [this] {
373             JNIEnv* env = javavm_to_jnienv(mVM);
374 
375             ALOGV("getInterfaceDescriptor() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
376 
377             jstring descriptor = (jstring)env->CallObjectMethod(mObject, gBinderOffsets.mGetInterfaceDescriptor);
378 
379             if (descriptor == nullptr) {
380                 return;
381             }
382 
383             static_assert(sizeof(jchar) == sizeof(char16_t), "");
384             const jchar* descriptorChars = env->GetStringChars(descriptor, nullptr);
385             const char16_t* rawDescriptor = reinterpret_cast<const char16_t*>(descriptorChars);
386             jsize rawDescriptorLen = env->GetStringLength(descriptor);
387             mDescriptor = String16(rawDescriptor, rawDescriptorLen);
388             env->ReleaseStringChars(descriptor, descriptorChars);
389         });
390 
391         return mDescriptor;
392     }
393 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags=0)394     status_t onTransact(
395         uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0) override
396     {
397         JNIEnv* env = javavm_to_jnienv(mVM);
398 
399         LOG_ALWAYS_FATAL_IF(env == nullptr,
400                             "Binder thread started or Java binder used, but env null. Attach JVM?");
401 
402         ALOGV("onTransact() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
403 
404         IPCThreadState* thread_state = IPCThreadState::self();
405         const int32_t strict_policy_before = thread_state->getStrictModePolicy();
406 
407         //printf("Transact from %p to Java code sending: ", this);
408         //data.print();
409         //printf("\n");
410         jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
411             code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);
412 
413         if (env->ExceptionCheck()) {
414             ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
415             binder_report_exception(env, excep.get(),
416                                     "*** Uncaught remote exception!  "
417                                     "(Exceptions are not yet supported across processes.)");
418             res = JNI_FALSE;
419         }
420 
421         // Check if the strict mode state changed while processing the
422         // call.  The Binder state will be restored by the underlying
423         // Binder system in IPCThreadState, however we need to take care
424         // of the parallel Java state as well.
425         if (thread_state->getStrictModePolicy() != strict_policy_before) {
426             set_dalvik_blockguard_policy(env, strict_policy_before);
427         }
428 
429         if (env->ExceptionCheck()) {
430             ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
431             binder_report_exception(env, excep.get(),
432                                     "*** Uncaught exception in onBinderStrictModePolicyChange");
433         }
434 
435         // Need to always call through the native implementation of
436         // SYSPROPS_TRANSACTION.
437         if (code == SYSPROPS_TRANSACTION) {
438             BBinder::onTransact(code, data, reply, flags);
439         }
440 
441         //aout << "onTransact to Java code; result=" << res << endl
442         //    << "Transact from " << this << " to Java code returning "
443         //    << reply << ": " << *reply << endl;
444         return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
445     }
446 
dump(int fd,const Vector<String16> & args)447     status_t dump(int fd, const Vector<String16>& args) override
448     {
449         return 0;
450     }
451 
452 private:
453     JavaVM* const   mVM;
454     jobject const   mObject;  // GlobalRef to Java Binder
455 
456     mutable std::once_flag mPopulateDescriptor;
457     mutable String16 mDescriptor;
458 };
459 
460 // ----------------------------------------------------------------------------
461 
462 class JavaBBinderHolder
463 {
464 public:
get(JNIEnv * env,jobject obj)465     sp<JavaBBinder> get(JNIEnv* env, jobject obj)
466     {
467         AutoMutex _l(mLock);
468         sp<JavaBBinder> b = mBinder.promote();
469         if (b == NULL) {
470             b = new JavaBBinder(env, obj);
471             if (mVintf) {
472                 ::android::internal::Stability::markVintf(b.get());
473             }
474             if (mExtension != nullptr) {
475                 b.get()->setExtension(mExtension);
476             }
477             mBinder = b;
478             ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
479                  b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
480         }
481 
482         return b;
483     }
484 
getExisting()485     sp<JavaBBinder> getExisting()
486     {
487         AutoMutex _l(mLock);
488         return mBinder.promote();
489     }
490 
markVintf()491     void markVintf() {
492         AutoMutex _l(mLock);
493         mVintf = true;
494     }
495 
forceDowngradeToSystemStability()496     void forceDowngradeToSystemStability() {
497         AutoMutex _l(mLock);
498         mVintf = false;
499     }
500 
getExtension()501     sp<IBinder> getExtension() {
502         AutoMutex _l(mLock);
503         sp<JavaBBinder> b = mBinder.promote();
504         if (b != nullptr) {
505             return b.get()->getExtension();
506         }
507         return mExtension;
508     }
509 
setExtension(const sp<IBinder> & extension)510     void setExtension(const sp<IBinder>& extension) {
511         AutoMutex _l(mLock);
512         mExtension = extension;
513         sp<JavaBBinder> b = mBinder.promote();
514         if (b != nullptr) {
515             b.get()->setExtension(mExtension);
516         }
517     }
518 
519 private:
520     Mutex           mLock;
521     wp<JavaBBinder> mBinder;
522 
523     // in the future, we might condense this into int32_t stability, or if there
524     // is too much binder state here, we can think about making JavaBBinder an
525     // sp here (avoid recreating it)
526     bool            mVintf = false;
527 
528     sp<IBinder>     mExtension;
529 };
530 
531 // ----------------------------------------------------------------------------
532 
533 // Per-IBinder death recipient bookkeeping.  This is how we reconcile local jobject
534 // death recipient references passed in through JNI with the permanent corresponding
535 // JavaDeathRecipient objects.
536 
537 class JavaDeathRecipient;
538 
539 class DeathRecipientList : public RefBase {
540     List< sp<JavaDeathRecipient> > mList;
541     Mutex mLock;
542 
543 public:
544     DeathRecipientList();
545     ~DeathRecipientList();
546 
547     void add(const sp<JavaDeathRecipient>& recipient);
548     void remove(const sp<JavaDeathRecipient>& recipient);
549     sp<JavaDeathRecipient> find(jobject recipient);
550 
551     Mutex& lock();  // Use with care; specifically for mutual exclusion during binder death
552 };
553 
554 // ----------------------------------------------------------------------------
555 
556 class JavaDeathRecipient : public IBinder::DeathRecipient
557 {
558 public:
JavaDeathRecipient(JNIEnv * env,jobject object,const sp<DeathRecipientList> & list)559     JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
560         : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
561           mObjectWeak(NULL), mList(list)
562     {
563         // These objects manage their own lifetimes so are responsible for final bookkeeping.
564         // The list holds a strong reference to this object.
565         LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
566         list->add(this);
567 
568         gNumDeathRefsCreated.fetch_add(1, std::memory_order_relaxed);
569         gcIfManyNewRefs(env);
570     }
571 
binderDied(const wp<IBinder> & who)572     void binderDied(const wp<IBinder>& who)
573     {
574         LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
575         if (mObject != NULL) {
576             JNIEnv* env = javavm_to_jnienv(mVM);
577             ScopedLocalRef<jobject> jBinderProxy(env, javaObjectForIBinder(env, who.promote()));
578             env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
579                                       gBinderProxyOffsets.mSendDeathNotice, mObject,
580                                       jBinderProxy.get());
581             if (env->ExceptionCheck()) {
582                 jthrowable excep = env->ExceptionOccurred();
583                 binder_report_exception(env, excep,
584                                         "*** Uncaught exception returned from death notification!");
585             }
586 
587             // Serialize with our containing DeathRecipientList so that we can't
588             // delete the global ref on mObject while the list is being iterated.
589             sp<DeathRecipientList> list = mList.promote();
590             if (list != NULL) {
591                 AutoMutex _l(list->lock());
592 
593                 // Demote from strong ref to weak after binderDied() has been delivered,
594                 // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
595                 mObjectWeak = env->NewWeakGlobalRef(mObject);
596                 env->DeleteGlobalRef(mObject);
597                 mObject = NULL;
598             }
599         }
600     }
601 
clearReference()602     void clearReference()
603     {
604         sp<DeathRecipientList> list = mList.promote();
605         if (list != NULL) {
606             LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
607             list->remove(this);
608         } else {
609             LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
610         }
611     }
612 
matches(jobject obj)613     bool matches(jobject obj) {
614         bool result;
615         JNIEnv* env = javavm_to_jnienv(mVM);
616 
617         if (mObject != NULL) {
618             result = env->IsSameObject(obj, mObject);
619         } else {
620             ScopedLocalRef<jobject> me(env, env->NewLocalRef(mObjectWeak));
621             result = env->IsSameObject(obj, me.get());
622         }
623         return result;
624     }
625 
warnIfStillLive()626     void warnIfStillLive() {
627         if (mObject != NULL) {
628             // Okay, something is wrong -- we have a hard reference to a live death
629             // recipient on the VM side, but the list is being torn down.
630             JNIEnv* env = javavm_to_jnienv(mVM);
631             ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
632             ScopedLocalRef<jstring> nameRef(env,
633                     (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
634             ScopedUtfChars nameUtf(env, nameRef.get());
635             if (nameUtf.c_str() != NULL) {
636                 ALOGW("BinderProxy is being destroyed but the application did not call "
637                         "unlinkToDeath to unlink all of its death recipients beforehand.  "
638                         "Releasing leaked death recipient: %s", nameUtf.c_str());
639             } else {
640                 ALOGW("BinderProxy being destroyed; unable to get DR object name");
641                 env->ExceptionClear();
642             }
643         }
644     }
645 
646 protected:
~JavaDeathRecipient()647     virtual ~JavaDeathRecipient()
648     {
649         //ALOGI("Removing death ref: recipient=%p\n", mObject);
650         gNumDeathRefsDeleted.fetch_add(1, std::memory_order_relaxed);
651         JNIEnv* env = javavm_to_jnienv(mVM);
652         if (mObject != NULL) {
653             env->DeleteGlobalRef(mObject);
654         } else {
655             env->DeleteWeakGlobalRef(mObjectWeak);
656         }
657     }
658 
659 private:
660     JavaVM* const mVM;
661     jobject mObject;  // Initial strong ref to Java-side DeathRecipient. Cleared on binderDied().
662     jweak mObjectWeak; // Weak ref to the same Java-side DeathRecipient after binderDied().
663     wp<DeathRecipientList> mList;
664 };
665 
666 // ----------------------------------------------------------------------------
667 
DeathRecipientList()668 DeathRecipientList::DeathRecipientList() {
669     LOGDEATH("New DRL @ %p", this);
670 }
671 
~DeathRecipientList()672 DeathRecipientList::~DeathRecipientList() {
673     LOGDEATH("Destroy DRL @ %p", this);
674     AutoMutex _l(mLock);
675 
676     // Should never happen -- the JavaDeathRecipient objects that have added themselves
677     // to the list are holding references on the list object.  Only when they are torn
678     // down can the list header be destroyed.
679     if (mList.size() > 0) {
680         List< sp<JavaDeathRecipient> >::iterator iter;
681         for (iter = mList.begin(); iter != mList.end(); iter++) {
682             (*iter)->warnIfStillLive();
683         }
684     }
685 }
686 
add(const sp<JavaDeathRecipient> & recipient)687 void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
688     AutoMutex _l(mLock);
689 
690     LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
691     mList.push_back(recipient);
692 }
693 
remove(const sp<JavaDeathRecipient> & recipient)694 void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
695     AutoMutex _l(mLock);
696 
697     List< sp<JavaDeathRecipient> >::iterator iter;
698     for (iter = mList.begin(); iter != mList.end(); iter++) {
699         if (*iter == recipient) {
700             LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
701             mList.erase(iter);
702             return;
703         }
704     }
705 }
706 
find(jobject recipient)707 sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
708     AutoMutex _l(mLock);
709 
710     List< sp<JavaDeathRecipient> >::iterator iter;
711     for (iter = mList.begin(); iter != mList.end(); iter++) {
712         if ((*iter)->matches(recipient)) {
713             return *iter;
714         }
715     }
716     return NULL;
717 }
718 
lock()719 Mutex& DeathRecipientList::lock() {
720     return mLock;
721 }
722 
723 // ----------------------------------------------------------------------------
724 
725 namespace android {
726 
727 // We aggregate native pointer fields for BinderProxy in a single object to allow
728 // management with a single NativeAllocationRegistry, and to reduce the number of JNI
729 // Java field accesses. This costs us some extra indirections here.
730 struct BinderProxyNativeData {
731     // Both fields are constant and not null once javaObjectForIBinder returns this as
732     // part of a BinderProxy.
733 
734     // The native IBinder proxied by this BinderProxy.
735     sp<IBinder> mObject;
736 
737     // Death recipients for mObject. Reference counted only because DeathRecipients
738     // hold a weak reference that can be temporarily promoted.
739     sp<DeathRecipientList> mOrgue;  // Death recipients for mObject.
740 };
741 
getBPNativeData(JNIEnv * env,jobject obj)742 BinderProxyNativeData* getBPNativeData(JNIEnv* env, jobject obj) {
743     return (BinderProxyNativeData *) env->GetLongField(obj, gBinderProxyOffsets.mNativeData);
744 }
745 
746 // If the argument is a JavaBBinder, return the Java object that was used to create it.
747 // Otherwise return a BinderProxy for the IBinder. If a previous call was passed the
748 // same IBinder, and the original BinderProxy is still alive, return the same BinderProxy.
javaObjectForIBinder(JNIEnv * env,const sp<IBinder> & val)749 jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
750 {
751     // N.B. This function is called from a @FastNative JNI method, so don't take locks around
752     // calls to Java code or block the calling thread for a long time for any reason.
753 
754     if (val == NULL) return NULL;
755 
756     if (val->checkSubclass(&gBinderOffsets)) {
757         // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
758         jobject object = static_cast<JavaBBinder*>(val.get())->object();
759         LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
760         return object;
761     }
762 
763     BinderProxyNativeData* nativeData = new BinderProxyNativeData();
764     nativeData->mOrgue = new DeathRecipientList;
765     nativeData->mObject = val;
766 
767     jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
768             gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
769     if (env->ExceptionCheck()) {
770         // In the exception case, getInstance still took ownership of nativeData.
771         return NULL;
772     }
773     BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
774     if (actualNativeData == nativeData) {
775         // Created a new Proxy
776         uint32_t numProxies = gNumProxies.fetch_add(1, std::memory_order_relaxed);
777         uint32_t numLastWarned = gProxiesWarned.load(std::memory_order_relaxed);
778         if (numProxies >= numLastWarned + PROXY_WARN_INTERVAL) {
779             // Multiple threads can get here, make sure only one of them gets to
780             // update the warn counter.
781             if (gProxiesWarned.compare_exchange_strong(numLastWarned,
782                         numLastWarned + PROXY_WARN_INTERVAL, std::memory_order_relaxed)) {
783                 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
784             }
785         }
786     } else {
787         delete nativeData;
788     }
789 
790     return object;
791 }
792 
ibinderForJavaObject(JNIEnv * env,jobject obj)793 sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
794 {
795     if (obj == NULL) return NULL;
796 
797     // Instance of Binder?
798     if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
799         JavaBBinderHolder* jbh = (JavaBBinderHolder*)
800             env->GetLongField(obj, gBinderOffsets.mObject);
801         return jbh->get(env, obj);
802     }
803 
804     // Instance of BinderProxy?
805     if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
806         return getBPNativeData(env, obj)->mObject;
807     }
808 
809     ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
810     return NULL;
811 }
812 
newParcelFileDescriptor(JNIEnv * env,jobject fileDesc)813 jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
814 {
815     return env->NewObject(
816             gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
817 }
818 
set_dalvik_blockguard_policy(JNIEnv * env,jint strict_policy)819 void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
820 {
821     // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
822     // to sync our state back to it.  See the comments in StrictMode.java.
823     env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
824                               gStrictModeCallbackOffsets.mCallback,
825                               strict_policy);
826 }
827 
signalExceptionForError(JNIEnv * env,jobject obj,status_t err,bool canThrowRemoteException,int parcelSize)828 void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
829         bool canThrowRemoteException, int parcelSize)
830 {
831     switch (err) {
832         case UNKNOWN_ERROR:
833             jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
834             break;
835         case NO_MEMORY:
836             jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
837             break;
838         case INVALID_OPERATION:
839             jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
840             break;
841         case BAD_VALUE:
842             jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
843             break;
844         case BAD_INDEX:
845             jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
846             break;
847         case BAD_TYPE:
848             jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
849             break;
850         case NAME_NOT_FOUND:
851             jniThrowException(env, "java/util/NoSuchElementException", NULL);
852             break;
853         case PERMISSION_DENIED:
854             jniThrowException(env, "java/lang/SecurityException", NULL);
855             break;
856         case NOT_ENOUGH_DATA:
857             jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
858             break;
859         case NO_INIT:
860             jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
861             break;
862         case ALREADY_EXISTS:
863             jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
864             break;
865         case DEAD_OBJECT:
866             // DeadObjectException is a checked exception, only throw from certain methods.
867             jniThrowException(env, canThrowRemoteException
868                     ? "android/os/DeadObjectException"
869                             : "java/lang/RuntimeException", NULL);
870             break;
871         case UNKNOWN_TRANSACTION:
872             jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
873             break;
874         case FAILED_TRANSACTION: {
875             ALOGE("!!! FAILED BINDER TRANSACTION !!!  (parcel size = %d)", parcelSize);
876             const char* exceptionToThrow;
877             char msg[128];
878             // TransactionTooLargeException is a checked exception, only throw from certain methods.
879             // TODO(b/28321379): Transaction size is the most common cause for FAILED_TRANSACTION
880             //        but it is not the only one.  The Binder driver can return BR_FAILED_REPLY
881             //        for other reasons also, such as if the transaction is malformed or
882             //        refers to an FD that has been closed.  We should change the driver
883             //        to enable us to distinguish these cases in the future.
884             if (canThrowRemoteException && parcelSize > 200*1024) {
885                 // bona fide large payload
886                 exceptionToThrow = "android/os/TransactionTooLargeException";
887                 snprintf(msg, sizeof(msg)-1, "data parcel size %d bytes", parcelSize);
888             } else {
889                 // Heuristic: a payload smaller than this threshold "shouldn't" be too
890                 // big, so it's probably some other, more subtle problem.  In practice
891                 // it seems to always mean that the remote process died while the binder
892                 // transaction was already in flight.
893                 exceptionToThrow = (canThrowRemoteException)
894                         ? "android/os/DeadObjectException"
895                         : "java/lang/RuntimeException";
896                 snprintf(msg, sizeof(msg) - 1,
897                          "Transaction failed on small parcel; remote process probably died, but "
898                          "this could also be caused by running out of binder buffer space");
899             }
900             jniThrowException(env, exceptionToThrow, msg);
901         } break;
902         case FDS_NOT_ALLOWED:
903             jniThrowException(env, "java/lang/RuntimeException",
904                     "Not allowed to write file descriptors here");
905             break;
906         case UNEXPECTED_NULL:
907             jniThrowNullPointerException(env, NULL);
908             break;
909         case -EBADF:
910             jniThrowException(env, "java/lang/RuntimeException",
911                     "Bad file descriptor");
912             break;
913         case -ENFILE:
914             jniThrowException(env, "java/lang/RuntimeException",
915                     "File table overflow");
916             break;
917         case -EMFILE:
918             jniThrowException(env, "java/lang/RuntimeException",
919                     "Too many open files");
920             break;
921         case -EFBIG:
922             jniThrowException(env, "java/lang/RuntimeException",
923                     "File too large");
924             break;
925         case -ENOSPC:
926             jniThrowException(env, "java/lang/RuntimeException",
927                     "No space left on device");
928             break;
929         case -ESPIPE:
930             jniThrowException(env, "java/lang/RuntimeException",
931                     "Illegal seek");
932             break;
933         case -EROFS:
934             jniThrowException(env, "java/lang/RuntimeException",
935                     "Read-only file system");
936             break;
937         case -EMLINK:
938             jniThrowException(env, "java/lang/RuntimeException",
939                     "Too many links");
940             break;
941         default:
942             ALOGE("Unknown binder error code. 0x%" PRIx32, err);
943             String8 msg;
944             msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
945             // RemoteException is a checked exception, only throw from certain methods.
946             jniThrowException(env, canThrowRemoteException
947                     ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
948             break;
949     }
950 }
951 
952 }
953 
954 // ----------------------------------------------------------------------------
955 
android_os_Binder_getCallingPid()956 static jint android_os_Binder_getCallingPid()
957 {
958     return IPCThreadState::self()->getCallingPid();
959 }
960 
android_os_Binder_getCallingUid()961 static jint android_os_Binder_getCallingUid()
962 {
963     return IPCThreadState::self()->getCallingUid();
964 }
965 
android_os_Binder_isDirectlyHandlingTransaction()966 static jboolean android_os_Binder_isDirectlyHandlingTransaction() {
967     return getCurrentServingCall() == BinderCallType::BINDER;
968 }
969 
android_os_Binder_clearCallingIdentity()970 static jlong android_os_Binder_clearCallingIdentity()
971 {
972     return IPCThreadState::self()->clearCallingIdentity();
973 }
974 
android_os_Binder_restoreCallingIdentity(jlong token)975 static void android_os_Binder_restoreCallingIdentity(jlong token)
976 {
977     IPCThreadState::self()->restoreCallingIdentity(token);
978 }
979 
android_os_Binder_setThreadStrictModePolicy(jint policyMask)980 static void android_os_Binder_setThreadStrictModePolicy(jint policyMask)
981 {
982     IPCThreadState::self()->setStrictModePolicy(policyMask);
983 }
984 
android_os_Binder_getThreadStrictModePolicy()985 static jint android_os_Binder_getThreadStrictModePolicy()
986 {
987     return IPCThreadState::self()->getStrictModePolicy();
988 }
989 
android_os_Binder_setCallingWorkSourceUid(jint workSource)990 static jlong android_os_Binder_setCallingWorkSourceUid(jint workSource)
991 {
992     return IPCThreadState::self()->setCallingWorkSourceUid(workSource);
993 }
994 
android_os_Binder_getCallingWorkSourceUid()995 static jlong android_os_Binder_getCallingWorkSourceUid()
996 {
997     return IPCThreadState::self()->getCallingWorkSourceUid();
998 }
999 
android_os_Binder_clearCallingWorkSource()1000 static jlong android_os_Binder_clearCallingWorkSource()
1001 {
1002     return IPCThreadState::self()->clearCallingWorkSource();
1003 }
1004 
android_os_Binder_restoreCallingWorkSource(jlong token)1005 static void android_os_Binder_restoreCallingWorkSource(jlong token)
1006 {
1007     IPCThreadState::self()->restoreCallingWorkSource(token);
1008 }
1009 
android_os_Binder_markVintfStability(JNIEnv * env,jobject clazz)1010 static void android_os_Binder_markVintfStability(JNIEnv* env, jobject clazz) {
1011     JavaBBinderHolder* jbh =
1012         (JavaBBinderHolder*) env->GetLongField(clazz, gBinderOffsets.mObject);
1013     jbh->markVintf();
1014 }
1015 
android_os_Binder_forceDowngradeToSystemStability(JNIEnv * env,jobject clazz)1016 static void android_os_Binder_forceDowngradeToSystemStability(JNIEnv* env, jobject clazz) {
1017     JavaBBinderHolder* jbh =
1018         (JavaBBinderHolder*) env->GetLongField(clazz, gBinderOffsets.mObject);
1019     jbh->forceDowngradeToSystemStability();
1020 }
1021 
android_os_Binder_flushPendingCommands(JNIEnv * env,jobject clazz)1022 static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
1023 {
1024     IPCThreadState::self()->flushCommands();
1025 }
1026 
android_os_Binder_getNativeBBinderHolder(JNIEnv * env,jobject clazz)1027 static jlong android_os_Binder_getNativeBBinderHolder(JNIEnv* env, jobject clazz)
1028 {
1029     JavaBBinderHolder* jbh = new JavaBBinderHolder();
1030     return (jlong) jbh;
1031 }
1032 
Binder_destroy(void * rawJbh)1033 static void Binder_destroy(void* rawJbh)
1034 {
1035     JavaBBinderHolder* jbh = (JavaBBinderHolder*) rawJbh;
1036     ALOGV("Java Binder: deleting holder %p", jbh);
1037     delete jbh;
1038 }
1039 
android_os_Binder_getNativeFinalizer(JNIEnv *,jclass)1040 JNIEXPORT jlong JNICALL android_os_Binder_getNativeFinalizer(JNIEnv*, jclass) {
1041     return (jlong) Binder_destroy;
1042 }
1043 
android_os_Binder_blockUntilThreadAvailable(JNIEnv * env,jobject clazz)1044 static void android_os_Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz)
1045 {
1046     return IPCThreadState::self()->blockUntilThreadAvailable();
1047 }
1048 
android_os_Binder_getExtension(JNIEnv * env,jobject obj)1049 static jobject android_os_Binder_getExtension(JNIEnv* env, jobject obj) {
1050     JavaBBinderHolder* jbh = (JavaBBinderHolder*) env->GetLongField(obj, gBinderOffsets.mObject);
1051     return javaObjectForIBinder(env, jbh->getExtension());
1052 }
1053 
android_os_Binder_setExtension(JNIEnv * env,jobject obj,jobject extensionObject)1054 static void android_os_Binder_setExtension(JNIEnv* env, jobject obj, jobject extensionObject) {
1055     JavaBBinderHolder* jbh = (JavaBBinderHolder*) env->GetLongField(obj, gBinderOffsets.mObject);
1056     sp<IBinder> extension = ibinderForJavaObject(env, extensionObject);
1057     jbh->setExtension(extension);
1058 }
1059 
1060 // ----------------------------------------------------------------------------
1061 
1062 // clang-format off
1063 static const JNINativeMethod gBinderMethods[] = {
1064      /* name, signature, funcPtr */
1065     // @CriticalNative
1066     { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
1067     // @CriticalNative
1068     { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
1069     // @CriticalNative
1070     { "isDirectlyHandlingTransaction", "()Z", (void*)android_os_Binder_isDirectlyHandlingTransaction },
1071     // @CriticalNative
1072     { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
1073     // @CriticalNative
1074     { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
1075     // @CriticalNative
1076     { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
1077     // @CriticalNative
1078     { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
1079     // @CriticalNative
1080     { "setCallingWorkSourceUid", "(I)J", (void*)android_os_Binder_setCallingWorkSourceUid },
1081     // @CriticalNative
1082     { "getCallingWorkSourceUid", "()I", (void*)android_os_Binder_getCallingWorkSourceUid },
1083     // @CriticalNative
1084     { "clearCallingWorkSource", "()J", (void*)android_os_Binder_clearCallingWorkSource },
1085     { "restoreCallingWorkSource", "(J)V", (void*)android_os_Binder_restoreCallingWorkSource },
1086     { "markVintfStability", "()V", (void*)android_os_Binder_markVintfStability},
1087     { "forceDowngradeToSystemStability", "()V", (void*)android_os_Binder_forceDowngradeToSystemStability},
1088     { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
1089     { "getNativeBBinderHolder", "()J", (void*)android_os_Binder_getNativeBBinderHolder },
1090     { "getNativeFinalizer", "()J", (void*)android_os_Binder_getNativeFinalizer },
1091     { "blockUntilThreadAvailable", "()V", (void*)android_os_Binder_blockUntilThreadAvailable },
1092     { "getExtension", "()Landroid/os/IBinder;", (void*)android_os_Binder_getExtension },
1093     { "setExtension", "(Landroid/os/IBinder;)V", (void*)android_os_Binder_setExtension },
1094 };
1095 // clang-format on
1096 
1097 const char* const kBinderPathName = "android/os/Binder";
1098 
int_register_android_os_Binder(JNIEnv * env)1099 static int int_register_android_os_Binder(JNIEnv* env)
1100 {
1101     jclass clazz = FindClassOrDie(env, kBinderPathName);
1102 
1103     gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1104     gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
1105     gBinderOffsets.mGetInterfaceDescriptor = GetMethodIDOrDie(env, clazz, "getInterfaceDescriptor",
1106         "()Ljava/lang/String;");
1107     gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
1108 
1109     return RegisterMethodsOrDie(
1110         env, kBinderPathName,
1111         gBinderMethods, NELEM(gBinderMethods));
1112 }
1113 
1114 // ****************************************************************************
1115 // ****************************************************************************
1116 // ****************************************************************************
1117 
1118 namespace android {
1119 
android_os_Debug_getLocalObjectCount(JNIEnv * env,jobject clazz)1120 jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
1121 {
1122     return gNumLocalRefsCreated - gNumLocalRefsDeleted;
1123 }
1124 
android_os_Debug_getProxyObjectCount(JNIEnv * env,jobject clazz)1125 jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
1126 {
1127     return gNumProxies.load();
1128 }
1129 
android_os_Debug_getDeathObjectCount(JNIEnv * env,jobject clazz)1130 jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
1131 {
1132     return gNumDeathRefsCreated - gNumDeathRefsDeleted;
1133 }
1134 
1135 }
1136 
1137 // ****************************************************************************
1138 // ****************************************************************************
1139 // ****************************************************************************
1140 
android_os_BinderInternal_getContextObject(JNIEnv * env,jobject clazz)1141 static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
1142 {
1143     sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1144     return javaObjectForIBinder(env, b);
1145 }
1146 
android_os_BinderInternal_joinThreadPool(JNIEnv * env,jobject clazz)1147 static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
1148 {
1149     sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1150     android::IPCThreadState::self()->joinThreadPool();
1151 }
1152 
android_os_BinderInternal_disableBackgroundScheduling(JNIEnv * env,jobject clazz,jboolean disable)1153 static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
1154         jobject clazz, jboolean disable)
1155 {
1156     IPCThreadState::disableBackgroundScheduling(disable ? true : false);
1157 }
1158 
android_os_BinderInternal_setMaxThreads(JNIEnv * env,jobject clazz,jint maxThreads)1159 static void android_os_BinderInternal_setMaxThreads(JNIEnv* env,
1160         jobject clazz, jint maxThreads)
1161 {
1162     ProcessState::self()->setThreadPoolMaxThreadCount(maxThreads);
1163 }
1164 
android_os_BinderInternal_handleGc(JNIEnv * env,jobject clazz)1165 static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
1166 {
1167     ALOGV("Gc has executed, updating Refs count at GC");
1168     gCollectedAtRefs = gNumLocalRefsCreated + gNumDeathRefsCreated;
1169 }
1170 
android_os_BinderInternal_proxyLimitcallback(int uid)1171 static void android_os_BinderInternal_proxyLimitcallback(int uid)
1172 {
1173     JNIEnv *env = AndroidRuntime::getJNIEnv();
1174     env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
1175                               gBinderInternalOffsets.mProxyLimitCallback,
1176                               uid);
1177 
1178     if (env->ExceptionCheck()) {
1179         ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
1180         binder_report_exception(env, excep.get(),
1181                                 "*** Uncaught exception in binderProxyLimitCallbackFromNative");
1182     }
1183 }
1184 
android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv * env,jobject clazz,jboolean enable)1185 static void android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv* env, jobject clazz,
1186                                                                  jboolean enable)
1187 {
1188     BpBinder::setCountByUidEnabled((bool) enable);
1189 }
1190 
android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv * env,jclass clazz)1191 static jobject android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv* env, jclass clazz)
1192 {
1193     Vector<uint32_t> uids, counts;
1194     BpBinder::getCountByUid(uids, counts);
1195     jobject sparseIntArray = env->NewObject(gSparseIntArrayOffsets.classObject,
1196                                             gSparseIntArrayOffsets.constructor);
1197     for (size_t i = 0; i < uids.size(); i++) {
1198         env->CallVoidMethod(sparseIntArray, gSparseIntArrayOffsets.put,
1199                             static_cast<jint>(uids[i]), static_cast<jint>(counts[i]));
1200     }
1201     return sparseIntArray;
1202 }
1203 
android_os_BinderInternal_getBinderProxyCount(JNIEnv * env,jobject clazz,jint uid)1204 static jint android_os_BinderInternal_getBinderProxyCount(JNIEnv* env, jobject clazz, jint uid) {
1205     return static_cast<jint>(BpBinder::getBinderProxyCount(static_cast<uint32_t>(uid)));
1206 }
1207 
android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv * env,jobject clazz,jint high,jint low)1208 static void android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv* env, jobject clazz,
1209                                                                     jint high, jint low)
1210 {
1211     BpBinder::setBinderProxyCountWatermarks(high, low);
1212 }
1213 
1214 // ----------------------------------------------------------------------------
1215 
1216 static const JNINativeMethod gBinderInternalMethods[] = {
1217      /* name, signature, funcPtr */
1218     { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
1219     { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
1220     { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
1221     { "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
1222     { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
1223     { "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
1224     { "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
1225     { "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
1226     { "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
1227 };
1228 
1229 const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
1230 
int_register_android_os_BinderInternal(JNIEnv * env)1231 static int int_register_android_os_BinderInternal(JNIEnv* env)
1232 {
1233     jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
1234 
1235     gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1236     gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
1237     gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
1238 
1239     jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
1240     gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
1241     gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
1242                                                            "<init>", "()V");
1243     gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
1244                                                    "(II)V");
1245 
1246     BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
1247 
1248     return RegisterMethodsOrDie(
1249         env, kBinderInternalPathName,
1250         gBinderInternalMethods, NELEM(gBinderInternalMethods));
1251 }
1252 
1253 // ****************************************************************************
1254 // ****************************************************************************
1255 // ****************************************************************************
1256 
android_os_BinderProxy_pingBinder(JNIEnv * env,jobject obj)1257 static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
1258 {
1259     IBinder* target = getBPNativeData(env, obj)->mObject.get();
1260     if (target == NULL) {
1261         return JNI_FALSE;
1262     }
1263     status_t err = target->pingBinder();
1264     return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
1265 }
1266 
android_os_BinderProxy_getInterfaceDescriptor(JNIEnv * env,jobject obj)1267 static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
1268 {
1269     IBinder* target = getBPNativeData(env, obj)->mObject.get();
1270     if (target != NULL) {
1271         const String16& desc = target->getInterfaceDescriptor();
1272         return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
1273                               desc.size());
1274     }
1275     jniThrowException(env, "java/lang/RuntimeException",
1276             "No binder found for object");
1277     return NULL;
1278 }
1279 
android_os_BinderProxy_isBinderAlive(JNIEnv * env,jobject obj)1280 static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
1281 {
1282     IBinder* target = getBPNativeData(env, obj)->mObject.get();
1283     if (target == NULL) {
1284         return JNI_FALSE;
1285     }
1286     bool alive = target->isBinderAlive();
1287     return alive ? JNI_TRUE : JNI_FALSE;
1288 }
1289 
getprocname(pid_t pid,char * buf,size_t len)1290 static int getprocname(pid_t pid, char *buf, size_t len) {
1291     char filename[32];
1292     FILE *f;
1293 
1294     snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
1295     f = fopen(filename, "re");
1296     if (!f) {
1297         *buf = '\0';
1298         return 1;
1299     }
1300     if (!fgets(buf, len, f)) {
1301         *buf = '\0';
1302         fclose(f);
1303         return 2;
1304     }
1305     fclose(f);
1306     return 0;
1307 }
1308 
push_eventlog_string(char ** pos,const char * end,const char * str)1309 static bool push_eventlog_string(char** pos, const char* end, const char* str) {
1310     jint len = strlen(str);
1311     int space_needed = 1 + sizeof(len) + len;
1312     if (end - *pos < space_needed) {
1313         ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
1314              end - *pos, space_needed);
1315         return false;
1316     }
1317     **pos = EVENT_TYPE_STRING;
1318     (*pos)++;
1319     memcpy(*pos, &len, sizeof(len));
1320     *pos += sizeof(len);
1321     memcpy(*pos, str, len);
1322     *pos += len;
1323     return true;
1324 }
1325 
push_eventlog_int(char ** pos,const char * end,jint val)1326 static bool push_eventlog_int(char** pos, const char* end, jint val) {
1327     int space_needed = 1 + sizeof(val);
1328     if (end - *pos < space_needed) {
1329         ALOGW("not enough space for int.  remain=%" PRIdPTR "; needed=%d",
1330              end - *pos, space_needed);
1331         return false;
1332     }
1333     **pos = EVENT_TYPE_INT;
1334     (*pos)++;
1335     memcpy(*pos, &val, sizeof(val));
1336     *pos += sizeof(val);
1337     return true;
1338 }
1339 
1340 // From frameworks/base/core/java/android/content/EventLogTags.logtags:
1341 
1342 static const bool kEnableBinderSample = false;
1343 
1344 #define LOGTAG_BINDER_OPERATION 52004
1345 
conditionally_log_binder_call(int64_t start_millis,IBinder * target,jint code)1346 static void conditionally_log_binder_call(int64_t start_millis,
1347                                           IBinder* target, jint code) {
1348     int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1349 
1350     int sample_percent;
1351     if (duration_ms >= 500) {
1352         sample_percent = 100;
1353     } else {
1354         sample_percent = 100 * duration_ms / 500;
1355         if (sample_percent == 0) {
1356             return;
1357         }
1358         if (sample_percent < (random() % 100 + 1)) {
1359             return;
1360         }
1361     }
1362 
1363     char process_name[40];
1364     getprocname(getpid(), process_name, sizeof(process_name));
1365     String8 desc(target->getInterfaceDescriptor());
1366 
1367     char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1368     buf[0] = EVENT_TYPE_LIST;
1369     buf[1] = 5;
1370     char* pos = &buf[2];
1371     char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1];  // leave room for final \n
1372     if (!push_eventlog_string(&pos, end, desc.string())) return;
1373     if (!push_eventlog_int(&pos, end, code)) return;
1374     if (!push_eventlog_int(&pos, end, duration_ms)) return;
1375     if (!push_eventlog_string(&pos, end, process_name)) return;
1376     if (!push_eventlog_int(&pos, end, sample_percent)) return;
1377     *(pos++) = '\n';   // conventional with EVENT_TYPE_LIST apparently.
1378     android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1379 }
1380 
1381 // We only measure binder call durations to potentially log them if
1382 // we're on the main thread.
should_time_binder_calls()1383 static bool should_time_binder_calls() {
1384   return (getpid() == gettid());
1385 }
1386 
android_os_BinderProxy_transact(JNIEnv * env,jobject obj,jint code,jobject dataObj,jobject replyObj,jint flags)1387 static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
1388         jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
1389 {
1390     if (dataObj == NULL) {
1391         jniThrowNullPointerException(env, NULL);
1392         return JNI_FALSE;
1393     }
1394 
1395     Parcel* data = parcelForJavaObject(env, dataObj);
1396     if (data == NULL) {
1397         return JNI_FALSE;
1398     }
1399     Parcel* reply = parcelForJavaObject(env, replyObj);
1400     if (reply == NULL && replyObj != NULL) {
1401         return JNI_FALSE;
1402     }
1403 
1404     IBinder* target = getBPNativeData(env, obj)->mObject.get();
1405     if (target == NULL) {
1406         jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1407         return JNI_FALSE;
1408     }
1409 
1410     ALOGV("Java code calling transact on %p in Java object %p with code %" PRId32 "\n",
1411             target, obj, code);
1412 
1413 
1414     bool time_binder_calls;
1415     int64_t start_millis;
1416     if (kEnableBinderSample) {
1417         // Only log the binder call duration for things on the Java-level main thread.
1418         // But if we don't
1419         time_binder_calls = should_time_binder_calls();
1420 
1421         if (time_binder_calls) {
1422             start_millis = uptimeMillis();
1423         }
1424     }
1425 
1426     //printf("Transact from Java code to %p sending: ", target); data->print();
1427     status_t err = target->transact(code, *data, reply, flags);
1428     //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
1429 
1430     if (kEnableBinderSample) {
1431         if (time_binder_calls) {
1432             conditionally_log_binder_call(start_millis, target, code);
1433         }
1434     }
1435 
1436     if (err == NO_ERROR) {
1437         return JNI_TRUE;
1438     } else if (err == UNKNOWN_TRANSACTION) {
1439         return JNI_FALSE;
1440     }
1441 
1442     signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
1443     return JNI_FALSE;
1444 }
1445 
android_os_BinderProxy_linkToDeath(JNIEnv * env,jobject obj,jobject recipient,jint flags)1446 static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
1447         jobject recipient, jint flags) // throws RemoteException
1448 {
1449     if (recipient == NULL) {
1450         jniThrowNullPointerException(env, NULL);
1451         return;
1452     }
1453 
1454     BinderProxyNativeData *nd = getBPNativeData(env, obj);
1455     IBinder* target = nd->mObject.get();
1456 
1457     LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
1458 
1459     if (!target->localBinder()) {
1460         DeathRecipientList* list = nd->mOrgue.get();
1461         sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
1462         status_t err = target->linkToDeath(jdr, NULL, flags);
1463         if (err != NO_ERROR) {
1464             // Failure adding the death recipient, so clear its reference
1465             // now.
1466             jdr->clearReference();
1467             signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
1468         }
1469     }
1470 }
1471 
android_os_BinderProxy_unlinkToDeath(JNIEnv * env,jobject obj,jobject recipient,jint flags)1472 static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1473                                                  jobject recipient, jint flags)
1474 {
1475     jboolean res = JNI_FALSE;
1476     if (recipient == NULL) {
1477         jniThrowNullPointerException(env, NULL);
1478         return res;
1479     }
1480 
1481     BinderProxyNativeData* nd = getBPNativeData(env, obj);
1482     IBinder* target = nd->mObject.get();
1483     if (target == NULL) {
1484         ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
1485         return JNI_FALSE;
1486     }
1487 
1488     LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
1489 
1490     if (!target->localBinder()) {
1491         status_t err = NAME_NOT_FOUND;
1492 
1493         // If we find the matching recipient, proceed to unlink using that
1494         DeathRecipientList* list = nd->mOrgue.get();
1495         sp<JavaDeathRecipient> origJDR = list->find(recipient);
1496         LOGDEATH("   unlink found list %p and JDR %p", list, origJDR.get());
1497         if (origJDR != NULL) {
1498             wp<IBinder::DeathRecipient> dr;
1499             err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1500             if (err == NO_ERROR && dr != NULL) {
1501                 sp<IBinder::DeathRecipient> sdr = dr.promote();
1502                 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1503                 if (jdr != NULL) {
1504                     jdr->clearReference();
1505                 }
1506             }
1507         }
1508 
1509         if (err == NO_ERROR || err == DEAD_OBJECT) {
1510             res = JNI_TRUE;
1511         } else {
1512             jniThrowException(env, "java/util/NoSuchElementException",
1513                               base::StringPrintf("Death link does not exist (%s)",
1514                                                  statusToString(err).c_str())
1515                                       .c_str());
1516         }
1517     }
1518 
1519     return res;
1520 }
1521 
BinderProxy_destroy(void * rawNativeData)1522 static void BinderProxy_destroy(void* rawNativeData)
1523 {
1524     BinderProxyNativeData * nativeData = (BinderProxyNativeData *) rawNativeData;
1525     LOGDEATH("Destroying BinderProxy: binder=%p drl=%p\n",
1526             nativeData->mObject.get(), nativeData->mOrgue.get());
1527     delete nativeData;
1528     IPCThreadState::self()->flushCommands();
1529     --gNumProxies;
1530 }
1531 
android_os_BinderProxy_getNativeFinalizer(JNIEnv *,jclass)1532 JNIEXPORT jlong JNICALL android_os_BinderProxy_getNativeFinalizer(JNIEnv*, jclass) {
1533     return (jlong) BinderProxy_destroy;
1534 }
1535 
android_os_BinderProxy_getExtension(JNIEnv * env,jobject obj)1536 static jobject android_os_BinderProxy_getExtension(JNIEnv* env, jobject obj) {
1537     IBinder* binder = getBPNativeData(env, obj)->mObject.get();
1538     if (binder == nullptr) {
1539         jniThrowException(env, "java/lang/IllegalStateException", "Native IBinder is null");
1540         return nullptr;
1541     }
1542     sp<IBinder> extension;
1543     status_t err = binder->getExtension(&extension);
1544     if (err != OK) {
1545         signalExceptionForError(env, obj, err, true /* canThrowRemoteException */);
1546         return nullptr;
1547     }
1548     return javaObjectForIBinder(env, extension);
1549 }
1550 
1551 // ----------------------------------------------------------------------------
1552 
1553 static const JNINativeMethod gBinderProxyMethods[] = {
1554      /* name, signature, funcPtr */
1555     {"pingBinder",          "()Z", (void*)android_os_BinderProxy_pingBinder},
1556     {"isBinderAlive",       "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1557     {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
1558     {"transactNative",      "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
1559     {"linkToDeath",         "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1560     {"unlinkToDeath",       "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
1561     {"getNativeFinalizer",  "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
1562     {"getExtension",        "()Landroid/os/IBinder;", (void*)android_os_BinderProxy_getExtension},
1563 };
1564 
1565 const char* const kBinderProxyPathName = "android/os/BinderProxy";
1566 
int_register_android_os_BinderProxy(JNIEnv * env)1567 static int int_register_android_os_BinderProxy(JNIEnv* env)
1568 {
1569     gErrorOffsets.mError = MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/Error"));
1570     gErrorOffsets.mOutOfMemory =
1571         MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/OutOfMemoryError"));
1572     gErrorOffsets.mStackOverflow =
1573         MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/StackOverflowError"));
1574 
1575     jclass clazz = FindClassOrDie(env, kBinderProxyPathName);
1576     gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1577     gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance",
1578             "(JJ)Landroid/os/BinderProxy;");
1579     gBinderProxyOffsets.mSendDeathNotice =
1580             GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
1581                                    "(Landroid/os/IBinder$DeathRecipient;Landroid/os/IBinder;)V");
1582     gBinderProxyOffsets.mNativeData = GetFieldIDOrDie(env, clazz, "mNativeData", "J");
1583 
1584     clazz = FindClassOrDie(env, "java/lang/Class");
1585     gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
1586 
1587     return RegisterMethodsOrDie(
1588         env, kBinderProxyPathName,
1589         gBinderProxyMethods, NELEM(gBinderProxyMethods));
1590 }
1591 
1592 // ****************************************************************************
1593 // ****************************************************************************
1594 // ****************************************************************************
1595 
register_android_os_Binder(JNIEnv * env)1596 int register_android_os_Binder(JNIEnv* env)
1597 {
1598     if (int_register_android_os_Binder(env) < 0)
1599         return -1;
1600     if (int_register_android_os_BinderInternal(env) < 0)
1601         return -1;
1602     if (int_register_android_os_BinderProxy(env) < 0)
1603         return -1;
1604 
1605     jclass clazz = FindClassOrDie(env, "android/util/Log");
1606     gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1607     gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
1608             "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
1609 
1610     clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
1611     gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1612     gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
1613                                                                  "(Ljava/io/FileDescriptor;)V");
1614 
1615     clazz = FindClassOrDie(env, "android/os/StrictMode");
1616     gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1617     gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
1618             "onBinderStrictModePolicyChange", "(I)V");
1619 
1620     clazz = FindClassOrDie(env, "java/lang/Thread");
1621     gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1622     gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
1623             "dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
1624     gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
1625             "()Ljava/lang/Thread;");
1626 
1627     return 0;
1628 }
1629