blob: 1b206fd8abdddc5ed8fcce28dedf3e6f02fb1c20 [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;
111
112 // Object state.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700113 jfieldID mNativeData; // Field holds native pointer to BinderProxyNativeData.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114} gBinderProxyOffsets;
115
Christopher Tate0d4a7922011-08-30 12:09:43 -0700116static struct class_offsets_t
117{
118 jmethodID mGetName;
119} gClassOffsets;
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121// ----------------------------------------------------------------------------
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123static struct log_offsets_t
124{
125 // Class state.
126 jclass mClass;
127 jmethodID mLogE;
128} gLogOffsets;
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130static struct parcel_file_descriptor_offsets_t
131{
132 jclass mClass;
133 jmethodID mConstructor;
134} gParcelFileDescriptorOffsets;
135
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700136static struct strict_mode_callback_offsets_t
137{
138 jclass mClass;
139 jmethodID mCallback;
140} gStrictModeCallbackOffsets;
141
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700142static struct thread_dispatch_offsets_t
143{
144 // Class state.
145 jclass mClass;
146 jmethodID mDispatchUncaughtException;
147 jmethodID mCurrentThread;
148} gThreadDispatchOffsets;
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150// ****************************************************************************
151// ****************************************************************************
152// ****************************************************************************
153
Hans Boehm29f388f2017-10-03 18:01:20 -0700154static constexpr int32_t PROXY_WARN_INTERVAL = 5000;
155static constexpr uint32_t GC_INTERVAL = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Hans Boehm29f388f2017-10-03 18:01:20 -0700157// Protected by gProxyLock. We warn if this gets too large.
158static int32_t gNumProxies = 0;
159static int32_t gProxiesWarned = 0;
160
161// Number of GlobalRefs held by JavaBBinders.
162static std::atomic<uint32_t> gNumLocalRefsCreated(0);
163static std::atomic<uint32_t> gNumLocalRefsDeleted(0);
164// Number of GlobalRefs held by JavaDeathRecipients.
165static std::atomic<uint32_t> gNumDeathRefsCreated(0);
166static std::atomic<uint32_t> gNumDeathRefsDeleted(0);
167
168// We collected after creating this many refs.
169static std::atomic<uint32_t> gCollectedAtRefs(0);
170
171// Garbage collect if we've allocated at least GC_INTERVAL refs since the last time.
172// TODO: Consider removing this completely. We should no longer be generating GlobalRefs
173// that are reclaimed as a result of GC action.
Ivan Lozano2ea71352017-11-02 14:10:57 -0700174__attribute__((no_sanitize("unsigned-integer-overflow")))
Hans Boehm29f388f2017-10-03 18:01:20 -0700175static void gcIfManyNewRefs(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176{
Hans Boehm29f388f2017-10-03 18:01:20 -0700177 uint32_t totalRefs = gNumLocalRefsCreated.load(std::memory_order_relaxed)
178 + gNumDeathRefsCreated.load(std::memory_order_relaxed);
179 uint32_t collectedAtRefs = gCollectedAtRefs.load(memory_order_relaxed);
180 // A bound on the number of threads that can have incremented gNum...RefsCreated before the
181 // following check is executed. Effectively a bound on #threads. Almost any value will do.
182 static constexpr uint32_t MAX_RACING = 100000;
183
184 if (totalRefs - (collectedAtRefs + GC_INTERVAL) /* modular arithmetic! */ < MAX_RACING) {
185 // Recently passed next GC interval.
186 if (gCollectedAtRefs.compare_exchange_strong(collectedAtRefs,
187 collectedAtRefs + GC_INTERVAL, std::memory_order_relaxed)) {
188 ALOGV("Binder forcing GC at %u created refs", totalRefs);
189 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
190 gBinderInternalOffsets.mForceGc);
191 } // otherwise somebody else beat us to it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 } else {
Hans Boehm29f388f2017-10-03 18:01:20 -0700193 ALOGV("Now have %d binder ops", totalRefs - collectedAtRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 }
195}
196
197static JavaVM* jnienv_to_javavm(JNIEnv* env)
198{
199 JavaVM* vm;
200 return env->GetJavaVM(&vm) >= 0 ? vm : NULL;
201}
202
203static JNIEnv* javavm_to_jnienv(JavaVM* vm)
204{
205 JNIEnv* env;
206 return vm->GetEnv((void **)&env, JNI_VERSION_1_4) >= 0 ? env : NULL;
207}
208
Andreas Gampe625e0002017-09-08 17:44:05 -0700209// Report a java.lang.Error (or subclass). This will terminate the runtime by
210// calling FatalError with a message derived from the given error.
211static void report_java_lang_error_fatal_error(JNIEnv* env, jthrowable error,
212 const char* msg)
213{
214 // Report an error: reraise the exception and ask the runtime to abort.
215
216 // Try to get the exception string. Sometimes logcat isn't available,
217 // so try to add it to the abort message.
218 std::string exc_msg = "(Unknown exception message)";
219 {
220 ScopedLocalRef<jclass> exc_class(env, env->GetObjectClass(error));
221 jmethodID method_id = env->GetMethodID(exc_class.get(), "toString",
222 "()Ljava/lang/String;");
223 ScopedLocalRef<jstring> jstr(
224 env,
225 reinterpret_cast<jstring>(
226 env->CallObjectMethod(error, method_id)));
227 env->ExceptionClear(); // Just for good measure.
228 if (jstr.get() != nullptr) {
229 ScopedUtfChars jstr_utf(env, jstr.get());
230 if (jstr_utf.c_str() != nullptr) {
231 exc_msg = jstr_utf.c_str();
232 } else {
233 env->ExceptionClear();
234 }
235 }
236 }
237
238 env->Throw(error);
239 ALOGE("java.lang.Error thrown during binder transaction (stack trace follows) : ");
240 env->ExceptionDescribe();
241
242 std::string error_msg = base::StringPrintf(
243 "java.lang.Error thrown during binder transaction: %s",
244 exc_msg.c_str());
245 env->FatalError(error_msg.c_str());
246}
247
248// Report a java.lang.Error (or subclass). This will terminate the runtime, either by
249// the uncaught exception handler, or explicitly by calling
250// report_java_lang_error_fatal_error.
251static void report_java_lang_error(JNIEnv* env, jthrowable error, const char* msg)
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700252{
253 // Try to run the uncaught exception machinery.
254 jobject thread = env->CallStaticObjectMethod(gThreadDispatchOffsets.mClass,
255 gThreadDispatchOffsets.mCurrentThread);
256 if (thread != nullptr) {
257 env->CallVoidMethod(thread, gThreadDispatchOffsets.mDispatchUncaughtException,
258 error);
259 // Should not return here, unless more errors occured.
260 }
261 // Some error occurred that meant that either dispatchUncaughtException could not be
262 // called or that it had an error itself (as this should be unreachable under normal
Andreas Gampe625e0002017-09-08 17:44:05 -0700263 // conditions). As the binder code cannot handle Errors, attempt to log the error and
264 // abort.
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700265 env->ExceptionClear();
Andreas Gampe625e0002017-09-08 17:44:05 -0700266 report_java_lang_error_fatal_error(env, error, msg);
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700267}
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269static void report_exception(JNIEnv* env, jthrowable excep, const char* msg)
270{
271 env->ExceptionClear();
272
Andreas Gampe625e0002017-09-08 17:44:05 -0700273 ScopedLocalRef<jstring> tagstr(env, env->NewStringUTF(LOG_TAG));
Andreas Gampe8571ec32017-09-21 10:55:59 -0700274 ScopedLocalRef<jstring> msgstr(env);
Andreas Gampe625e0002017-09-08 17:44:05 -0700275 if (tagstr != nullptr) {
276 msgstr.reset(env->NewStringUTF(msg));
Mathieu Chartiercf6775e2014-08-06 13:39:17 -0700277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
Andreas Gampe625e0002017-09-08 17:44:05 -0700279 if ((tagstr != nullptr) && (msgstr != nullptr)) {
280 env->CallStaticIntMethod(gLogOffsets.mClass, gLogOffsets.mLogE,
281 tagstr.get(), msgstr.get(), excep);
282 if (env->ExceptionCheck()) {
283 // Attempting to log the failure has failed.
284 ALOGW("Failed trying to log exception, msg='%s'\n", msg);
285 env->ExceptionClear();
286 }
287 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 env->ExceptionClear(); /* assume exception (OOM?) was thrown */
Steve Block3762c312012-01-06 19:20:56 +0000289 ALOGE("Unable to call Log.e()\n");
290 ALOGE("%s", msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
292
293 if (env->IsInstanceOf(excep, gErrorOffsets.mClass)) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700294 report_java_lang_error(env, excep, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296}
297
298class JavaBBinderHolder;
299
300class JavaBBinder : public BBinder
301{
302public:
Hans Boehm29f388f2017-10-03 18:01:20 -0700303 JavaBBinder(JNIEnv* env, jobject /* Java Binder */ object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))
305 {
Steve Block71f2cf12011-10-20 11:56:00 +0100306 ALOGV("Creating JavaBBinder %p\n", this);
Hans Boehm29f388f2017-10-03 18:01:20 -0700307 gNumLocalRefsCreated.fetch_add(1, std::memory_order_relaxed);
308 gcIfManyNewRefs(env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 }
310
311 bool checkSubclass(const void* subclassID) const
312 {
313 return subclassID == &gBinderOffsets;
314 }
315
316 jobject object() const
317 {
318 return mObject;
319 }
320
321protected:
322 virtual ~JavaBBinder()
323 {
Steve Block71f2cf12011-10-20 11:56:00 +0100324 ALOGV("Destroying JavaBBinder %p\n", this);
Hans Boehm29f388f2017-10-03 18:01:20 -0700325 gNumLocalRefsDeleted.fetch_add(1, memory_order_relaxed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 JNIEnv* env = javavm_to_jnienv(mVM);
327 env->DeleteGlobalRef(mObject);
328 }
329
330 virtual status_t onTransact(
331 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0)
332 {
333 JNIEnv* env = javavm_to_jnienv(mVM);
334
Steve Block71f2cf12011-10-20 11:56:00 +0100335 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 -0800336
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700337 IPCThreadState* thread_state = IPCThreadState::self();
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700338 const int32_t strict_policy_before = thread_state->getStrictModePolicy();
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 //printf("Transact from %p to Java code sending: ", this);
341 //data.print();
342 //printf("\n");
343 jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000344 code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700345
Mathieu Chartier98671c32014-08-20 10:04:08 -0700346 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700347 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
348 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100349 "*** Uncaught remote exception! "
350 "(Exceptions are not yet supported across processes.)");
351 res = JNI_FALSE;
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100352 }
353
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700354 // Check if the strict mode state changed while processing the
355 // call. The Binder state will be restored by the underlying
356 // Binder system in IPCThreadState, however we need to take care
357 // of the parallel Java state as well.
358 if (thread_state->getStrictModePolicy() != strict_policy_before) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700359 set_dalvik_blockguard_policy(env, strict_policy_before);
360 }
361
Mathieu Chartier98671c32014-08-20 10:04:08 -0700362 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700363 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
364 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100365 "*** Uncaught exception in onBinderStrictModePolicyChange");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 }
367
Dianne Hackborna53de062012-05-08 18:53:51 -0700368 // Need to always call through the native implementation of
369 // SYSPROPS_TRANSACTION.
370 if (code == SYSPROPS_TRANSACTION) {
371 BBinder::onTransact(code, data, reply, flags);
372 }
373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 //aout << "onTransact to Java code; result=" << res << endl
375 // << "Transact from " << this << " to Java code returning "
376 // << reply << ": " << *reply << endl;
377 return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
378 }
379
380 virtual status_t dump(int fd, const Vector<String16>& args)
381 {
382 return 0;
383 }
384
385private:
386 JavaVM* const mVM;
Hans Boehm29f388f2017-10-03 18:01:20 -0700387 jobject const mObject; // GlobalRef to Java Binder
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388};
389
390// ----------------------------------------------------------------------------
391
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700392class JavaBBinderHolder
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393{
394public:
Christopher Tate0b414482011-02-17 13:00:38 -0800395 sp<JavaBBinder> get(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 {
397 AutoMutex _l(mLock);
398 sp<JavaBBinder> b = mBinder.promote();
399 if (b == NULL) {
Christopher Tate0b414482011-02-17 13:00:38 -0800400 b = new JavaBBinder(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 mBinder = b;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700402 ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
Christopher Tate0b414482011-02-17 13:00:38 -0800403 b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 }
405
406 return b;
407 }
408
409 sp<JavaBBinder> getExisting()
410 {
411 AutoMutex _l(mLock);
412 return mBinder.promote();
413 }
414
415private:
416 Mutex mLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 wp<JavaBBinder> mBinder;
418};
419
420// ----------------------------------------------------------------------------
421
Christopher Tate0b414482011-02-17 13:00:38 -0800422// Per-IBinder death recipient bookkeeping. This is how we reconcile local jobject
423// death recipient references passed in through JNI with the permanent corresponding
424// JavaDeathRecipient objects.
425
426class JavaDeathRecipient;
427
428class DeathRecipientList : public RefBase {
429 List< sp<JavaDeathRecipient> > mList;
430 Mutex mLock;
431
432public:
Christopher Tate79dd31f2011-03-04 17:45:00 -0800433 DeathRecipientList();
Christopher Tate0b414482011-02-17 13:00:38 -0800434 ~DeathRecipientList();
435
436 void add(const sp<JavaDeathRecipient>& recipient);
437 void remove(const sp<JavaDeathRecipient>& recipient);
438 sp<JavaDeathRecipient> find(jobject recipient);
Christopher Tate090c08f2015-05-19 18:16:58 -0700439
440 Mutex& lock(); // Use with care; specifically for mutual exclusion during binder death
Christopher Tate0b414482011-02-17 13:00:38 -0800441};
442
443// ----------------------------------------------------------------------------
444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445class JavaDeathRecipient : public IBinder::DeathRecipient
446{
447public:
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800448 JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
Christopher Tate86284c62011-08-17 15:19:29 -0700449 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
450 mObjectWeak(NULL), mList(list)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 {
Christopher Tate0b414482011-02-17 13:00:38 -0800452 // These objects manage their own lifetimes so are responsible for final bookkeeping.
453 // The list holds a strong reference to this object.
Christopher Tate79dd31f2011-03-04 17:45:00 -0800454 LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800455 list->add(this);
Christopher Tate0b414482011-02-17 13:00:38 -0800456
Hans Boehm29f388f2017-10-03 18:01:20 -0700457 gNumDeathRefsCreated.fetch_add(1, std::memory_order_relaxed);
458 gcIfManyNewRefs(env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 }
460
461 void binderDied(const wp<IBinder>& who)
462 {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800463 LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
Christopher Tate86284c62011-08-17 15:19:29 -0700464 if (mObject != NULL) {
465 JNIEnv* env = javavm_to_jnienv(mVM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466
Christopher Tate86284c62011-08-17 15:19:29 -0700467 env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
468 gBinderProxyOffsets.mSendDeathNotice, mObject);
Mathieu Chartier98671c32014-08-20 10:04:08 -0700469 if (env->ExceptionCheck()) {
470 jthrowable excep = env->ExceptionOccurred();
Christopher Tate86284c62011-08-17 15:19:29 -0700471 report_exception(env, excep,
472 "*** Uncaught exception returned from death notification!");
473 }
474
Christopher Tate090c08f2015-05-19 18:16:58 -0700475 // Serialize with our containing DeathRecipientList so that we can't
476 // delete the global ref on mObject while the list is being iterated.
477 sp<DeathRecipientList> list = mList.promote();
478 if (list != NULL) {
479 AutoMutex _l(list->lock());
480
481 // Demote from strong ref to weak after binderDied() has been delivered,
482 // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
483 mObjectWeak = env->NewWeakGlobalRef(mObject);
484 env->DeleteGlobalRef(mObject);
485 mObject = NULL;
486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 }
489
490 void clearReference()
491 {
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800492 sp<DeathRecipientList> list = mList.promote();
493 if (list != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800494 LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800495 list->remove(this);
Christopher Tate79dd31f2011-03-04 17:45:00 -0800496 } else {
497 LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800498 }
Christopher Tate0b414482011-02-17 13:00:38 -0800499 }
500
501 bool matches(jobject obj) {
Christopher Tate86284c62011-08-17 15:19:29 -0700502 bool result;
Christopher Tate0b414482011-02-17 13:00:38 -0800503 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700504
505 if (mObject != NULL) {
506 result = env->IsSameObject(obj, mObject);
507 } else {
Andreas Gampe625e0002017-09-08 17:44:05 -0700508 ScopedLocalRef<jobject> me(env, env->NewLocalRef(mObjectWeak));
509 result = env->IsSameObject(obj, me.get());
Christopher Tate86284c62011-08-17 15:19:29 -0700510 }
511 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
513
Christopher Tateac5e3502011-08-25 15:48:09 -0700514 void warnIfStillLive() {
515 if (mObject != NULL) {
516 // Okay, something is wrong -- we have a hard reference to a live death
517 // recipient on the VM side, but the list is being torn down.
518 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate0d4a7922011-08-30 12:09:43 -0700519 ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
520 ScopedLocalRef<jstring> nameRef(env,
521 (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
522 ScopedUtfChars nameUtf(env, nameRef.get());
523 if (nameUtf.c_str() != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000524 ALOGW("BinderProxy is being destroyed but the application did not call "
Christopher Tate0d4a7922011-08-30 12:09:43 -0700525 "unlinkToDeath to unlink all of its death recipients beforehand. "
526 "Releasing leaked death recipient: %s", nameUtf.c_str());
527 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000528 ALOGW("BinderProxy being destroyed; unable to get DR object name");
Christopher Tate0d4a7922011-08-30 12:09:43 -0700529 env->ExceptionClear();
530 }
Christopher Tateac5e3502011-08-25 15:48:09 -0700531 }
532 }
533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534protected:
535 virtual ~JavaDeathRecipient()
536 {
Steve Block6215d3f2012-01-04 20:05:49 +0000537 //ALOGI("Removing death ref: recipient=%p\n", mObject);
Hans Boehm29f388f2017-10-03 18:01:20 -0700538 gNumDeathRefsDeleted.fetch_add(1, std::memory_order_relaxed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700540 if (mObject != NULL) {
541 env->DeleteGlobalRef(mObject);
542 } else {
543 env->DeleteWeakGlobalRef(mObjectWeak);
544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546
547private:
Christopher Tate86284c62011-08-17 15:19:29 -0700548 JavaVM* const mVM;
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700549 jobject mObject; // Initial strong ref to Java-side DeathRecipient. Cleared on binderDied().
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700550 jweak mObjectWeak; // Weak ref to the same Java-side DeathRecipient after binderDied().
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800551 wp<DeathRecipientList> mList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552};
553
554// ----------------------------------------------------------------------------
555
Christopher Tate79dd31f2011-03-04 17:45:00 -0800556DeathRecipientList::DeathRecipientList() {
557 LOGDEATH("New DRL @ %p", this);
558}
559
Christopher Tate0b414482011-02-17 13:00:38 -0800560DeathRecipientList::~DeathRecipientList() {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800561 LOGDEATH("Destroy DRL @ %p", this);
Christopher Tate0b414482011-02-17 13:00:38 -0800562 AutoMutex _l(mLock);
563
564 // Should never happen -- the JavaDeathRecipient objects that have added themselves
565 // to the list are holding references on the list object. Only when they are torn
566 // down can the list header be destroyed.
567 if (mList.size() > 0) {
Christopher Tateac5e3502011-08-25 15:48:09 -0700568 List< sp<JavaDeathRecipient> >::iterator iter;
569 for (iter = mList.begin(); iter != mList.end(); iter++) {
570 (*iter)->warnIfStillLive();
571 }
Christopher Tate0b414482011-02-17 13:00:38 -0800572 }
573}
574
575void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
576 AutoMutex _l(mLock);
577
Christopher Tate79dd31f2011-03-04 17:45:00 -0800578 LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800579 mList.push_back(recipient);
580}
581
582void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
583 AutoMutex _l(mLock);
584
585 List< sp<JavaDeathRecipient> >::iterator iter;
586 for (iter = mList.begin(); iter != mList.end(); iter++) {
587 if (*iter == recipient) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800588 LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800589 mList.erase(iter);
590 return;
591 }
592 }
593}
594
595sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
596 AutoMutex _l(mLock);
597
598 List< sp<JavaDeathRecipient> >::iterator iter;
599 for (iter = mList.begin(); iter != mList.end(); iter++) {
600 if ((*iter)->matches(recipient)) {
601 return *iter;
602 }
603 }
604 return NULL;
605}
606
Christopher Tate090c08f2015-05-19 18:16:58 -0700607Mutex& DeathRecipientList::lock() {
608 return mLock;
609}
610
Christopher Tate0b414482011-02-17 13:00:38 -0800611// ----------------------------------------------------------------------------
612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613namespace android {
614
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700615// We aggregate native pointer fields for BinderProxy in a single object to allow
616// management with a single NativeAllocationRegistry, and to reduce the number of JNI
617// Java field accesses. This costs us some extra indirections here.
618struct BinderProxyNativeData {
Hans Boehm29f388f2017-10-03 18:01:20 -0700619 // Both fields are constant and not null once javaObjectForIBinder returns this as
620 // part of a BinderProxy.
621
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700622 // The native IBinder proxied by this BinderProxy.
Hans Boehm29f388f2017-10-03 18:01:20 -0700623 sp<IBinder> mObject;
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700624
625 // Death recipients for mObject. Reference counted only because DeathRecipients
626 // hold a weak reference that can be temporarily promoted.
Hans Boehm29f388f2017-10-03 18:01:20 -0700627 sp<DeathRecipientList> mOrgue; // Death recipients for mObject.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700628};
629
630BinderProxyNativeData* getBPNativeData(JNIEnv* env, jobject obj) {
631 return (BinderProxyNativeData *) env->GetLongField(obj, gBinderProxyOffsets.mNativeData);
632}
633
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700634static Mutex gProxyLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635
Hans Boehm29f388f2017-10-03 18:01:20 -0700636// We may cache a single BinderProxyNativeData node to avoid repeat allocation.
637// All fields are null. Protected by gProxyLock.
638static BinderProxyNativeData *gNativeDataCache;
639
640// If the argument is a JavaBBinder, return the Java object that was used to create it.
641// Otherwise return a BinderProxy for the IBinder. If a previous call was passed the
642// same IBinder, and the original BinderProxy is still alive, return the same BinderProxy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
644{
645 if (val == NULL) return NULL;
646
647 if (val->checkSubclass(&gBinderOffsets)) {
Hans Boehm29f388f2017-10-03 18:01:20 -0700648 // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 jobject object = static_cast<JavaBBinder*>(val.get())->object();
Christopher Tate86284c62011-08-17 15:19:29 -0700650 LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 return object;
652 }
653
654 // For the rest of the function we will hold this lock, to serialize
Christopher Tate10c3a282016-02-26 17:48:08 -0800655 // looking/creation/destruction of Java proxies for native Binder proxies.
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700656 AutoMutex _l(gProxyLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657
Hans Boehm29f388f2017-10-03 18:01:20 -0700658 BinderProxyNativeData* nativeData = gNativeDataCache;
659 if (nativeData == nullptr) {
660 nativeData = new BinderProxyNativeData();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 }
Hans Boehm29f388f2017-10-03 18:01:20 -0700662 // gNativeDataCache is now logically empty.
663 jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
664 gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
665 if (env->ExceptionCheck()) {
Hans Boehm03477cb2018-02-15 16:12:51 -0800666 // In the exception case, getInstance still took ownership of nativeData.
667 gNativeDataCache = nullptr;
Hans Boehm29f388f2017-10-03 18:01:20 -0700668 return NULL;
669 }
670 BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
671 if (actualNativeData == nativeData) {
672 // New BinderProxy; we still have exclusive access.
673 nativeData->mOrgue = new DeathRecipientList;
674 nativeData->mObject = val;
675 gNativeDataCache = nullptr;
676 ++gNumProxies;
Martijn Coenen5183c0e2018-02-07 10:25:39 +0100677 if (gNumProxies >= gProxiesWarned + PROXY_WARN_INTERVAL) {
Hans Boehm29f388f2017-10-03 18:01:20 -0700678 ALOGW("Unexpectedly many live BinderProxies: %d\n", gNumProxies);
679 gProxiesWarned = gNumProxies;
680 }
681 } else {
682 // nativeData wasn't used. Reuse it the next time.
683 gNativeDataCache = nativeData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
685
686 return object;
687}
688
689sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
690{
691 if (obj == NULL) return NULL;
692
Hans Boehm29f388f2017-10-03 18:01:20 -0700693 // Instance of Binder?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
695 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000696 env->GetLongField(obj, gBinderOffsets.mObject);
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700697 return jbh->get(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 }
699
Hans Boehm29f388f2017-10-03 18:01:20 -0700700 // Instance of BinderProxy?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700702 return getBPNativeData(env, obj)->mObject;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704
Steve Block8564c8d2012-01-05 23:22:43 +0000705 ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 return NULL;
707}
708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
710{
711 return env->NewObject(
712 gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
713}
714
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -0800715void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
716{
717 // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
718 // to sync our state back to it. See the comments in StrictMode.java.
719 env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
720 gStrictModeCallbackOffsets.mCallback,
721 strict_policy);
722}
723
724void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
Dianne Hackborne5c42622015-05-19 16:04:04 -0700725 bool canThrowRemoteException, int parcelSize)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726{
727 switch (err) {
728 case UNKNOWN_ERROR:
729 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
730 break;
731 case NO_MEMORY:
732 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
733 break;
734 case INVALID_OPERATION:
735 jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
736 break;
737 case BAD_VALUE:
738 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
739 break;
740 case BAD_INDEX:
741 jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
742 break;
743 case BAD_TYPE:
744 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
745 break;
746 case NAME_NOT_FOUND:
747 jniThrowException(env, "java/util/NoSuchElementException", NULL);
748 break;
749 case PERMISSION_DENIED:
750 jniThrowException(env, "java/lang/SecurityException", NULL);
751 break;
752 case NOT_ENOUGH_DATA:
753 jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
754 break;
755 case NO_INIT:
756 jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
757 break;
758 case ALREADY_EXISTS:
759 jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
760 break;
761 case DEAD_OBJECT:
Jeff Brown0bde66a2011-11-07 12:50:08 -0800762 // DeadObjectException is a checked exception, only throw from certain methods.
763 jniThrowException(env, canThrowRemoteException
764 ? "android/os/DeadObjectException"
765 : "java/lang/RuntimeException", NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 break;
767 case UNKNOWN_TRANSACTION:
768 jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
769 break;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700770 case FAILED_TRANSACTION: {
771 ALOGE("!!! FAILED BINDER TRANSACTION !!! (parcel size = %d)", parcelSize);
Christopher Tate02ca7a72015-06-24 18:16:42 -0700772 const char* exceptionToThrow;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700773 char msg[128];
Jeff Brown0bde66a2011-11-07 12:50:08 -0800774 // TransactionTooLargeException is a checked exception, only throw from certain methods.
775 // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
776 // but it is not the only one. The Binder driver can return BR_FAILED_REPLY
777 // for other reasons also, such as if the transaction is malformed or
778 // refers to an FD that has been closed. We should change the driver
779 // to enable us to distinguish these cases in the future.
Christopher Tate02ca7a72015-06-24 18:16:42 -0700780 if (canThrowRemoteException && parcelSize > 200*1024) {
781 // bona fide large payload
782 exceptionToThrow = "android/os/TransactionTooLargeException";
783 snprintf(msg, sizeof(msg)-1, "data parcel size %d bytes", parcelSize);
784 } else {
785 // Heuristic: a payload smaller than this threshold "shouldn't" be too
786 // big, so it's probably some other, more subtle problem. In practice
Christopher Tateffd58642015-06-29 11:00:15 -0700787 // it seems to always mean that the remote process died while the binder
Christopher Tate02ca7a72015-06-24 18:16:42 -0700788 // transaction was already in flight.
Christopher Tateffd58642015-06-29 11:00:15 -0700789 exceptionToThrow = (canThrowRemoteException)
790 ? "android/os/DeadObjectException"
791 : "java/lang/RuntimeException";
Christopher Tate02ca7a72015-06-24 18:16:42 -0700792 snprintf(msg, sizeof(msg)-1,
793 "Transaction failed on small parcel; remote process probably died");
794 }
795 jniThrowException(env, exceptionToThrow, msg);
Dianne Hackborne5c42622015-05-19 16:04:04 -0700796 } break;
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -0400797 case FDS_NOT_ALLOWED:
798 jniThrowException(env, "java/lang/RuntimeException",
799 "Not allowed to write file descriptors here");
800 break;
Christopher Wileya94fc522015-11-22 14:21:25 -0800801 case UNEXPECTED_NULL:
802 jniThrowNullPointerException(env, NULL);
803 break;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700804 case -EBADF:
805 jniThrowException(env, "java/lang/RuntimeException",
806 "Bad file descriptor");
807 break;
808 case -ENFILE:
809 jniThrowException(env, "java/lang/RuntimeException",
810 "File table overflow");
811 break;
812 case -EMFILE:
813 jniThrowException(env, "java/lang/RuntimeException",
814 "Too many open files");
815 break;
816 case -EFBIG:
817 jniThrowException(env, "java/lang/RuntimeException",
818 "File too large");
819 break;
820 case -ENOSPC:
821 jniThrowException(env, "java/lang/RuntimeException",
822 "No space left on device");
823 break;
824 case -ESPIPE:
825 jniThrowException(env, "java/lang/RuntimeException",
826 "Illegal seek");
827 break;
828 case -EROFS:
829 jniThrowException(env, "java/lang/RuntimeException",
830 "Read-only file system");
831 break;
832 case -EMLINK:
833 jniThrowException(env, "java/lang/RuntimeException",
834 "Too many links");
835 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 default:
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700837 ALOGE("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800838 String8 msg;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700839 msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800840 // RemoteException is a checked exception, only throw from certain methods.
841 jniThrowException(env, canThrowRemoteException
842 ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
843 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845}
846
847}
848
849// ----------------------------------------------------------------------------
850
851static jint android_os_Binder_getCallingPid(JNIEnv* env, jobject clazz)
852{
853 return IPCThreadState::self()->getCallingPid();
854}
855
856static jint android_os_Binder_getCallingUid(JNIEnv* env, jobject clazz)
857{
858 return IPCThreadState::self()->getCallingUid();
859}
860
861static jlong android_os_Binder_clearCallingIdentity(JNIEnv* env, jobject clazz)
862{
863 return IPCThreadState::self()->clearCallingIdentity();
864}
865
866static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
867{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700868 // XXX temporary sanity check to debug crashes.
869 int uid = (int)(token>>32);
870 if (uid > 0 && uid < 999) {
871 // In Android currently there are no uids in this range.
872 char buf[128];
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700873 sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700874 jniThrowException(env, "java/lang/IllegalStateException", buf);
875 return;
876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 IPCThreadState::self()->restoreCallingIdentity(token);
878}
879
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700880static void android_os_Binder_setThreadStrictModePolicy(JNIEnv* env, jobject clazz, jint policyMask)
881{
882 IPCThreadState::self()->setStrictModePolicy(policyMask);
883}
884
885static jint android_os_Binder_getThreadStrictModePolicy(JNIEnv* env, jobject clazz)
886{
887 return IPCThreadState::self()->getStrictModePolicy();
888}
889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
891{
892 IPCThreadState::self()->flushCommands();
893}
894
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700895static jlong android_os_Binder_getNativeBBinderHolder(JNIEnv* env, jobject clazz)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896{
Christopher Tate0b414482011-02-17 13:00:38 -0800897 JavaBBinderHolder* jbh = new JavaBBinderHolder();
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700898 return (jlong) jbh;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899}
900
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700901static void Binder_destroy(void* rawJbh)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902{
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700903 JavaBBinderHolder* jbh = (JavaBBinderHolder*) rawJbh;
904 ALOGV("Java Binder: deleting holder %p", jbh);
905 delete jbh;
906}
907
908JNIEXPORT jlong JNICALL android_os_Binder_getNativeFinalizer(JNIEnv*, jclass) {
909 return (jlong) Binder_destroy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910}
911
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700912static void android_os_Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz)
913{
914 return IPCThreadState::self()->blockUntilThreadAvailable();
915}
916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917// ----------------------------------------------------------------------------
918
919static const JNINativeMethod gBinderMethods[] = {
920 /* name, signature, funcPtr */
921 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
922 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
923 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
924 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700925 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
926 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700928 { "getNativeBBinderHolder", "()J", (void*)android_os_Binder_getNativeBBinderHolder },
929 { "getNativeFinalizer", "()J", (void*)android_os_Binder_getNativeFinalizer },
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700930 { "blockUntilThreadAvailable", "()V", (void*)android_os_Binder_blockUntilThreadAvailable }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931};
932
933const char* const kBinderPathName = "android/os/Binder";
934
935static int int_register_android_os_Binder(JNIEnv* env)
936{
Andreas Gampe987f79f2014-11-18 17:29:46 -0800937 jclass clazz = FindClassOrDie(env, kBinderPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938
Andreas Gampe987f79f2014-11-18 17:29:46 -0800939 gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
940 gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
941 gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800943 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 env, kBinderPathName,
945 gBinderMethods, NELEM(gBinderMethods));
946}
947
948// ****************************************************************************
949// ****************************************************************************
950// ****************************************************************************
951
952namespace android {
953
954jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
955{
Hans Boehm29f388f2017-10-03 18:01:20 -0700956 return gNumLocalRefsCreated - gNumLocalRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957}
958
959jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
960{
Hans Boehm29f388f2017-10-03 18:01:20 -0700961 AutoMutex _l(gProxyLock);
962 return gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963}
964
965jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
966{
Hans Boehm29f388f2017-10-03 18:01:20 -0700967 return gNumDeathRefsCreated - gNumDeathRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968}
969
970}
971
972// ****************************************************************************
973// ****************************************************************************
974// ****************************************************************************
975
976static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
977{
978 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
979 return javaObjectForIBinder(env, b);
980}
981
982static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
983{
984 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
985 android::IPCThreadState::self()->joinThreadPool();
986}
987
Dianne Hackborn887f3552009-12-07 17:59:37 -0800988static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
989 jobject clazz, jboolean disable)
990{
991 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
992}
993
Tim Murrayeef4a3d2016-04-19 14:14:20 -0700994static void android_os_BinderInternal_setMaxThreads(JNIEnv* env,
995 jobject clazz, jint maxThreads)
996{
997 ProcessState::self()->setThreadPoolMaxThreadCount(maxThreads);
998}
999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
1001{
Hans Boehm29f388f2017-10-03 18:01:20 -07001002 ALOGV("Gc has executed, updating Refs count at GC");
1003 gCollectedAtRefs = gNumLocalRefsCreated + gNumDeathRefsCreated;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004}
1005
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001006static void android_os_BinderInternal_proxyLimitcallback(int uid)
1007{
1008 JNIEnv *env = AndroidRuntime::getJNIEnv();
1009 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
1010 gBinderInternalOffsets.mProxyLimitCallback,
1011 uid);
1012}
1013
1014static void android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv* env, jobject clazz,
1015 jboolean enable)
1016{
1017 BpBinder::setCountByUidEnabled((bool) enable);
1018}
1019
1020static jobject android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv* env, jclass clazz)
1021{
1022 Vector<uint32_t> uids, counts;
1023 BpBinder::getCountByUid(uids, counts);
1024 jobject sparseIntArray = env->NewObject(gSparseIntArrayOffsets.classObject,
1025 gSparseIntArrayOffsets.constructor);
1026 for (size_t i = 0; i < uids.size(); i++) {
1027 env->CallVoidMethod(sparseIntArray, gSparseIntArrayOffsets.put,
1028 static_cast<jint>(uids[i]), static_cast<jint>(counts[i]));
1029 }
1030 return sparseIntArray;
1031}
1032
1033static jint android_os_BinderInternal_getBinderProxyCount(JNIEnv* env, jobject clazz, jint uid) {
1034 return static_cast<jint>(BpBinder::getBinderProxyCount(static_cast<uint32_t>(uid)));
1035}
1036
1037static void android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv* env, jobject clazz,
1038 jint high, jint low)
1039{
1040 BpBinder::setBinderProxyCountWatermarks(high, low);
1041}
1042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043// ----------------------------------------------------------------------------
1044
1045static const JNINativeMethod gBinderInternalMethods[] = {
1046 /* name, signature, funcPtr */
1047 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
1048 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -08001049 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001050 { "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001051 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
1052 { "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
1053 { "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
1054 { "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
1055 { "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056};
1057
1058const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
1059
1060static int int_register_android_os_BinderInternal(JNIEnv* env)
1061{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001062 jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063
Andreas Gampe987f79f2014-11-18 17:29:46 -08001064 gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1065 gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001066 gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
1067
1068 jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
1069 gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
1070 gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
1071 "<init>", "()V");
1072 gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
1073 "(II)V");
1074
1075 BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001077 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 env, kBinderInternalPathName,
1079 gBinderInternalMethods, NELEM(gBinderInternalMethods));
1080}
1081
1082// ****************************************************************************
1083// ****************************************************************************
1084// ****************************************************************************
1085
1086static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
1087{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001088 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 if (target == NULL) {
1090 return JNI_FALSE;
1091 }
1092 status_t err = target->pingBinder();
1093 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
1094}
1095
1096static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
1097{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001098 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 if (target != NULL) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001100 const String16& desc = target->getInterfaceDescriptor();
Dan Albert66987492014-11-20 11:41:21 -08001101 return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
1102 desc.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
1104 jniThrowException(env, "java/lang/RuntimeException",
1105 "No binder found for object");
1106 return NULL;
1107}
1108
1109static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
1110{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001111 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 if (target == NULL) {
1113 return JNI_FALSE;
1114 }
1115 bool alive = target->isBinderAlive();
1116 return alive ? JNI_TRUE : JNI_FALSE;
1117}
1118
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001119static int getprocname(pid_t pid, char *buf, size_t len) {
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001120 char filename[32];
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001121 FILE *f;
1122
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001123 snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001124 f = fopen(filename, "r");
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001125 if (!f) {
1126 *buf = '\0';
1127 return 1;
1128 }
1129 if (!fgets(buf, len, f)) {
1130 *buf = '\0';
1131 fclose(f);
1132 return 2;
1133 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001134 fclose(f);
1135 return 0;
1136}
1137
1138static bool push_eventlog_string(char** pos, const char* end, const char* str) {
1139 jint len = strlen(str);
1140 int space_needed = 1 + sizeof(len) + len;
1141 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001142 ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001143 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001144 return false;
1145 }
1146 **pos = EVENT_TYPE_STRING;
1147 (*pos)++;
1148 memcpy(*pos, &len, sizeof(len));
1149 *pos += sizeof(len);
1150 memcpy(*pos, str, len);
1151 *pos += len;
1152 return true;
1153}
1154
1155static bool push_eventlog_int(char** pos, const char* end, jint val) {
1156 int space_needed = 1 + sizeof(val);
1157 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001158 ALOGW("not enough space for int. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001159 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001160 return false;
1161 }
1162 **pos = EVENT_TYPE_INT;
1163 (*pos)++;
1164 memcpy(*pos, &val, sizeof(val));
1165 *pos += sizeof(val);
1166 return true;
1167}
1168
1169// From frameworks/base/core/java/android/content/EventLogTags.logtags:
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001170
1171static const bool kEnableBinderSample = false;
1172
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001173#define LOGTAG_BINDER_OPERATION 52004
1174
1175static void conditionally_log_binder_call(int64_t start_millis,
1176 IBinder* target, jint code) {
1177 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1178
1179 int sample_percent;
1180 if (duration_ms >= 500) {
1181 sample_percent = 100;
1182 } else {
1183 sample_percent = 100 * duration_ms / 500;
1184 if (sample_percent == 0) {
1185 return;
1186 }
1187 if (sample_percent < (random() % 100 + 1)) {
1188 return;
1189 }
1190 }
1191
1192 char process_name[40];
1193 getprocname(getpid(), process_name, sizeof(process_name));
1194 String8 desc(target->getInterfaceDescriptor());
1195
1196 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1197 buf[0] = EVENT_TYPE_LIST;
1198 buf[1] = 5;
1199 char* pos = &buf[2];
1200 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1201 if (!push_eventlog_string(&pos, end, desc.string())) return;
1202 if (!push_eventlog_int(&pos, end, code)) return;
1203 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1204 if (!push_eventlog_string(&pos, end, process_name)) return;
1205 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1206 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1207 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1208}
1209
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001210// We only measure binder call durations to potentially log them if
Elliott Hughes06451fe2014-08-18 10:26:52 -07001211// we're on the main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001212static bool should_time_binder_calls() {
Elliott Hughes06451fe2014-08-18 10:26:52 -07001213 return (getpid() == gettid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001214}
1215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001217 jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218{
1219 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001220 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 return JNI_FALSE;
1222 }
1223
1224 Parcel* data = parcelForJavaObject(env, dataObj);
1225 if (data == NULL) {
1226 return JNI_FALSE;
1227 }
1228 Parcel* reply = parcelForJavaObject(env, replyObj);
1229 if (reply == NULL && replyObj != NULL) {
1230 return JNI_FALSE;
1231 }
1232
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001233 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 if (target == NULL) {
1235 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1236 return JNI_FALSE;
1237 }
1238
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001239 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 -08001240 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001241
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001242
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001243 bool time_binder_calls;
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001244 int64_t start_millis;
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001245 if (kEnableBinderSample) {
1246 // Only log the binder call duration for things on the Java-level main thread.
1247 // But if we don't
1248 time_binder_calls = should_time_binder_calls();
1249
1250 if (time_binder_calls) {
1251 start_millis = uptimeMillis();
1252 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001253 }
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 //printf("Transact from Java code to %p sending: ", target); data->print();
1256 status_t err = target->transact(code, *data, reply, flags);
1257 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001258
1259 if (kEnableBinderSample) {
1260 if (time_binder_calls) {
1261 conditionally_log_binder_call(start_millis, target, code);
1262 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001263 }
1264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 if (err == NO_ERROR) {
1266 return JNI_TRUE;
1267 } else if (err == UNKNOWN_TRANSACTION) {
1268 return JNI_FALSE;
1269 }
1270
Dianne Hackborne5c42622015-05-19 16:04:04 -07001271 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 return JNI_FALSE;
1273}
1274
1275static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001276 jobject recipient, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277{
1278 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001279 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 return;
1281 }
1282
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001283 BinderProxyNativeData *nd = getBPNativeData(env, obj);
1284 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285
Christopher Tate79dd31f2011-03-04 17:45:00 -08001286 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287
1288 if (!target->localBinder()) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001289 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001290 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001291 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 if (err != NO_ERROR) {
1293 // Failure adding the death recipient, so clear its reference
1294 // now.
1295 jdr->clearReference();
Jeff Brown0bde66a2011-11-07 12:50:08 -08001296 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
1298 }
1299}
1300
1301static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1302 jobject recipient, jint flags)
1303{
1304 jboolean res = JNI_FALSE;
1305 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001306 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 return res;
1308 }
1309
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001310 BinderProxyNativeData* nd = getBPNativeData(env, obj);
1311 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001313 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 return JNI_FALSE;
1315 }
1316
Christopher Tate79dd31f2011-03-04 17:45:00 -08001317 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318
1319 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001320 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001321
1322 // If we find the matching recipient, proceed to unlink using that
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001323 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001324 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001325 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001326 if (origJDR != NULL) {
1327 wp<IBinder::DeathRecipient> dr;
1328 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1329 if (err == NO_ERROR && dr != NULL) {
1330 sp<IBinder::DeathRecipient> sdr = dr.promote();
1331 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1332 if (jdr != NULL) {
1333 jdr->clearReference();
1334 }
1335 }
1336 }
1337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 if (err == NO_ERROR || err == DEAD_OBJECT) {
1339 res = JNI_TRUE;
1340 } else {
1341 jniThrowException(env, "java/util/NoSuchElementException",
1342 "Death link does not exist");
1343 }
1344 }
1345
1346 return res;
1347}
1348
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001349static void BinderProxy_destroy(void* rawNativeData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350{
Christopher Tate10c3a282016-02-26 17:48:08 -08001351 // Don't race with construction/initialization
Hans Boehmeb6d62c2017-09-20 15:59:12 -07001352 AutoMutex _l(gProxyLock);
Christopher Tate10c3a282016-02-26 17:48:08 -08001353
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001354 BinderProxyNativeData * nativeData = (BinderProxyNativeData *) rawNativeData;
1355 LOGDEATH("Destroying BinderProxy: binder=%p drl=%p\n",
1356 nativeData->mObject.get(), nativeData->mOrgue.get());
Hans Boehm29f388f2017-10-03 18:01:20 -07001357 delete nativeData;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001358 IPCThreadState::self()->flushCommands();
Hans Boehm29f388f2017-10-03 18:01:20 -07001359 --gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360}
1361
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001362JNIEXPORT jlong JNICALL android_os_BinderProxy_getNativeFinalizer(JNIEnv*, jclass) {
1363 return (jlong) BinderProxy_destroy;
1364}
1365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366// ----------------------------------------------------------------------------
1367
1368static const JNINativeMethod gBinderProxyMethods[] = {
1369 /* name, signature, funcPtr */
1370 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1371 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1372 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001373 {"transactNative", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1375 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001376 {"getNativeFinalizer", "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377};
1378
1379const char* const kBinderProxyPathName = "android/os/BinderProxy";
1380
1381static int int_register_android_os_BinderProxy(JNIEnv* env)
1382{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001383 jclass clazz = FindClassOrDie(env, "java/lang/Error");
1384 gErrorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385
Andreas Gampe987f79f2014-11-18 17:29:46 -08001386 clazz = FindClassOrDie(env, kBinderProxyPathName);
1387 gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
Hans Boehm29f388f2017-10-03 18:01:20 -07001388 gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance",
1389 "(JJ)Landroid/os/BinderProxy;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001390 gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
1391 "(Landroid/os/IBinder$DeathRecipient;)V");
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001392 gBinderProxyOffsets.mNativeData = GetFieldIDOrDie(env, clazz, "mNativeData", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393
Andreas Gampe987f79f2014-11-18 17:29:46 -08001394 clazz = FindClassOrDie(env, "java/lang/Class");
1395 gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
Christopher Tate0d4a7922011-08-30 12:09:43 -07001396
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001397 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 env, kBinderProxyPathName,
1399 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1400}
1401
1402// ****************************************************************************
1403// ****************************************************************************
1404// ****************************************************************************
1405
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001406int register_android_os_Binder(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407{
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001408 if (int_register_android_os_Binder(env) < 0)
1409 return -1;
1410 if (int_register_android_os_BinderInternal(env) < 0)
1411 return -1;
1412 if (int_register_android_os_BinderProxy(env) < 0)
1413 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414
Andreas Gampe987f79f2014-11-18 17:29:46 -08001415 jclass clazz = FindClassOrDie(env, "android/util/Log");
1416 gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1417 gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
1418 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419
Andreas Gampe987f79f2014-11-18 17:29:46 -08001420 clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
1421 gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1422 gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
1423 "(Ljava/io/FileDescriptor;)V");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424
Andreas Gampe987f79f2014-11-18 17:29:46 -08001425 clazz = FindClassOrDie(env, "android/os/StrictMode");
1426 gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1427 gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
1428 "onBinderStrictModePolicyChange", "(I)V");
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001429
Andreas Gampe1cd76f52017-09-08 17:44:05 -07001430 clazz = FindClassOrDie(env, "java/lang/Thread");
1431 gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1432 gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
1433 "dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
1434 gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
1435 "()Ljava/lang/Thread;");
1436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 return 0;
1438}