blob: c3ba9ba828268034a650b616e2892ed4bda214f8 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -080020#include "android_os_Parcel.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021#include "android_util_Binder.h"
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -080022
Hans Boehm29f388f2017-10-03 18:01:20 -070023#include <atomic>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024#include <fcntl.h>
Mark Salyzyncfd91e72014-04-17 15:40:01 -070025#include <inttypes.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026#include <stdio.h>
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -070027#include <sys/stat.h>
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -070028#include <sys/types.h>
Brad Fitzpatrick8f26b322010-03-25 00:25:37 -070029#include <unistd.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030
Andreas Gampe58383ba2017-06-12 10:43:05 -070031#include <android-base/stringprintf.h>
Mathias Agopian07952722009-05-19 19:08:10 -070032#include <binder/IInterface.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070033#include <binder/IServiceManager.h>
Mathias Agopian07952722009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070035#include <binder/Parcel.h>
Michael Wachenschwanz55182462017-08-14 23:10:13 -070036#include <binder/BpBinder.h>
Mathias Agopian07952722009-05-19 19:08:10 -070037#include <binder/ProcessState.h>
Steven Morelandfb7952f2018-02-23 14:58:50 -080038#include <cutils/atomic.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070039#include <log/log.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070040#include <utils/KeyedVector.h>
41#include <utils/List.h>
42#include <utils/Log.h>
Jeff Brown0bde66a2011-11-07 12:50:08 -080043#include <utils/String8.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070044#include <utils/SystemClock.h>
45#include <utils/threads.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
Andreas Gampe625e0002017-09-08 17:44:05 -070047#include <nativehelper/JNIHelp.h>
Steven Moreland2279b252017-07-19 09:50:45 -070048#include <nativehelper/ScopedLocalRef.h>
Andreas Gampe625e0002017-09-08 17:44:05 -070049#include <nativehelper/ScopedUtfChars.h>
Christopher Tateac5e3502011-08-25 15:48:09 -070050
Andreas Gampe987f79f2014-11-18 17:29:46 -080051#include "core_jni_helpers.h"
52
Steve Block71f2cf12011-10-20 11:56:00 +010053//#undef ALOGV
54//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
Christopher Tate79dd31f2011-03-04 17:45:00 -080056#define DEBUG_DEATH 0
57#if DEBUG_DEATH
Steve Block5baa3a62011-12-20 16:23:08 +000058#define LOGDEATH ALOGD
Christopher Tate79dd31f2011-03-04 17:45:00 -080059#else
Steve Block71f2cf12011-10-20 11:56:00 +010060#define LOGDEATH ALOGV
Christopher Tate79dd31f2011-03-04 17:45:00 -080061#endif
62
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063using namespace android;
64
65// ----------------------------------------------------------------------------
66
67static struct bindernative_offsets_t
68{
69 // Class state.
70 jclass mClass;
71 jmethodID mExecTransact;
72
73 // Object state.
74 jfieldID mObject;
75
76} gBinderOffsets;
77
78// ----------------------------------------------------------------------------
79
80static struct binderinternal_offsets_t
81{
82 // Class state.
83 jclass mClass;
84 jmethodID mForceGc;
Michael Wachenschwanz55182462017-08-14 23:10:13 -070085 jmethodID mProxyLimitCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87} gBinderInternalOffsets;
88
Michael Wachenschwanz55182462017-08-14 23:10:13 -070089static struct sparseintarray_offsets_t
90{
91 jclass classObject;
92 jmethodID constructor;
93 jmethodID put;
94} gSparseIntArrayOffsets;
95
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096// ----------------------------------------------------------------------------
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098static struct error_offsets_t
99{
100 jclass mClass;
101} gErrorOffsets;
102
103// ----------------------------------------------------------------------------
104
105static struct binderproxy_offsets_t
106{
107 // Class state.
108 jclass mClass;
Hans Boehm29f388f2017-10-03 18:01:20 -0700109 jmethodID mGetInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 jmethodID mSendDeathNotice;
Martijn Coenendfa390e2018-06-05 11:02:23 +0200111 jmethodID mDumpProxyDebugInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
113 // Object state.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700114 jfieldID mNativeData; // Field holds native pointer to BinderProxyNativeData.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115} gBinderProxyOffsets;
116
Christopher Tate0d4a7922011-08-30 12:09:43 -0700117static struct class_offsets_t
118{
119 jmethodID mGetName;
120} gClassOffsets;
121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122// ----------------------------------------------------------------------------
123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124static struct log_offsets_t
125{
126 // Class state.
127 jclass mClass;
128 jmethodID mLogE;
129} gLogOffsets;
130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131static struct parcel_file_descriptor_offsets_t
132{
133 jclass mClass;
134 jmethodID mConstructor;
135} gParcelFileDescriptorOffsets;
136
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700137static struct strict_mode_callback_offsets_t
138{
139 jclass mClass;
140 jmethodID mCallback;
141} gStrictModeCallbackOffsets;
142
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700143static struct thread_dispatch_offsets_t
144{
145 // Class state.
146 jclass mClass;
147 jmethodID mDispatchUncaughtException;
148 jmethodID mCurrentThread;
149} gThreadDispatchOffsets;
150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151// ****************************************************************************
152// ****************************************************************************
153// ****************************************************************************
154
Hans Boehm29f388f2017-10-03 18:01:20 -0700155static constexpr int32_t PROXY_WARN_INTERVAL = 5000;
156static constexpr uint32_t GC_INTERVAL = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Hans Boehm29f388f2017-10-03 18:01:20 -0700158// Protected by gProxyLock. We warn if this gets too large.
159static int32_t gNumProxies = 0;
160static int32_t gProxiesWarned = 0;
161
162// Number of GlobalRefs held by JavaBBinders.
163static std::atomic<uint32_t> gNumLocalRefsCreated(0);
164static std::atomic<uint32_t> gNumLocalRefsDeleted(0);
165// Number of GlobalRefs held by JavaDeathRecipients.
166static std::atomic<uint32_t> gNumDeathRefsCreated(0);
167static std::atomic<uint32_t> gNumDeathRefsDeleted(0);
168
169// We collected after creating this many refs.
170static std::atomic<uint32_t> gCollectedAtRefs(0);
171
172// Garbage collect if we've allocated at least GC_INTERVAL refs since the last time.
173// TODO: Consider removing this completely. We should no longer be generating GlobalRefs
174// that are reclaimed as a result of GC action.
Ivan Lozano2ea71352017-11-02 14:10:57 -0700175__attribute__((no_sanitize("unsigned-integer-overflow")))
Hans Boehm29f388f2017-10-03 18:01:20 -0700176static void gcIfManyNewRefs(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177{
Hans Boehm29f388f2017-10-03 18:01:20 -0700178 uint32_t totalRefs = gNumLocalRefsCreated.load(std::memory_order_relaxed)
179 + gNumDeathRefsCreated.load(std::memory_order_relaxed);
180 uint32_t collectedAtRefs = gCollectedAtRefs.load(memory_order_relaxed);
181 // A bound on the number of threads that can have incremented gNum...RefsCreated before the
182 // following check is executed. Effectively a bound on #threads. Almost any value will do.
183 static constexpr uint32_t MAX_RACING = 100000;
184
185 if (totalRefs - (collectedAtRefs + GC_INTERVAL) /* modular arithmetic! */ < MAX_RACING) {
186 // Recently passed next GC interval.
187 if (gCollectedAtRefs.compare_exchange_strong(collectedAtRefs,
188 collectedAtRefs + GC_INTERVAL, std::memory_order_relaxed)) {
189 ALOGV("Binder forcing GC at %u created refs", totalRefs);
190 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
191 gBinderInternalOffsets.mForceGc);
192 } // otherwise somebody else beat us to it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 } else {
Hans Boehm29f388f2017-10-03 18:01:20 -0700194 ALOGV("Now have %d binder ops", totalRefs - collectedAtRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 }
196}
197
198static JavaVM* jnienv_to_javavm(JNIEnv* env)
199{
200 JavaVM* vm;
201 return env->GetJavaVM(&vm) >= 0 ? vm : NULL;
202}
203
204static JNIEnv* javavm_to_jnienv(JavaVM* vm)
205{
206 JNIEnv* env;
207 return vm->GetEnv((void **)&env, JNI_VERSION_1_4) >= 0 ? env : NULL;
208}
209
Andreas Gampe625e0002017-09-08 17:44:05 -0700210// Report a java.lang.Error (or subclass). This will terminate the runtime by
211// calling FatalError with a message derived from the given error.
212static void report_java_lang_error_fatal_error(JNIEnv* env, jthrowable error,
213 const char* msg)
214{
215 // Report an error: reraise the exception and ask the runtime to abort.
216
217 // Try to get the exception string. Sometimes logcat isn't available,
218 // so try to add it to the abort message.
219 std::string exc_msg = "(Unknown exception message)";
220 {
221 ScopedLocalRef<jclass> exc_class(env, env->GetObjectClass(error));
222 jmethodID method_id = env->GetMethodID(exc_class.get(), "toString",
223 "()Ljava/lang/String;");
224 ScopedLocalRef<jstring> jstr(
225 env,
226 reinterpret_cast<jstring>(
227 env->CallObjectMethod(error, method_id)));
228 env->ExceptionClear(); // Just for good measure.
229 if (jstr.get() != nullptr) {
230 ScopedUtfChars jstr_utf(env, jstr.get());
231 if (jstr_utf.c_str() != nullptr) {
232 exc_msg = jstr_utf.c_str();
233 } else {
234 env->ExceptionClear();
235 }
236 }
237 }
238
239 env->Throw(error);
240 ALOGE("java.lang.Error thrown during binder transaction (stack trace follows) : ");
241 env->ExceptionDescribe();
242
243 std::string error_msg = base::StringPrintf(
244 "java.lang.Error thrown during binder transaction: %s",
245 exc_msg.c_str());
246 env->FatalError(error_msg.c_str());
247}
248
249// Report a java.lang.Error (or subclass). This will terminate the runtime, either by
250// the uncaught exception handler, or explicitly by calling
251// report_java_lang_error_fatal_error.
252static void report_java_lang_error(JNIEnv* env, jthrowable error, const char* msg)
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700253{
254 // Try to run the uncaught exception machinery.
255 jobject thread = env->CallStaticObjectMethod(gThreadDispatchOffsets.mClass,
256 gThreadDispatchOffsets.mCurrentThread);
257 if (thread != nullptr) {
258 env->CallVoidMethod(thread, gThreadDispatchOffsets.mDispatchUncaughtException,
259 error);
260 // Should not return here, unless more errors occured.
261 }
262 // Some error occurred that meant that either dispatchUncaughtException could not be
263 // called or that it had an error itself (as this should be unreachable under normal
Andreas Gampe625e0002017-09-08 17:44:05 -0700264 // conditions). As the binder code cannot handle Errors, attempt to log the error and
265 // abort.
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700266 env->ExceptionClear();
Andreas Gampe625e0002017-09-08 17:44:05 -0700267 report_java_lang_error_fatal_error(env, error, msg);
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700268}
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270static void report_exception(JNIEnv* env, jthrowable excep, const char* msg)
271{
272 env->ExceptionClear();
273
Andreas Gampe625e0002017-09-08 17:44:05 -0700274 ScopedLocalRef<jstring> tagstr(env, env->NewStringUTF(LOG_TAG));
Andreas Gampe8571ec32017-09-21 10:55:59 -0700275 ScopedLocalRef<jstring> msgstr(env);
Andreas Gampe625e0002017-09-08 17:44:05 -0700276 if (tagstr != nullptr) {
277 msgstr.reset(env->NewStringUTF(msg));
Mathieu Chartiercf6775e2014-08-06 13:39:17 -0700278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279
Andreas Gampe625e0002017-09-08 17:44:05 -0700280 if ((tagstr != nullptr) && (msgstr != nullptr)) {
281 env->CallStaticIntMethod(gLogOffsets.mClass, gLogOffsets.mLogE,
282 tagstr.get(), msgstr.get(), excep);
283 if (env->ExceptionCheck()) {
284 // Attempting to log the failure has failed.
285 ALOGW("Failed trying to log exception, msg='%s'\n", msg);
286 env->ExceptionClear();
287 }
288 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 env->ExceptionClear(); /* assume exception (OOM?) was thrown */
Steve Block3762c312012-01-06 19:20:56 +0000290 ALOGE("Unable to call Log.e()\n");
291 ALOGE("%s", msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293
294 if (env->IsInstanceOf(excep, gErrorOffsets.mClass)) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700295 report_java_lang_error(env, excep, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297}
298
299class JavaBBinderHolder;
300
301class JavaBBinder : public BBinder
302{
303public:
Hans Boehm29f388f2017-10-03 18:01:20 -0700304 JavaBBinder(JNIEnv* env, jobject /* Java Binder */ object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))
306 {
Steve Block71f2cf12011-10-20 11:56:00 +0100307 ALOGV("Creating JavaBBinder %p\n", this);
Hans Boehm29f388f2017-10-03 18:01:20 -0700308 gNumLocalRefsCreated.fetch_add(1, std::memory_order_relaxed);
309 gcIfManyNewRefs(env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 }
311
312 bool checkSubclass(const void* subclassID) const
313 {
314 return subclassID == &gBinderOffsets;
315 }
316
317 jobject object() const
318 {
319 return mObject;
320 }
321
322protected:
323 virtual ~JavaBBinder()
324 {
Steve Block71f2cf12011-10-20 11:56:00 +0100325 ALOGV("Destroying JavaBBinder %p\n", this);
Hans Boehm29f388f2017-10-03 18:01:20 -0700326 gNumLocalRefsDeleted.fetch_add(1, memory_order_relaxed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 JNIEnv* env = javavm_to_jnienv(mVM);
328 env->DeleteGlobalRef(mObject);
329 }
330
331 virtual status_t onTransact(
332 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0)
333 {
334 JNIEnv* env = javavm_to_jnienv(mVM);
335
Steve Block71f2cf12011-10-20 11:56:00 +0100336 ALOGV("onTransact() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700338 IPCThreadState* thread_state = IPCThreadState::self();
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700339 const int32_t strict_policy_before = thread_state->getStrictModePolicy();
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 //printf("Transact from %p to Java code sending: ", this);
342 //data.print();
343 //printf("\n");
344 jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000345 code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700346
Mathieu Chartier98671c32014-08-20 10:04:08 -0700347 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700348 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
349 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100350 "*** Uncaught remote exception! "
351 "(Exceptions are not yet supported across processes.)");
352 res = JNI_FALSE;
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100353 }
354
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700355 // Check if the strict mode state changed while processing the
356 // call. The Binder state will be restored by the underlying
357 // Binder system in IPCThreadState, however we need to take care
358 // of the parallel Java state as well.
359 if (thread_state->getStrictModePolicy() != strict_policy_before) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700360 set_dalvik_blockguard_policy(env, strict_policy_before);
361 }
362
Mathieu Chartier98671c32014-08-20 10:04:08 -0700363 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700364 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
365 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100366 "*** Uncaught exception in onBinderStrictModePolicyChange");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 }
368
Dianne Hackborna53de062012-05-08 18:53:51 -0700369 // Need to always call through the native implementation of
370 // SYSPROPS_TRANSACTION.
371 if (code == SYSPROPS_TRANSACTION) {
372 BBinder::onTransact(code, data, reply, flags);
373 }
374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 //aout << "onTransact to Java code; result=" << res << endl
376 // << "Transact from " << this << " to Java code returning "
377 // << reply << ": " << *reply << endl;
378 return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
379 }
380
381 virtual status_t dump(int fd, const Vector<String16>& args)
382 {
383 return 0;
384 }
385
386private:
387 JavaVM* const mVM;
Hans Boehm29f388f2017-10-03 18:01:20 -0700388 jobject const mObject; // GlobalRef to Java Binder
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389};
390
391// ----------------------------------------------------------------------------
392
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700393class JavaBBinderHolder
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394{
395public:
Christopher Tate0b414482011-02-17 13:00:38 -0800396 sp<JavaBBinder> get(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397 {
398 AutoMutex _l(mLock);
399 sp<JavaBBinder> b = mBinder.promote();
400 if (b == NULL) {
Christopher Tate0b414482011-02-17 13:00:38 -0800401 b = new JavaBBinder(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 mBinder = b;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700403 ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
Christopher Tate0b414482011-02-17 13:00:38 -0800404 b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 }
406
407 return b;
408 }
409
410 sp<JavaBBinder> getExisting()
411 {
412 AutoMutex _l(mLock);
413 return mBinder.promote();
414 }
415
416private:
417 Mutex mLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 wp<JavaBBinder> mBinder;
419};
420
421// ----------------------------------------------------------------------------
422
Christopher Tate0b414482011-02-17 13:00:38 -0800423// Per-IBinder death recipient bookkeeping. This is how we reconcile local jobject
424// death recipient references passed in through JNI with the permanent corresponding
425// JavaDeathRecipient objects.
426
427class JavaDeathRecipient;
428
429class DeathRecipientList : public RefBase {
430 List< sp<JavaDeathRecipient> > mList;
431 Mutex mLock;
432
433public:
Christopher Tate79dd31f2011-03-04 17:45:00 -0800434 DeathRecipientList();
Christopher Tate0b414482011-02-17 13:00:38 -0800435 ~DeathRecipientList();
436
437 void add(const sp<JavaDeathRecipient>& recipient);
438 void remove(const sp<JavaDeathRecipient>& recipient);
439 sp<JavaDeathRecipient> find(jobject recipient);
Christopher Tate090c08f2015-05-19 18:16:58 -0700440
441 Mutex& lock(); // Use with care; specifically for mutual exclusion during binder death
Christopher Tate0b414482011-02-17 13:00:38 -0800442};
443
444// ----------------------------------------------------------------------------
445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446class JavaDeathRecipient : public IBinder::DeathRecipient
447{
448public:
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800449 JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
Christopher Tate86284c62011-08-17 15:19:29 -0700450 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
451 mObjectWeak(NULL), mList(list)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 {
Christopher Tate0b414482011-02-17 13:00:38 -0800453 // These objects manage their own lifetimes so are responsible for final bookkeeping.
454 // The list holds a strong reference to this object.
Christopher Tate79dd31f2011-03-04 17:45:00 -0800455 LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800456 list->add(this);
Christopher Tate0b414482011-02-17 13:00:38 -0800457
Hans Boehm29f388f2017-10-03 18:01:20 -0700458 gNumDeathRefsCreated.fetch_add(1, std::memory_order_relaxed);
459 gcIfManyNewRefs(env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 }
461
462 void binderDied(const wp<IBinder>& who)
463 {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800464 LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
Christopher Tate86284c62011-08-17 15:19:29 -0700465 if (mObject != NULL) {
466 JNIEnv* env = javavm_to_jnienv(mVM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467
Christopher Tate86284c62011-08-17 15:19:29 -0700468 env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
469 gBinderProxyOffsets.mSendDeathNotice, mObject);
Mathieu Chartier98671c32014-08-20 10:04:08 -0700470 if (env->ExceptionCheck()) {
471 jthrowable excep = env->ExceptionOccurred();
Christopher Tate86284c62011-08-17 15:19:29 -0700472 report_exception(env, excep,
473 "*** Uncaught exception returned from death notification!");
474 }
475
Christopher Tate090c08f2015-05-19 18:16:58 -0700476 // Serialize with our containing DeathRecipientList so that we can't
477 // delete the global ref on mObject while the list is being iterated.
478 sp<DeathRecipientList> list = mList.promote();
479 if (list != NULL) {
480 AutoMutex _l(list->lock());
481
482 // Demote from strong ref to weak after binderDied() has been delivered,
483 // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
484 mObjectWeak = env->NewWeakGlobalRef(mObject);
485 env->DeleteGlobalRef(mObject);
486 mObject = NULL;
487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490
491 void clearReference()
492 {
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800493 sp<DeathRecipientList> list = mList.promote();
494 if (list != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800495 LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800496 list->remove(this);
Christopher Tate79dd31f2011-03-04 17:45:00 -0800497 } else {
498 LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800499 }
Christopher Tate0b414482011-02-17 13:00:38 -0800500 }
501
502 bool matches(jobject obj) {
Christopher Tate86284c62011-08-17 15:19:29 -0700503 bool result;
Christopher Tate0b414482011-02-17 13:00:38 -0800504 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700505
506 if (mObject != NULL) {
507 result = env->IsSameObject(obj, mObject);
508 } else {
Andreas Gampe625e0002017-09-08 17:44:05 -0700509 ScopedLocalRef<jobject> me(env, env->NewLocalRef(mObjectWeak));
510 result = env->IsSameObject(obj, me.get());
Christopher Tate86284c62011-08-17 15:19:29 -0700511 }
512 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
514
Christopher Tateac5e3502011-08-25 15:48:09 -0700515 void warnIfStillLive() {
516 if (mObject != NULL) {
517 // Okay, something is wrong -- we have a hard reference to a live death
518 // recipient on the VM side, but the list is being torn down.
519 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate0d4a7922011-08-30 12:09:43 -0700520 ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
521 ScopedLocalRef<jstring> nameRef(env,
522 (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
523 ScopedUtfChars nameUtf(env, nameRef.get());
524 if (nameUtf.c_str() != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000525 ALOGW("BinderProxy is being destroyed but the application did not call "
Christopher Tate0d4a7922011-08-30 12:09:43 -0700526 "unlinkToDeath to unlink all of its death recipients beforehand. "
527 "Releasing leaked death recipient: %s", nameUtf.c_str());
528 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000529 ALOGW("BinderProxy being destroyed; unable to get DR object name");
Christopher Tate0d4a7922011-08-30 12:09:43 -0700530 env->ExceptionClear();
531 }
Christopher Tateac5e3502011-08-25 15:48:09 -0700532 }
533 }
534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535protected:
536 virtual ~JavaDeathRecipient()
537 {
Steve Block6215d3f2012-01-04 20:05:49 +0000538 //ALOGI("Removing death ref: recipient=%p\n", mObject);
Hans Boehm29f388f2017-10-03 18:01:20 -0700539 gNumDeathRefsDeleted.fetch_add(1, std::memory_order_relaxed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700541 if (mObject != NULL) {
542 env->DeleteGlobalRef(mObject);
543 } else {
544 env->DeleteWeakGlobalRef(mObjectWeak);
545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 }
547
548private:
Christopher Tate86284c62011-08-17 15:19:29 -0700549 JavaVM* const mVM;
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700550 jobject mObject; // Initial strong ref to Java-side DeathRecipient. Cleared on binderDied().
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700551 jweak mObjectWeak; // Weak ref to the same Java-side DeathRecipient after binderDied().
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800552 wp<DeathRecipientList> mList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553};
554
555// ----------------------------------------------------------------------------
556
Christopher Tate79dd31f2011-03-04 17:45:00 -0800557DeathRecipientList::DeathRecipientList() {
558 LOGDEATH("New DRL @ %p", this);
559}
560
Christopher Tate0b414482011-02-17 13:00:38 -0800561DeathRecipientList::~DeathRecipientList() {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800562 LOGDEATH("Destroy DRL @ %p", this);
Christopher Tate0b414482011-02-17 13:00:38 -0800563 AutoMutex _l(mLock);
564
565 // Should never happen -- the JavaDeathRecipient objects that have added themselves
566 // to the list are holding references on the list object. Only when they are torn
567 // down can the list header be destroyed.
568 if (mList.size() > 0) {
Christopher Tateac5e3502011-08-25 15:48:09 -0700569 List< sp<JavaDeathRecipient> >::iterator iter;
570 for (iter = mList.begin(); iter != mList.end(); iter++) {
571 (*iter)->warnIfStillLive();
572 }
Christopher Tate0b414482011-02-17 13:00:38 -0800573 }
574}
575
576void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
577 AutoMutex _l(mLock);
578
Christopher Tate79dd31f2011-03-04 17:45:00 -0800579 LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800580 mList.push_back(recipient);
581}
582
583void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
584 AutoMutex _l(mLock);
585
586 List< sp<JavaDeathRecipient> >::iterator iter;
587 for (iter = mList.begin(); iter != mList.end(); iter++) {
588 if (*iter == recipient) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800589 LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800590 mList.erase(iter);
591 return;
592 }
593 }
594}
595
596sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
597 AutoMutex _l(mLock);
598
599 List< sp<JavaDeathRecipient> >::iterator iter;
600 for (iter = mList.begin(); iter != mList.end(); iter++) {
601 if ((*iter)->matches(recipient)) {
602 return *iter;
603 }
604 }
605 return NULL;
606}
607
Christopher Tate090c08f2015-05-19 18:16:58 -0700608Mutex& DeathRecipientList::lock() {
609 return mLock;
610}
611
Christopher Tate0b414482011-02-17 13:00:38 -0800612// ----------------------------------------------------------------------------
613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614namespace android {
615
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700616// We aggregate native pointer fields for BinderProxy in a single object to allow
617// management with a single NativeAllocationRegistry, and to reduce the number of JNI
618// Java field accesses. This costs us some extra indirections here.
619struct BinderProxyNativeData {
Hans Boehm29f388f2017-10-03 18:01:20 -0700620 // Both fields are constant and not null once javaObjectForIBinder returns this as
621 // part of a BinderProxy.
622
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700623 // The native IBinder proxied by this BinderProxy.
Hans Boehm29f388f2017-10-03 18:01:20 -0700624 sp<IBinder> mObject;
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700625
626 // Death recipients for mObject. Reference counted only because DeathRecipients
627 // hold a weak reference that can be temporarily promoted.
Hans Boehm29f388f2017-10-03 18:01:20 -0700628 sp<DeathRecipientList> mOrgue; // Death recipients for mObject.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700629};
630
631BinderProxyNativeData* getBPNativeData(JNIEnv* env, jobject obj) {
632 return (BinderProxyNativeData *) env->GetLongField(obj, gBinderProxyOffsets.mNativeData);
633}
634
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700635static Mutex gProxyLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636
Hans Boehm29f388f2017-10-03 18:01:20 -0700637// We may cache a single BinderProxyNativeData node to avoid repeat allocation.
638// All fields are null. Protected by gProxyLock.
639static BinderProxyNativeData *gNativeDataCache;
640
641// If the argument is a JavaBBinder, return the Java object that was used to create it.
642// Otherwise return a BinderProxy for the IBinder. If a previous call was passed the
643// same IBinder, and the original BinderProxy is still alive, return the same BinderProxy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
645{
646 if (val == NULL) return NULL;
647
648 if (val->checkSubclass(&gBinderOffsets)) {
Hans Boehm29f388f2017-10-03 18:01:20 -0700649 // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 jobject object = static_cast<JavaBBinder*>(val.get())->object();
Christopher Tate86284c62011-08-17 15:19:29 -0700651 LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 return object;
653 }
654
655 // For the rest of the function we will hold this lock, to serialize
Christopher Tate10c3a282016-02-26 17:48:08 -0800656 // looking/creation/destruction of Java proxies for native Binder proxies.
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700657 AutoMutex _l(gProxyLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658
Hans Boehm29f388f2017-10-03 18:01:20 -0700659 BinderProxyNativeData* nativeData = gNativeDataCache;
660 if (nativeData == nullptr) {
661 nativeData = new BinderProxyNativeData();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
Hans Boehm29f388f2017-10-03 18:01:20 -0700663 // gNativeDataCache is now logically empty.
664 jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
665 gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
666 if (env->ExceptionCheck()) {
Hans Boehm03477cb2018-02-15 16:12:51 -0800667 // In the exception case, getInstance still took ownership of nativeData.
668 gNativeDataCache = nullptr;
Hans Boehm29f388f2017-10-03 18:01:20 -0700669 return NULL;
670 }
671 BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
672 if (actualNativeData == nativeData) {
673 // New BinderProxy; we still have exclusive access.
674 nativeData->mOrgue = new DeathRecipientList;
675 nativeData->mObject = val;
676 gNativeDataCache = nullptr;
677 ++gNumProxies;
Martijn Coenen5183c0e2018-02-07 10:25:39 +0100678 if (gNumProxies >= gProxiesWarned + PROXY_WARN_INTERVAL) {
Hans Boehm29f388f2017-10-03 18:01:20 -0700679 ALOGW("Unexpectedly many live BinderProxies: %d\n", gNumProxies);
680 gProxiesWarned = gNumProxies;
681 }
682 } else {
683 // nativeData wasn't used. Reuse it the next time.
684 gNativeDataCache = nativeData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 }
686
687 return object;
688}
689
690sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
691{
692 if (obj == NULL) return NULL;
693
Hans Boehm29f388f2017-10-03 18:01:20 -0700694 // Instance of Binder?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
696 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000697 env->GetLongField(obj, gBinderOffsets.mObject);
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700698 return jbh->get(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 }
700
Hans Boehm29f388f2017-10-03 18:01:20 -0700701 // Instance of BinderProxy?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700703 return getBPNativeData(env, obj)->mObject;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 }
705
Steve Block8564c8d2012-01-05 23:22:43 +0000706 ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 return NULL;
708}
709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
711{
712 return env->NewObject(
713 gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
714}
715
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -0800716void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
717{
718 // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
719 // to sync our state back to it. See the comments in StrictMode.java.
720 env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
721 gStrictModeCallbackOffsets.mCallback,
722 strict_policy);
723}
724
725void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
Dianne Hackborne5c42622015-05-19 16:04:04 -0700726 bool canThrowRemoteException, int parcelSize)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727{
728 switch (err) {
729 case UNKNOWN_ERROR:
730 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
731 break;
732 case NO_MEMORY:
733 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
734 break;
735 case INVALID_OPERATION:
736 jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
737 break;
738 case BAD_VALUE:
739 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
740 break;
741 case BAD_INDEX:
742 jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
743 break;
744 case BAD_TYPE:
745 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
746 break;
747 case NAME_NOT_FOUND:
748 jniThrowException(env, "java/util/NoSuchElementException", NULL);
749 break;
750 case PERMISSION_DENIED:
751 jniThrowException(env, "java/lang/SecurityException", NULL);
752 break;
753 case NOT_ENOUGH_DATA:
754 jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
755 break;
756 case NO_INIT:
757 jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
758 break;
759 case ALREADY_EXISTS:
760 jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
761 break;
762 case DEAD_OBJECT:
Jeff Brown0bde66a2011-11-07 12:50:08 -0800763 // DeadObjectException is a checked exception, only throw from certain methods.
764 jniThrowException(env, canThrowRemoteException
765 ? "android/os/DeadObjectException"
766 : "java/lang/RuntimeException", NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 break;
768 case UNKNOWN_TRANSACTION:
769 jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
770 break;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700771 case FAILED_TRANSACTION: {
772 ALOGE("!!! FAILED BINDER TRANSACTION !!! (parcel size = %d)", parcelSize);
Christopher Tate02ca7a72015-06-24 18:16:42 -0700773 const char* exceptionToThrow;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700774 char msg[128];
Jeff Brown0bde66a2011-11-07 12:50:08 -0800775 // TransactionTooLargeException is a checked exception, only throw from certain methods.
776 // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
777 // but it is not the only one. The Binder driver can return BR_FAILED_REPLY
778 // for other reasons also, such as if the transaction is malformed or
779 // refers to an FD that has been closed. We should change the driver
780 // to enable us to distinguish these cases in the future.
Christopher Tate02ca7a72015-06-24 18:16:42 -0700781 if (canThrowRemoteException && parcelSize > 200*1024) {
782 // bona fide large payload
783 exceptionToThrow = "android/os/TransactionTooLargeException";
784 snprintf(msg, sizeof(msg)-1, "data parcel size %d bytes", parcelSize);
785 } else {
786 // Heuristic: a payload smaller than this threshold "shouldn't" be too
787 // big, so it's probably some other, more subtle problem. In practice
Christopher Tateffd58642015-06-29 11:00:15 -0700788 // it seems to always mean that the remote process died while the binder
Christopher Tate02ca7a72015-06-24 18:16:42 -0700789 // transaction was already in flight.
Christopher Tateffd58642015-06-29 11:00:15 -0700790 exceptionToThrow = (canThrowRemoteException)
791 ? "android/os/DeadObjectException"
792 : "java/lang/RuntimeException";
Christopher Tate02ca7a72015-06-24 18:16:42 -0700793 snprintf(msg, sizeof(msg)-1,
794 "Transaction failed on small parcel; remote process probably died");
795 }
796 jniThrowException(env, exceptionToThrow, msg);
Dianne Hackborne5c42622015-05-19 16:04:04 -0700797 } break;
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -0400798 case FDS_NOT_ALLOWED:
799 jniThrowException(env, "java/lang/RuntimeException",
800 "Not allowed to write file descriptors here");
801 break;
Christopher Wileya94fc522015-11-22 14:21:25 -0800802 case UNEXPECTED_NULL:
803 jniThrowNullPointerException(env, NULL);
804 break;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700805 case -EBADF:
806 jniThrowException(env, "java/lang/RuntimeException",
807 "Bad file descriptor");
808 break;
809 case -ENFILE:
810 jniThrowException(env, "java/lang/RuntimeException",
811 "File table overflow");
812 break;
813 case -EMFILE:
814 jniThrowException(env, "java/lang/RuntimeException",
815 "Too many open files");
816 break;
817 case -EFBIG:
818 jniThrowException(env, "java/lang/RuntimeException",
819 "File too large");
820 break;
821 case -ENOSPC:
822 jniThrowException(env, "java/lang/RuntimeException",
823 "No space left on device");
824 break;
825 case -ESPIPE:
826 jniThrowException(env, "java/lang/RuntimeException",
827 "Illegal seek");
828 break;
829 case -EROFS:
830 jniThrowException(env, "java/lang/RuntimeException",
831 "Read-only file system");
832 break;
833 case -EMLINK:
834 jniThrowException(env, "java/lang/RuntimeException",
835 "Too many links");
836 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 default:
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700838 ALOGE("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800839 String8 msg;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700840 msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800841 // RemoteException is a checked exception, only throw from certain methods.
842 jniThrowException(env, canThrowRemoteException
843 ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
844 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846}
847
848}
849
850// ----------------------------------------------------------------------------
851
852static jint android_os_Binder_getCallingPid(JNIEnv* env, jobject clazz)
853{
854 return IPCThreadState::self()->getCallingPid();
855}
856
857static jint android_os_Binder_getCallingUid(JNIEnv* env, jobject clazz)
858{
859 return IPCThreadState::self()->getCallingUid();
860}
861
862static jlong android_os_Binder_clearCallingIdentity(JNIEnv* env, jobject clazz)
863{
864 return IPCThreadState::self()->clearCallingIdentity();
865}
866
867static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
868{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700869 // XXX temporary sanity check to debug crashes.
870 int uid = (int)(token>>32);
871 if (uid > 0 && uid < 999) {
872 // In Android currently there are no uids in this range.
873 char buf[128];
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700874 sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700875 jniThrowException(env, "java/lang/IllegalStateException", buf);
876 return;
877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 IPCThreadState::self()->restoreCallingIdentity(token);
879}
880
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700881static void android_os_Binder_setThreadStrictModePolicy(JNIEnv* env, jobject clazz, jint policyMask)
882{
883 IPCThreadState::self()->setStrictModePolicy(policyMask);
884}
885
886static jint android_os_Binder_getThreadStrictModePolicy(JNIEnv* env, jobject clazz)
887{
888 return IPCThreadState::self()->getStrictModePolicy();
889}
890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
892{
893 IPCThreadState::self()->flushCommands();
894}
895
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700896static jlong android_os_Binder_getNativeBBinderHolder(JNIEnv* env, jobject clazz)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897{
Christopher Tate0b414482011-02-17 13:00:38 -0800898 JavaBBinderHolder* jbh = new JavaBBinderHolder();
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700899 return (jlong) jbh;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900}
901
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700902static void Binder_destroy(void* rawJbh)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903{
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700904 JavaBBinderHolder* jbh = (JavaBBinderHolder*) rawJbh;
905 ALOGV("Java Binder: deleting holder %p", jbh);
906 delete jbh;
907}
908
909JNIEXPORT jlong JNICALL android_os_Binder_getNativeFinalizer(JNIEnv*, jclass) {
910 return (jlong) Binder_destroy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911}
912
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700913static void android_os_Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz)
914{
915 return IPCThreadState::self()->blockUntilThreadAvailable();
916}
917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918// ----------------------------------------------------------------------------
919
920static const JNINativeMethod gBinderMethods[] = {
921 /* name, signature, funcPtr */
922 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
923 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
924 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
925 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700926 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
927 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700929 { "getNativeBBinderHolder", "()J", (void*)android_os_Binder_getNativeBBinderHolder },
930 { "getNativeFinalizer", "()J", (void*)android_os_Binder_getNativeFinalizer },
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700931 { "blockUntilThreadAvailable", "()V", (void*)android_os_Binder_blockUntilThreadAvailable }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932};
933
934const char* const kBinderPathName = "android/os/Binder";
935
936static int int_register_android_os_Binder(JNIEnv* env)
937{
Andreas Gampe987f79f2014-11-18 17:29:46 -0800938 jclass clazz = FindClassOrDie(env, kBinderPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939
Andreas Gampe987f79f2014-11-18 17:29:46 -0800940 gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
941 gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
942 gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800944 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 env, kBinderPathName,
946 gBinderMethods, NELEM(gBinderMethods));
947}
948
949// ****************************************************************************
950// ****************************************************************************
951// ****************************************************************************
952
953namespace android {
954
955jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
956{
Hans Boehm29f388f2017-10-03 18:01:20 -0700957 return gNumLocalRefsCreated - gNumLocalRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958}
959
960jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
961{
Hans Boehm29f388f2017-10-03 18:01:20 -0700962 AutoMutex _l(gProxyLock);
963 return gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964}
965
966jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
967{
Hans Boehm29f388f2017-10-03 18:01:20 -0700968 return gNumDeathRefsCreated - gNumDeathRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969}
970
971}
972
973// ****************************************************************************
974// ****************************************************************************
975// ****************************************************************************
976
977static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
978{
979 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
980 return javaObjectForIBinder(env, b);
981}
982
983static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
984{
985 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
986 android::IPCThreadState::self()->joinThreadPool();
987}
988
Dianne Hackborn887f3552009-12-07 17:59:37 -0800989static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
990 jobject clazz, jboolean disable)
991{
992 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
993}
994
Tim Murrayeef4a3d2016-04-19 14:14:20 -0700995static void android_os_BinderInternal_setMaxThreads(JNIEnv* env,
996 jobject clazz, jint maxThreads)
997{
998 ProcessState::self()->setThreadPoolMaxThreadCount(maxThreads);
999}
1000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
1002{
Hans Boehm29f388f2017-10-03 18:01:20 -07001003 ALOGV("Gc has executed, updating Refs count at GC");
1004 gCollectedAtRefs = gNumLocalRefsCreated + gNumDeathRefsCreated;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005}
1006
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001007static void android_os_BinderInternal_proxyLimitcallback(int uid)
1008{
1009 JNIEnv *env = AndroidRuntime::getJNIEnv();
Martijn Coenendfa390e2018-06-05 11:02:23 +02001010 {
1011 // Calls into BinderProxy must be serialized
1012 AutoMutex _l(gProxyLock);
1013 env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
1014 gBinderProxyOffsets.mDumpProxyDebugInfo);
1015 }
1016 if (env->ExceptionCheck()) {
1017 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
1018 report_exception(env, excep.get(),
1019 "*** Uncaught exception in dumpProxyDebugInfo");
1020 }
1021
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001022 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
1023 gBinderInternalOffsets.mProxyLimitCallback,
1024 uid);
Martijn Coenendfa390e2018-06-05 11:02:23 +02001025
1026 if (env->ExceptionCheck()) {
1027 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
1028 report_exception(env, excep.get(),
1029 "*** Uncaught exception in binderProxyLimitCallbackFromNative");
1030 }
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001031}
1032
1033static void android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv* env, jobject clazz,
1034 jboolean enable)
1035{
1036 BpBinder::setCountByUidEnabled((bool) enable);
1037}
1038
1039static jobject android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv* env, jclass clazz)
1040{
1041 Vector<uint32_t> uids, counts;
1042 BpBinder::getCountByUid(uids, counts);
1043 jobject sparseIntArray = env->NewObject(gSparseIntArrayOffsets.classObject,
1044 gSparseIntArrayOffsets.constructor);
1045 for (size_t i = 0; i < uids.size(); i++) {
1046 env->CallVoidMethod(sparseIntArray, gSparseIntArrayOffsets.put,
1047 static_cast<jint>(uids[i]), static_cast<jint>(counts[i]));
1048 }
1049 return sparseIntArray;
1050}
1051
1052static jint android_os_BinderInternal_getBinderProxyCount(JNIEnv* env, jobject clazz, jint uid) {
1053 return static_cast<jint>(BpBinder::getBinderProxyCount(static_cast<uint32_t>(uid)));
1054}
1055
1056static void android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv* env, jobject clazz,
1057 jint high, jint low)
1058{
1059 BpBinder::setBinderProxyCountWatermarks(high, low);
1060}
1061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062// ----------------------------------------------------------------------------
1063
1064static const JNINativeMethod gBinderInternalMethods[] = {
1065 /* name, signature, funcPtr */
1066 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
1067 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -08001068 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001069 { "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001070 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
1071 { "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
1072 { "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
1073 { "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
1074 { "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075};
1076
1077const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
1078
1079static int int_register_android_os_BinderInternal(JNIEnv* env)
1080{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001081 jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082
Andreas Gampe987f79f2014-11-18 17:29:46 -08001083 gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1084 gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001085 gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
1086
1087 jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
1088 gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
1089 gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
1090 "<init>", "()V");
1091 gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
1092 "(II)V");
1093
1094 BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001096 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 env, kBinderInternalPathName,
1098 gBinderInternalMethods, NELEM(gBinderInternalMethods));
1099}
1100
1101// ****************************************************************************
1102// ****************************************************************************
1103// ****************************************************************************
1104
1105static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
1106{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001107 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 if (target == NULL) {
1109 return JNI_FALSE;
1110 }
1111 status_t err = target->pingBinder();
1112 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
1113}
1114
1115static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
1116{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001117 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 if (target != NULL) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001119 const String16& desc = target->getInterfaceDescriptor();
Dan Albert66987492014-11-20 11:41:21 -08001120 return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
1121 desc.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
1123 jniThrowException(env, "java/lang/RuntimeException",
1124 "No binder found for object");
1125 return NULL;
1126}
1127
1128static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
1129{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001130 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 if (target == NULL) {
1132 return JNI_FALSE;
1133 }
1134 bool alive = target->isBinderAlive();
1135 return alive ? JNI_TRUE : JNI_FALSE;
1136}
1137
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001138static int getprocname(pid_t pid, char *buf, size_t len) {
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001139 char filename[32];
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001140 FILE *f;
1141
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001142 snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001143 f = fopen(filename, "r");
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001144 if (!f) {
1145 *buf = '\0';
1146 return 1;
1147 }
1148 if (!fgets(buf, len, f)) {
1149 *buf = '\0';
1150 fclose(f);
1151 return 2;
1152 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001153 fclose(f);
1154 return 0;
1155}
1156
1157static bool push_eventlog_string(char** pos, const char* end, const char* str) {
1158 jint len = strlen(str);
1159 int space_needed = 1 + sizeof(len) + len;
1160 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001161 ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001162 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001163 return false;
1164 }
1165 **pos = EVENT_TYPE_STRING;
1166 (*pos)++;
1167 memcpy(*pos, &len, sizeof(len));
1168 *pos += sizeof(len);
1169 memcpy(*pos, str, len);
1170 *pos += len;
1171 return true;
1172}
1173
1174static bool push_eventlog_int(char** pos, const char* end, jint val) {
1175 int space_needed = 1 + sizeof(val);
1176 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001177 ALOGW("not enough space for int. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001178 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001179 return false;
1180 }
1181 **pos = EVENT_TYPE_INT;
1182 (*pos)++;
1183 memcpy(*pos, &val, sizeof(val));
1184 *pos += sizeof(val);
1185 return true;
1186}
1187
1188// From frameworks/base/core/java/android/content/EventLogTags.logtags:
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001189
1190static const bool kEnableBinderSample = false;
1191
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001192#define LOGTAG_BINDER_OPERATION 52004
1193
1194static void conditionally_log_binder_call(int64_t start_millis,
1195 IBinder* target, jint code) {
1196 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1197
1198 int sample_percent;
1199 if (duration_ms >= 500) {
1200 sample_percent = 100;
1201 } else {
1202 sample_percent = 100 * duration_ms / 500;
1203 if (sample_percent == 0) {
1204 return;
1205 }
1206 if (sample_percent < (random() % 100 + 1)) {
1207 return;
1208 }
1209 }
1210
1211 char process_name[40];
1212 getprocname(getpid(), process_name, sizeof(process_name));
1213 String8 desc(target->getInterfaceDescriptor());
1214
1215 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1216 buf[0] = EVENT_TYPE_LIST;
1217 buf[1] = 5;
1218 char* pos = &buf[2];
1219 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1220 if (!push_eventlog_string(&pos, end, desc.string())) return;
1221 if (!push_eventlog_int(&pos, end, code)) return;
1222 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1223 if (!push_eventlog_string(&pos, end, process_name)) return;
1224 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1225 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1226 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1227}
1228
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001229// We only measure binder call durations to potentially log them if
Elliott Hughes06451fe2014-08-18 10:26:52 -07001230// we're on the main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001231static bool should_time_binder_calls() {
Elliott Hughes06451fe2014-08-18 10:26:52 -07001232 return (getpid() == gettid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001233}
1234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001236 jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237{
1238 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001239 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 return JNI_FALSE;
1241 }
1242
1243 Parcel* data = parcelForJavaObject(env, dataObj);
1244 if (data == NULL) {
1245 return JNI_FALSE;
1246 }
1247 Parcel* reply = parcelForJavaObject(env, replyObj);
1248 if (reply == NULL && replyObj != NULL) {
1249 return JNI_FALSE;
1250 }
1251
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001252 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 if (target == NULL) {
1254 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1255 return JNI_FALSE;
1256 }
1257
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001258 ALOGV("Java code calling transact on %p in Java object %p with code %" PRId32 "\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001260
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001261
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001262 bool time_binder_calls;
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001263 int64_t start_millis;
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001264 if (kEnableBinderSample) {
1265 // Only log the binder call duration for things on the Java-level main thread.
1266 // But if we don't
1267 time_binder_calls = should_time_binder_calls();
1268
1269 if (time_binder_calls) {
1270 start_millis = uptimeMillis();
1271 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001272 }
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 //printf("Transact from Java code to %p sending: ", target); data->print();
1275 status_t err = target->transact(code, *data, reply, flags);
1276 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001277
1278 if (kEnableBinderSample) {
1279 if (time_binder_calls) {
1280 conditionally_log_binder_call(start_millis, target, code);
1281 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001282 }
1283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 if (err == NO_ERROR) {
1285 return JNI_TRUE;
1286 } else if (err == UNKNOWN_TRANSACTION) {
1287 return JNI_FALSE;
1288 }
1289
Dianne Hackborne5c42622015-05-19 16:04:04 -07001290 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 return JNI_FALSE;
1292}
1293
1294static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001295 jobject recipient, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296{
1297 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001298 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 return;
1300 }
1301
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001302 BinderProxyNativeData *nd = getBPNativeData(env, obj);
1303 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304
Christopher Tate79dd31f2011-03-04 17:45:00 -08001305 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306
1307 if (!target->localBinder()) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001308 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001309 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001310 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 if (err != NO_ERROR) {
1312 // Failure adding the death recipient, so clear its reference
1313 // now.
1314 jdr->clearReference();
Jeff Brown0bde66a2011-11-07 12:50:08 -08001315 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 }
1317 }
1318}
1319
1320static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1321 jobject recipient, jint flags)
1322{
1323 jboolean res = JNI_FALSE;
1324 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001325 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 return res;
1327 }
1328
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001329 BinderProxyNativeData* nd = getBPNativeData(env, obj);
1330 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001332 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 return JNI_FALSE;
1334 }
1335
Christopher Tate79dd31f2011-03-04 17:45:00 -08001336 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337
1338 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001339 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001340
1341 // If we find the matching recipient, proceed to unlink using that
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001342 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001343 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001344 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001345 if (origJDR != NULL) {
1346 wp<IBinder::DeathRecipient> dr;
1347 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1348 if (err == NO_ERROR && dr != NULL) {
1349 sp<IBinder::DeathRecipient> sdr = dr.promote();
1350 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1351 if (jdr != NULL) {
1352 jdr->clearReference();
1353 }
1354 }
1355 }
1356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 if (err == NO_ERROR || err == DEAD_OBJECT) {
1358 res = JNI_TRUE;
1359 } else {
1360 jniThrowException(env, "java/util/NoSuchElementException",
1361 "Death link does not exist");
1362 }
1363 }
1364
1365 return res;
1366}
1367
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001368static void BinderProxy_destroy(void* rawNativeData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369{
Christopher Tate10c3a282016-02-26 17:48:08 -08001370 // Don't race with construction/initialization
Hans Boehmeb6d62c2017-09-20 15:59:12 -07001371 AutoMutex _l(gProxyLock);
Christopher Tate10c3a282016-02-26 17:48:08 -08001372
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001373 BinderProxyNativeData * nativeData = (BinderProxyNativeData *) rawNativeData;
1374 LOGDEATH("Destroying BinderProxy: binder=%p drl=%p\n",
1375 nativeData->mObject.get(), nativeData->mOrgue.get());
Hans Boehm29f388f2017-10-03 18:01:20 -07001376 delete nativeData;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001377 IPCThreadState::self()->flushCommands();
Hans Boehm29f388f2017-10-03 18:01:20 -07001378 --gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379}
1380
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001381JNIEXPORT jlong JNICALL android_os_BinderProxy_getNativeFinalizer(JNIEnv*, jclass) {
1382 return (jlong) BinderProxy_destroy;
1383}
1384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385// ----------------------------------------------------------------------------
1386
1387static const JNINativeMethod gBinderProxyMethods[] = {
1388 /* name, signature, funcPtr */
1389 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1390 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1391 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001392 {"transactNative", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1394 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001395 {"getNativeFinalizer", "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396};
1397
1398const char* const kBinderProxyPathName = "android/os/BinderProxy";
1399
1400static int int_register_android_os_BinderProxy(JNIEnv* env)
1401{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001402 jclass clazz = FindClassOrDie(env, "java/lang/Error");
1403 gErrorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404
Andreas Gampe987f79f2014-11-18 17:29:46 -08001405 clazz = FindClassOrDie(env, kBinderProxyPathName);
1406 gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
Hans Boehm29f388f2017-10-03 18:01:20 -07001407 gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance",
1408 "(JJ)Landroid/os/BinderProxy;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001409 gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
1410 "(Landroid/os/IBinder$DeathRecipient;)V");
Martijn Coenendfa390e2018-06-05 11:02:23 +02001411 gBinderProxyOffsets.mDumpProxyDebugInfo = GetStaticMethodIDOrDie(env, clazz, "dumpProxyDebugInfo",
1412 "()V");
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001413 gBinderProxyOffsets.mNativeData = GetFieldIDOrDie(env, clazz, "mNativeData", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414
Andreas Gampe987f79f2014-11-18 17:29:46 -08001415 clazz = FindClassOrDie(env, "java/lang/Class");
1416 gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
Christopher Tate0d4a7922011-08-30 12:09:43 -07001417
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001418 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 env, kBinderProxyPathName,
1420 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1421}
1422
1423// ****************************************************************************
1424// ****************************************************************************
1425// ****************************************************************************
1426
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001427int register_android_os_Binder(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428{
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001429 if (int_register_android_os_Binder(env) < 0)
1430 return -1;
1431 if (int_register_android_os_BinderInternal(env) < 0)
1432 return -1;
1433 if (int_register_android_os_BinderProxy(env) < 0)
1434 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435
Andreas Gampe987f79f2014-11-18 17:29:46 -08001436 jclass clazz = FindClassOrDie(env, "android/util/Log");
1437 gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1438 gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
1439 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440
Andreas Gampe987f79f2014-11-18 17:29:46 -08001441 clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
1442 gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1443 gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
1444 "(Ljava/io/FileDescriptor;)V");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445
Andreas Gampe987f79f2014-11-18 17:29:46 -08001446 clazz = FindClassOrDie(env, "android/os/StrictMode");
1447 gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1448 gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
1449 "onBinderStrictModePolicyChange", "(I)V");
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001450
Andreas Gampe1cd76f52017-09-08 17:44:05 -07001451 clazz = FindClassOrDie(env, "java/lang/Thread");
1452 gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1453 gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
1454 "dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
1455 gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
1456 "()Ljava/lang/Thread;");
1457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 return 0;
1459}