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