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