Debian Codegraph @

core/jni/android_util_Binder.cpp

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