blob: fd042b39f7c27d035ef5bb5513e3172f9cf2a8d7 [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>
Steven Morelande52bb7d2018-10-10 11:24:58 -070026#include <mutex>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027#include <stdio.h>
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -070028#include <sys/stat.h>
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -070029#include <sys/types.h>
Brad Fitzpatrick8f26b322010-03-25 00:25:37 -070030#include <unistd.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Andreas Gampe58383ba2017-06-12 10:43:05 -070032#include <android-base/stringprintf.h>
Mathias Agopian07952722009-05-19 19:08:10 -070033#include <binder/IInterface.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070034#include <binder/IServiceManager.h>
Mathias Agopian07952722009-05-19 19:08:10 -070035#include <binder/IPCThreadState.h>
Mathias Agopian07952722009-05-19 19:08:10 -070036#include <binder/Parcel.h>
Michael Wachenschwanz55182462017-08-14 23:10:13 -070037#include <binder/BpBinder.h>
Mathias Agopian07952722009-05-19 19:08:10 -070038#include <binder/ProcessState.h>
Steven Morelandfb7952f2018-02-23 14:58:50 -080039#include <cutils/atomic.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070040#include <log/log.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070041#include <utils/KeyedVector.h>
42#include <utils/List.h>
43#include <utils/Log.h>
Jeff Brown0bde66a2011-11-07 12:50:08 -080044#include <utils/String8.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070045#include <utils/SystemClock.h>
46#include <utils/threads.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
Andreas Gampe625e0002017-09-08 17:44:05 -070048#include <nativehelper/JNIHelp.h>
Steven Moreland2279b252017-07-19 09:50:45 -070049#include <nativehelper/ScopedLocalRef.h>
Andreas Gampe625e0002017-09-08 17:44:05 -070050#include <nativehelper/ScopedUtfChars.h>
Christopher Tateac5e3502011-08-25 15:48:09 -070051
Andreas Gampe987f79f2014-11-18 17:29:46 -080052#include "core_jni_helpers.h"
53
Steve Block71f2cf12011-10-20 11:56:00 +010054//#undef ALOGV
55//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Christopher Tate79dd31f2011-03-04 17:45:00 -080057#define DEBUG_DEATH 0
58#if DEBUG_DEATH
Steve Block5baa3a62011-12-20 16:23:08 +000059#define LOGDEATH ALOGD
Christopher Tate79dd31f2011-03-04 17:45:00 -080060#else
Steve Block71f2cf12011-10-20 11:56:00 +010061#define LOGDEATH ALOGV
Christopher Tate79dd31f2011-03-04 17:45:00 -080062#endif
63
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064using namespace android;
65
66// ----------------------------------------------------------------------------
67
68static struct bindernative_offsets_t
69{
70 // Class state.
71 jclass mClass;
72 jmethodID mExecTransact;
Steven Morelande52bb7d2018-10-10 11:24:58 -070073 jmethodID mGetInterfaceDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074
75 // Object state.
76 jfieldID mObject;
77
78} gBinderOffsets;
79
80// ----------------------------------------------------------------------------
81
82static struct binderinternal_offsets_t
83{
84 // Class state.
85 jclass mClass;
86 jmethodID mForceGc;
Michael Wachenschwanz55182462017-08-14 23:10:13 -070087 jmethodID mProxyLimitCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
89} gBinderInternalOffsets;
90
Michael Wachenschwanz55182462017-08-14 23:10:13 -070091static struct sparseintarray_offsets_t
92{
93 jclass classObject;
94 jmethodID constructor;
95 jmethodID put;
96} gSparseIntArrayOffsets;
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098// ----------------------------------------------------------------------------
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100static struct error_offsets_t
101{
102 jclass mClass;
103} gErrorOffsets;
104
105// ----------------------------------------------------------------------------
106
107static struct binderproxy_offsets_t
108{
109 // Class state.
110 jclass mClass;
Hans Boehm29f388f2017-10-03 18:01:20 -0700111 jmethodID mGetInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 jmethodID mSendDeathNotice;
113
114 // Object state.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700115 jfieldID mNativeData; // Field holds native pointer to BinderProxyNativeData.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116} gBinderProxyOffsets;
117
Christopher Tate0d4a7922011-08-30 12:09:43 -0700118static struct class_offsets_t
119{
120 jmethodID mGetName;
121} gClassOffsets;
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123// ----------------------------------------------------------------------------
124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125static struct log_offsets_t
126{
127 // Class state.
128 jclass mClass;
129 jmethodID mLogE;
130} gLogOffsets;
131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132static struct parcel_file_descriptor_offsets_t
133{
134 jclass mClass;
135 jmethodID mConstructor;
136} gParcelFileDescriptorOffsets;
137
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700138static struct strict_mode_callback_offsets_t
139{
140 jclass mClass;
141 jmethodID mCallback;
142} gStrictModeCallbackOffsets;
143
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700144static struct thread_dispatch_offsets_t
145{
146 // Class state.
147 jclass mClass;
148 jmethodID mDispatchUncaughtException;
149 jmethodID mCurrentThread;
150} gThreadDispatchOffsets;
151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152// ****************************************************************************
153// ****************************************************************************
154// ****************************************************************************
155
Hans Boehm29f388f2017-10-03 18:01:20 -0700156static constexpr int32_t PROXY_WARN_INTERVAL = 5000;
157static constexpr uint32_t GC_INTERVAL = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200159static std::atomic<uint32_t> gNumProxies(0);
160static std::atomic<uint32_t> gProxiesWarned(0);
Hans Boehm29f388f2017-10-03 18:01:20 -0700161
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
Steven Morelande52bb7d2018-10-10 11:24:58 -0700331 const String16& getInterfaceDescriptor() const override
332 {
333 call_once(mPopulateDescriptor, [this] {
334 JNIEnv* env = javavm_to_jnienv(mVM);
335
336 ALOGV("getInterfaceDescriptor() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
337
338 jstring descriptor = (jstring)env->CallObjectMethod(mObject, gBinderOffsets.mGetInterfaceDescriptor);
339
340 if (descriptor == nullptr) {
341 return;
342 }
343
344 static_assert(sizeof(jchar) == sizeof(char16_t), "");
345 const jchar* descriptorChars = env->GetStringChars(descriptor, nullptr);
346 const char16_t* rawDescriptor = reinterpret_cast<const char16_t*>(descriptorChars);
347 jsize rawDescriptorLen = env->GetStringLength(descriptor);
348 mDescriptor = String16(rawDescriptor, rawDescriptorLen);
349 env->ReleaseStringChars(descriptor, descriptorChars);
350 });
351
352 return mDescriptor;
353 }
354
355 status_t onTransact(
356 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0) override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 {
358 JNIEnv* env = javavm_to_jnienv(mVM);
359
Steve Block71f2cf12011-10-20 11:56:00 +0100360 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 -0800361
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700362 IPCThreadState* thread_state = IPCThreadState::self();
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700363 const int32_t strict_policy_before = thread_state->getStrictModePolicy();
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 //printf("Transact from %p to Java code sending: ", this);
366 //data.print();
367 //printf("\n");
368 jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000369 code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700370
Mathieu Chartier98671c32014-08-20 10:04:08 -0700371 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700372 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
373 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100374 "*** Uncaught remote exception! "
375 "(Exceptions are not yet supported across processes.)");
376 res = JNI_FALSE;
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100377 }
378
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700379 // Check if the strict mode state changed while processing the
380 // call. The Binder state will be restored by the underlying
381 // Binder system in IPCThreadState, however we need to take care
382 // of the parallel Java state as well.
383 if (thread_state->getStrictModePolicy() != strict_policy_before) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700384 set_dalvik_blockguard_policy(env, strict_policy_before);
385 }
386
Mathieu Chartier98671c32014-08-20 10:04:08 -0700387 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700388 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
389 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100390 "*** Uncaught exception in onBinderStrictModePolicyChange");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 }
392
Dianne Hackborna53de062012-05-08 18:53:51 -0700393 // Need to always call through the native implementation of
394 // SYSPROPS_TRANSACTION.
395 if (code == SYSPROPS_TRANSACTION) {
396 BBinder::onTransact(code, data, reply, flags);
397 }
398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 //aout << "onTransact to Java code; result=" << res << endl
400 // << "Transact from " << this << " to Java code returning "
401 // << reply << ": " << *reply << endl;
402 return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
403 }
404
Steven Morelande52bb7d2018-10-10 11:24:58 -0700405 status_t dump(int fd, const Vector<String16>& args) override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 {
407 return 0;
408 }
409
410private:
411 JavaVM* const mVM;
Hans Boehm29f388f2017-10-03 18:01:20 -0700412 jobject const mObject; // GlobalRef to Java Binder
Steven Morelande52bb7d2018-10-10 11:24:58 -0700413
414 mutable std::once_flag mPopulateDescriptor;
415 mutable String16 mDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800416};
417
418// ----------------------------------------------------------------------------
419
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700420class JavaBBinderHolder
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421{
422public:
Christopher Tate0b414482011-02-17 13:00:38 -0800423 sp<JavaBBinder> get(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 {
425 AutoMutex _l(mLock);
426 sp<JavaBBinder> b = mBinder.promote();
427 if (b == NULL) {
Christopher Tate0b414482011-02-17 13:00:38 -0800428 b = new JavaBBinder(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 mBinder = b;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700430 ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
Christopher Tate0b414482011-02-17 13:00:38 -0800431 b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 }
433
434 return b;
435 }
436
437 sp<JavaBBinder> getExisting()
438 {
439 AutoMutex _l(mLock);
440 return mBinder.promote();
441 }
442
443private:
444 Mutex mLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 wp<JavaBBinder> mBinder;
446};
447
448// ----------------------------------------------------------------------------
449
Christopher Tate0b414482011-02-17 13:00:38 -0800450// Per-IBinder death recipient bookkeeping. This is how we reconcile local jobject
451// death recipient references passed in through JNI with the permanent corresponding
452// JavaDeathRecipient objects.
453
454class JavaDeathRecipient;
455
456class DeathRecipientList : public RefBase {
457 List< sp<JavaDeathRecipient> > mList;
458 Mutex mLock;
459
460public:
Christopher Tate79dd31f2011-03-04 17:45:00 -0800461 DeathRecipientList();
Christopher Tate0b414482011-02-17 13:00:38 -0800462 ~DeathRecipientList();
463
464 void add(const sp<JavaDeathRecipient>& recipient);
465 void remove(const sp<JavaDeathRecipient>& recipient);
466 sp<JavaDeathRecipient> find(jobject recipient);
Christopher Tate090c08f2015-05-19 18:16:58 -0700467
468 Mutex& lock(); // Use with care; specifically for mutual exclusion during binder death
Christopher Tate0b414482011-02-17 13:00:38 -0800469};
470
471// ----------------------------------------------------------------------------
472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473class JavaDeathRecipient : public IBinder::DeathRecipient
474{
475public:
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800476 JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
Christopher Tate86284c62011-08-17 15:19:29 -0700477 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
478 mObjectWeak(NULL), mList(list)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 {
Christopher Tate0b414482011-02-17 13:00:38 -0800480 // These objects manage their own lifetimes so are responsible for final bookkeeping.
481 // The list holds a strong reference to this object.
Christopher Tate79dd31f2011-03-04 17:45:00 -0800482 LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800483 list->add(this);
Christopher Tate0b414482011-02-17 13:00:38 -0800484
Hans Boehm29f388f2017-10-03 18:01:20 -0700485 gNumDeathRefsCreated.fetch_add(1, std::memory_order_relaxed);
486 gcIfManyNewRefs(env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
488
489 void binderDied(const wp<IBinder>& who)
490 {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800491 LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
Christopher Tate86284c62011-08-17 15:19:29 -0700492 if (mObject != NULL) {
493 JNIEnv* env = javavm_to_jnienv(mVM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494
Christopher Tate86284c62011-08-17 15:19:29 -0700495 env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
496 gBinderProxyOffsets.mSendDeathNotice, mObject);
Mathieu Chartier98671c32014-08-20 10:04:08 -0700497 if (env->ExceptionCheck()) {
498 jthrowable excep = env->ExceptionOccurred();
Christopher Tate86284c62011-08-17 15:19:29 -0700499 report_exception(env, excep,
500 "*** Uncaught exception returned from death notification!");
501 }
502
Christopher Tate090c08f2015-05-19 18:16:58 -0700503 // Serialize with our containing DeathRecipientList so that we can't
504 // delete the global ref on mObject while the list is being iterated.
505 sp<DeathRecipientList> list = mList.promote();
506 if (list != NULL) {
507 AutoMutex _l(list->lock());
508
509 // Demote from strong ref to weak after binderDied() has been delivered,
510 // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
511 mObjectWeak = env->NewWeakGlobalRef(mObject);
512 env->DeleteGlobalRef(mObject);
513 mObject = NULL;
514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 }
517
518 void clearReference()
519 {
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800520 sp<DeathRecipientList> list = mList.promote();
521 if (list != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800522 LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800523 list->remove(this);
Christopher Tate79dd31f2011-03-04 17:45:00 -0800524 } else {
525 LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800526 }
Christopher Tate0b414482011-02-17 13:00:38 -0800527 }
528
529 bool matches(jobject obj) {
Christopher Tate86284c62011-08-17 15:19:29 -0700530 bool result;
Christopher Tate0b414482011-02-17 13:00:38 -0800531 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700532
533 if (mObject != NULL) {
534 result = env->IsSameObject(obj, mObject);
535 } else {
Andreas Gampe625e0002017-09-08 17:44:05 -0700536 ScopedLocalRef<jobject> me(env, env->NewLocalRef(mObjectWeak));
537 result = env->IsSameObject(obj, me.get());
Christopher Tate86284c62011-08-17 15:19:29 -0700538 }
539 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541
Christopher Tateac5e3502011-08-25 15:48:09 -0700542 void warnIfStillLive() {
543 if (mObject != NULL) {
544 // Okay, something is wrong -- we have a hard reference to a live death
545 // recipient on the VM side, but the list is being torn down.
546 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate0d4a7922011-08-30 12:09:43 -0700547 ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
548 ScopedLocalRef<jstring> nameRef(env,
549 (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
550 ScopedUtfChars nameUtf(env, nameRef.get());
551 if (nameUtf.c_str() != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000552 ALOGW("BinderProxy is being destroyed but the application did not call "
Christopher Tate0d4a7922011-08-30 12:09:43 -0700553 "unlinkToDeath to unlink all of its death recipients beforehand. "
554 "Releasing leaked death recipient: %s", nameUtf.c_str());
555 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000556 ALOGW("BinderProxy being destroyed; unable to get DR object name");
Christopher Tate0d4a7922011-08-30 12:09:43 -0700557 env->ExceptionClear();
558 }
Christopher Tateac5e3502011-08-25 15:48:09 -0700559 }
560 }
561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562protected:
563 virtual ~JavaDeathRecipient()
564 {
Steve Block6215d3f2012-01-04 20:05:49 +0000565 //ALOGI("Removing death ref: recipient=%p\n", mObject);
Hans Boehm29f388f2017-10-03 18:01:20 -0700566 gNumDeathRefsDeleted.fetch_add(1, std::memory_order_relaxed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700568 if (mObject != NULL) {
569 env->DeleteGlobalRef(mObject);
570 } else {
571 env->DeleteWeakGlobalRef(mObjectWeak);
572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 }
574
575private:
Christopher Tate86284c62011-08-17 15:19:29 -0700576 JavaVM* const mVM;
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700577 jobject mObject; // Initial strong ref to Java-side DeathRecipient. Cleared on binderDied().
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700578 jweak mObjectWeak; // Weak ref to the same Java-side DeathRecipient after binderDied().
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800579 wp<DeathRecipientList> mList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580};
581
582// ----------------------------------------------------------------------------
583
Christopher Tate79dd31f2011-03-04 17:45:00 -0800584DeathRecipientList::DeathRecipientList() {
585 LOGDEATH("New DRL @ %p", this);
586}
587
Christopher Tate0b414482011-02-17 13:00:38 -0800588DeathRecipientList::~DeathRecipientList() {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800589 LOGDEATH("Destroy DRL @ %p", this);
Christopher Tate0b414482011-02-17 13:00:38 -0800590 AutoMutex _l(mLock);
591
592 // Should never happen -- the JavaDeathRecipient objects that have added themselves
593 // to the list are holding references on the list object. Only when they are torn
594 // down can the list header be destroyed.
595 if (mList.size() > 0) {
Christopher Tateac5e3502011-08-25 15:48:09 -0700596 List< sp<JavaDeathRecipient> >::iterator iter;
597 for (iter = mList.begin(); iter != mList.end(); iter++) {
598 (*iter)->warnIfStillLive();
599 }
Christopher Tate0b414482011-02-17 13:00:38 -0800600 }
601}
602
603void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
604 AutoMutex _l(mLock);
605
Christopher Tate79dd31f2011-03-04 17:45:00 -0800606 LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800607 mList.push_back(recipient);
608}
609
610void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
611 AutoMutex _l(mLock);
612
613 List< sp<JavaDeathRecipient> >::iterator iter;
614 for (iter = mList.begin(); iter != mList.end(); iter++) {
615 if (*iter == recipient) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800616 LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800617 mList.erase(iter);
618 return;
619 }
620 }
621}
622
623sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
624 AutoMutex _l(mLock);
625
626 List< sp<JavaDeathRecipient> >::iterator iter;
627 for (iter = mList.begin(); iter != mList.end(); iter++) {
628 if ((*iter)->matches(recipient)) {
629 return *iter;
630 }
631 }
632 return NULL;
633}
634
Christopher Tate090c08f2015-05-19 18:16:58 -0700635Mutex& DeathRecipientList::lock() {
636 return mLock;
637}
638
Christopher Tate0b414482011-02-17 13:00:38 -0800639// ----------------------------------------------------------------------------
640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641namespace android {
642
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700643// We aggregate native pointer fields for BinderProxy in a single object to allow
644// management with a single NativeAllocationRegistry, and to reduce the number of JNI
645// Java field accesses. This costs us some extra indirections here.
646struct BinderProxyNativeData {
Hans Boehm29f388f2017-10-03 18:01:20 -0700647 // Both fields are constant and not null once javaObjectForIBinder returns this as
648 // part of a BinderProxy.
649
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700650 // The native IBinder proxied by this BinderProxy.
Hans Boehm29f388f2017-10-03 18:01:20 -0700651 sp<IBinder> mObject;
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700652
653 // Death recipients for mObject. Reference counted only because DeathRecipients
654 // hold a weak reference that can be temporarily promoted.
Hans Boehm29f388f2017-10-03 18:01:20 -0700655 sp<DeathRecipientList> mOrgue; // Death recipients for mObject.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700656};
657
658BinderProxyNativeData* getBPNativeData(JNIEnv* env, jobject obj) {
659 return (BinderProxyNativeData *) env->GetLongField(obj, gBinderProxyOffsets.mNativeData);
660}
661
Hans Boehm29f388f2017-10-03 18:01:20 -0700662// If the argument is a JavaBBinder, return the Java object that was used to create it.
663// Otherwise return a BinderProxy for the IBinder. If a previous call was passed the
664// same IBinder, and the original BinderProxy is still alive, return the same BinderProxy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
666{
667 if (val == NULL) return NULL;
668
669 if (val->checkSubclass(&gBinderOffsets)) {
Hans Boehm29f388f2017-10-03 18:01:20 -0700670 // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 jobject object = static_cast<JavaBBinder*>(val.get())->object();
Christopher Tate86284c62011-08-17 15:19:29 -0700672 LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 return object;
674 }
675
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200676 BinderProxyNativeData* nativeData = new BinderProxyNativeData();
677 nativeData->mOrgue = new DeathRecipientList;
678 nativeData->mObject = val;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679
Hans Boehm29f388f2017-10-03 18:01:20 -0700680 jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
681 gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
682 if (env->ExceptionCheck()) {
Hans Boehm03477cb2018-02-15 16:12:51 -0800683 // In the exception case, getInstance still took ownership of nativeData.
Hans Boehm29f388f2017-10-03 18:01:20 -0700684 return NULL;
685 }
686 BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
687 if (actualNativeData == nativeData) {
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200688 // Created a new Proxy
689 uint32_t numProxies = gNumProxies.fetch_add(1, std::memory_order_relaxed);
690 uint32_t numLastWarned = gProxiesWarned.load(std::memory_order_relaxed);
691 if (numProxies >= numLastWarned + PROXY_WARN_INTERVAL) {
692 // Multiple threads can get here, make sure only one of them gets to
693 // update the warn counter.
694 if (gProxiesWarned.compare_exchange_strong(numLastWarned,
695 numLastWarned + PROXY_WARN_INTERVAL, std::memory_order_relaxed)) {
696 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
697 }
Hans Boehm29f388f2017-10-03 18:01:20 -0700698 }
699 } else {
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200700 delete nativeData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 }
702
703 return object;
704}
705
706sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
707{
708 if (obj == NULL) return NULL;
709
Hans Boehm29f388f2017-10-03 18:01:20 -0700710 // Instance of Binder?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
712 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000713 env->GetLongField(obj, gBinderOffsets.mObject);
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700714 return jbh->get(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
716
Hans Boehm29f388f2017-10-03 18:01:20 -0700717 // Instance of BinderProxy?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700719 return getBPNativeData(env, obj)->mObject;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
721
Steve Block8564c8d2012-01-05 23:22:43 +0000722 ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 return NULL;
724}
725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
727{
728 return env->NewObject(
729 gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
730}
731
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -0800732void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
733{
734 // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
735 // to sync our state back to it. See the comments in StrictMode.java.
736 env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
737 gStrictModeCallbackOffsets.mCallback,
738 strict_policy);
739}
740
741void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
Dianne Hackborne5c42622015-05-19 16:04:04 -0700742 bool canThrowRemoteException, int parcelSize)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743{
744 switch (err) {
745 case UNKNOWN_ERROR:
746 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
747 break;
748 case NO_MEMORY:
749 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
750 break;
751 case INVALID_OPERATION:
752 jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
753 break;
754 case BAD_VALUE:
755 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
756 break;
757 case BAD_INDEX:
758 jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
759 break;
760 case BAD_TYPE:
761 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
762 break;
763 case NAME_NOT_FOUND:
764 jniThrowException(env, "java/util/NoSuchElementException", NULL);
765 break;
766 case PERMISSION_DENIED:
767 jniThrowException(env, "java/lang/SecurityException", NULL);
768 break;
769 case NOT_ENOUGH_DATA:
770 jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
771 break;
772 case NO_INIT:
773 jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
774 break;
775 case ALREADY_EXISTS:
776 jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
777 break;
778 case DEAD_OBJECT:
Jeff Brown0bde66a2011-11-07 12:50:08 -0800779 // DeadObjectException is a checked exception, only throw from certain methods.
780 jniThrowException(env, canThrowRemoteException
781 ? "android/os/DeadObjectException"
782 : "java/lang/RuntimeException", NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 break;
784 case UNKNOWN_TRANSACTION:
785 jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
786 break;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700787 case FAILED_TRANSACTION: {
788 ALOGE("!!! FAILED BINDER TRANSACTION !!! (parcel size = %d)", parcelSize);
Christopher Tate02ca7a72015-06-24 18:16:42 -0700789 const char* exceptionToThrow;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700790 char msg[128];
Jeff Brown0bde66a2011-11-07 12:50:08 -0800791 // TransactionTooLargeException is a checked exception, only throw from certain methods.
792 // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
793 // but it is not the only one. The Binder driver can return BR_FAILED_REPLY
794 // for other reasons also, such as if the transaction is malformed or
795 // refers to an FD that has been closed. We should change the driver
796 // to enable us to distinguish these cases in the future.
Christopher Tate02ca7a72015-06-24 18:16:42 -0700797 if (canThrowRemoteException && parcelSize > 200*1024) {
798 // bona fide large payload
799 exceptionToThrow = "android/os/TransactionTooLargeException";
800 snprintf(msg, sizeof(msg)-1, "data parcel size %d bytes", parcelSize);
801 } else {
802 // Heuristic: a payload smaller than this threshold "shouldn't" be too
803 // big, so it's probably some other, more subtle problem. In practice
Christopher Tateffd58642015-06-29 11:00:15 -0700804 // it seems to always mean that the remote process died while the binder
Christopher Tate02ca7a72015-06-24 18:16:42 -0700805 // transaction was already in flight.
Christopher Tateffd58642015-06-29 11:00:15 -0700806 exceptionToThrow = (canThrowRemoteException)
807 ? "android/os/DeadObjectException"
808 : "java/lang/RuntimeException";
Christopher Tate02ca7a72015-06-24 18:16:42 -0700809 snprintf(msg, sizeof(msg)-1,
810 "Transaction failed on small parcel; remote process probably died");
811 }
812 jniThrowException(env, exceptionToThrow, msg);
Dianne Hackborne5c42622015-05-19 16:04:04 -0700813 } break;
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -0400814 case FDS_NOT_ALLOWED:
815 jniThrowException(env, "java/lang/RuntimeException",
816 "Not allowed to write file descriptors here");
817 break;
Christopher Wileya94fc522015-11-22 14:21:25 -0800818 case UNEXPECTED_NULL:
819 jniThrowNullPointerException(env, NULL);
820 break;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700821 case -EBADF:
822 jniThrowException(env, "java/lang/RuntimeException",
823 "Bad file descriptor");
824 break;
825 case -ENFILE:
826 jniThrowException(env, "java/lang/RuntimeException",
827 "File table overflow");
828 break;
829 case -EMFILE:
830 jniThrowException(env, "java/lang/RuntimeException",
831 "Too many open files");
832 break;
833 case -EFBIG:
834 jniThrowException(env, "java/lang/RuntimeException",
835 "File too large");
836 break;
837 case -ENOSPC:
838 jniThrowException(env, "java/lang/RuntimeException",
839 "No space left on device");
840 break;
841 case -ESPIPE:
842 jniThrowException(env, "java/lang/RuntimeException",
843 "Illegal seek");
844 break;
845 case -EROFS:
846 jniThrowException(env, "java/lang/RuntimeException",
847 "Read-only file system");
848 break;
849 case -EMLINK:
850 jniThrowException(env, "java/lang/RuntimeException",
851 "Too many links");
852 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 default:
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700854 ALOGE("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800855 String8 msg;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700856 msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800857 // RemoteException is a checked exception, only throw from certain methods.
858 jniThrowException(env, canThrowRemoteException
859 ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
860 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862}
863
864}
865
866// ----------------------------------------------------------------------------
867
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100868static jint android_os_Binder_getCallingPid()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869{
870 return IPCThreadState::self()->getCallingPid();
871}
872
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100873static jint android_os_Binder_getCallingUid()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874{
875 return IPCThreadState::self()->getCallingUid();
876}
877
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100878static jlong android_os_Binder_clearCallingIdentity()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879{
880 return IPCThreadState::self()->clearCallingIdentity();
881}
882
883static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
884{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700885 // XXX temporary sanity check to debug crashes.
886 int uid = (int)(token>>32);
887 if (uid > 0 && uid < 999) {
888 // In Android currently there are no uids in this range.
889 char buf[128];
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700890 sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700891 jniThrowException(env, "java/lang/IllegalStateException", buf);
892 return;
893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 IPCThreadState::self()->restoreCallingIdentity(token);
895}
896
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100897static void android_os_Binder_setThreadStrictModePolicy(jint policyMask)
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700898{
899 IPCThreadState::self()->setStrictModePolicy(policyMask);
900}
901
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100902static jint android_os_Binder_getThreadStrictModePolicy()
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700903{
904 return IPCThreadState::self()->getStrictModePolicy();
905}
906
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100907static jint android_os_Binder_setThreadWorkSource(jint workSource)
908{
909 return IPCThreadState::self()->setWorkSource(workSource);
910}
911
912static jint android_os_Binder_getThreadWorkSource()
913{
914 return IPCThreadState::self()->getWorkSource();
915}
916
917static jint android_os_Binder_clearThreadWorkSource()
918{
919 return IPCThreadState::self()->clearWorkSource();
920}
921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
923{
924 IPCThreadState::self()->flushCommands();
925}
926
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700927static jlong android_os_Binder_getNativeBBinderHolder(JNIEnv* env, jobject clazz)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928{
Christopher Tate0b414482011-02-17 13:00:38 -0800929 JavaBBinderHolder* jbh = new JavaBBinderHolder();
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700930 return (jlong) jbh;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931}
932
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700933static void Binder_destroy(void* rawJbh)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934{
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700935 JavaBBinderHolder* jbh = (JavaBBinderHolder*) rawJbh;
936 ALOGV("Java Binder: deleting holder %p", jbh);
937 delete jbh;
938}
939
940JNIEXPORT jlong JNICALL android_os_Binder_getNativeFinalizer(JNIEnv*, jclass) {
941 return (jlong) Binder_destroy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942}
943
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700944static void android_os_Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz)
945{
946 return IPCThreadState::self()->blockUntilThreadAvailable();
947}
948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949// ----------------------------------------------------------------------------
950
951static const JNINativeMethod gBinderMethods[] = {
952 /* name, signature, funcPtr */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100953 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100955 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100957 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
959 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100960 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700961 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100962 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700963 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100964 // @CriticalNative
965 { "setThreadWorkSource", "(I)I", (void*)android_os_Binder_setThreadWorkSource },
966 // @CriticalNative
967 { "getThreadWorkSource", "()I", (void*)android_os_Binder_getThreadWorkSource },
968 // @CriticalNative
969 { "clearThreadWorkSource", "()I", (void*)android_os_Binder_clearThreadWorkSource },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700971 { "getNativeBBinderHolder", "()J", (void*)android_os_Binder_getNativeBBinderHolder },
972 { "getNativeFinalizer", "()J", (void*)android_os_Binder_getNativeFinalizer },
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700973 { "blockUntilThreadAvailable", "()V", (void*)android_os_Binder_blockUntilThreadAvailable }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974};
975
976const char* const kBinderPathName = "android/os/Binder";
977
978static int int_register_android_os_Binder(JNIEnv* env)
979{
Andreas Gampe987f79f2014-11-18 17:29:46 -0800980 jclass clazz = FindClassOrDie(env, kBinderPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Andreas Gampe987f79f2014-11-18 17:29:46 -0800982 gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
983 gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
Steven Morelande52bb7d2018-10-10 11:24:58 -0700984 gBinderOffsets.mGetInterfaceDescriptor = GetMethodIDOrDie(env, clazz, "getInterfaceDescriptor",
985 "()Ljava/lang/String;");
Andreas Gampe987f79f2014-11-18 17:29:46 -0800986 gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987
Andreas Gampeed6b9df2014-11-20 22:02:20 -0800988 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 env, kBinderPathName,
990 gBinderMethods, NELEM(gBinderMethods));
991}
992
993// ****************************************************************************
994// ****************************************************************************
995// ****************************************************************************
996
997namespace android {
998
999jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
1000{
Hans Boehm29f388f2017-10-03 18:01:20 -07001001 return gNumLocalRefsCreated - gNumLocalRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002}
1003
1004jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
1005{
Martijn Coenend3ef4bf2018-07-05 14:58:59 +02001006 return gNumProxies.load();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007}
1008
1009jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
1010{
Hans Boehm29f388f2017-10-03 18:01:20 -07001011 return gNumDeathRefsCreated - gNumDeathRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012}
1013
1014}
1015
1016// ****************************************************************************
1017// ****************************************************************************
1018// ****************************************************************************
1019
1020static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
1021{
1022 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1023 return javaObjectForIBinder(env, b);
1024}
1025
1026static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
1027{
1028 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1029 android::IPCThreadState::self()->joinThreadPool();
1030}
1031
Dianne Hackborn887f3552009-12-07 17:59:37 -08001032static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
1033 jobject clazz, jboolean disable)
1034{
1035 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
1036}
1037
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001038static void android_os_BinderInternal_setMaxThreads(JNIEnv* env,
1039 jobject clazz, jint maxThreads)
1040{
1041 ProcessState::self()->setThreadPoolMaxThreadCount(maxThreads);
1042}
1043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
1045{
Hans Boehm29f388f2017-10-03 18:01:20 -07001046 ALOGV("Gc has executed, updating Refs count at GC");
1047 gCollectedAtRefs = gNumLocalRefsCreated + gNumDeathRefsCreated;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048}
1049
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001050static void android_os_BinderInternal_proxyLimitcallback(int uid)
1051{
1052 JNIEnv *env = AndroidRuntime::getJNIEnv();
1053 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
1054 gBinderInternalOffsets.mProxyLimitCallback,
1055 uid);
Martijn Coenendfa390e2018-06-05 11:02:23 +02001056
1057 if (env->ExceptionCheck()) {
1058 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
1059 report_exception(env, excep.get(),
1060 "*** Uncaught exception in binderProxyLimitCallbackFromNative");
1061 }
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001062}
1063
1064static void android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv* env, jobject clazz,
1065 jboolean enable)
1066{
1067 BpBinder::setCountByUidEnabled((bool) enable);
1068}
1069
1070static jobject android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv* env, jclass clazz)
1071{
1072 Vector<uint32_t> uids, counts;
1073 BpBinder::getCountByUid(uids, counts);
1074 jobject sparseIntArray = env->NewObject(gSparseIntArrayOffsets.classObject,
1075 gSparseIntArrayOffsets.constructor);
1076 for (size_t i = 0; i < uids.size(); i++) {
1077 env->CallVoidMethod(sparseIntArray, gSparseIntArrayOffsets.put,
1078 static_cast<jint>(uids[i]), static_cast<jint>(counts[i]));
1079 }
1080 return sparseIntArray;
1081}
1082
1083static jint android_os_BinderInternal_getBinderProxyCount(JNIEnv* env, jobject clazz, jint uid) {
1084 return static_cast<jint>(BpBinder::getBinderProxyCount(static_cast<uint32_t>(uid)));
1085}
1086
1087static void android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv* env, jobject clazz,
1088 jint high, jint low)
1089{
1090 BpBinder::setBinderProxyCountWatermarks(high, low);
1091}
1092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093// ----------------------------------------------------------------------------
1094
1095static const JNINativeMethod gBinderInternalMethods[] = {
1096 /* name, signature, funcPtr */
1097 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
1098 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -08001099 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001100 { "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001101 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
1102 { "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
1103 { "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
1104 { "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
1105 { "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106};
1107
1108const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
1109
1110static int int_register_android_os_BinderInternal(JNIEnv* env)
1111{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001112 jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113
Andreas Gampe987f79f2014-11-18 17:29:46 -08001114 gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1115 gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001116 gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
1117
1118 jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
1119 gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
1120 gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
1121 "<init>", "()V");
1122 gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
1123 "(II)V");
1124
1125 BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001127 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 env, kBinderInternalPathName,
1129 gBinderInternalMethods, NELEM(gBinderInternalMethods));
1130}
1131
1132// ****************************************************************************
1133// ****************************************************************************
1134// ****************************************************************************
1135
1136static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
1137{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001138 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 if (target == NULL) {
1140 return JNI_FALSE;
1141 }
1142 status_t err = target->pingBinder();
1143 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
1144}
1145
1146static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
1147{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001148 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 if (target != NULL) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001150 const String16& desc = target->getInterfaceDescriptor();
Dan Albert66987492014-11-20 11:41:21 -08001151 return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
1152 desc.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
1154 jniThrowException(env, "java/lang/RuntimeException",
1155 "No binder found for object");
1156 return NULL;
1157}
1158
1159static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
1160{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001161 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 if (target == NULL) {
1163 return JNI_FALSE;
1164 }
1165 bool alive = target->isBinderAlive();
1166 return alive ? JNI_TRUE : JNI_FALSE;
1167}
1168
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001169static int getprocname(pid_t pid, char *buf, size_t len) {
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001170 char filename[32];
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001171 FILE *f;
1172
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001173 snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001174 f = fopen(filename, "r");
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001175 if (!f) {
1176 *buf = '\0';
1177 return 1;
1178 }
1179 if (!fgets(buf, len, f)) {
1180 *buf = '\0';
1181 fclose(f);
1182 return 2;
1183 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001184 fclose(f);
1185 return 0;
1186}
1187
1188static bool push_eventlog_string(char** pos, const char* end, const char* str) {
1189 jint len = strlen(str);
1190 int space_needed = 1 + sizeof(len) + len;
1191 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001192 ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001193 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001194 return false;
1195 }
1196 **pos = EVENT_TYPE_STRING;
1197 (*pos)++;
1198 memcpy(*pos, &len, sizeof(len));
1199 *pos += sizeof(len);
1200 memcpy(*pos, str, len);
1201 *pos += len;
1202 return true;
1203}
1204
1205static bool push_eventlog_int(char** pos, const char* end, jint val) {
1206 int space_needed = 1 + sizeof(val);
1207 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001208 ALOGW("not enough space for int. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001209 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001210 return false;
1211 }
1212 **pos = EVENT_TYPE_INT;
1213 (*pos)++;
1214 memcpy(*pos, &val, sizeof(val));
1215 *pos += sizeof(val);
1216 return true;
1217}
1218
1219// From frameworks/base/core/java/android/content/EventLogTags.logtags:
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001220
1221static const bool kEnableBinderSample = false;
1222
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001223#define LOGTAG_BINDER_OPERATION 52004
1224
1225static void conditionally_log_binder_call(int64_t start_millis,
1226 IBinder* target, jint code) {
1227 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1228
1229 int sample_percent;
1230 if (duration_ms >= 500) {
1231 sample_percent = 100;
1232 } else {
1233 sample_percent = 100 * duration_ms / 500;
1234 if (sample_percent == 0) {
1235 return;
1236 }
1237 if (sample_percent < (random() % 100 + 1)) {
1238 return;
1239 }
1240 }
1241
1242 char process_name[40];
1243 getprocname(getpid(), process_name, sizeof(process_name));
1244 String8 desc(target->getInterfaceDescriptor());
1245
1246 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1247 buf[0] = EVENT_TYPE_LIST;
1248 buf[1] = 5;
1249 char* pos = &buf[2];
1250 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1251 if (!push_eventlog_string(&pos, end, desc.string())) return;
1252 if (!push_eventlog_int(&pos, end, code)) return;
1253 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1254 if (!push_eventlog_string(&pos, end, process_name)) return;
1255 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1256 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1257 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1258}
1259
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001260// We only measure binder call durations to potentially log them if
Elliott Hughes06451fe2014-08-18 10:26:52 -07001261// we're on the main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001262static bool should_time_binder_calls() {
Elliott Hughes06451fe2014-08-18 10:26:52 -07001263 return (getpid() == gettid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001264}
1265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001267 jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268{
1269 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001270 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 return JNI_FALSE;
1272 }
1273
1274 Parcel* data = parcelForJavaObject(env, dataObj);
1275 if (data == NULL) {
1276 return JNI_FALSE;
1277 }
1278 Parcel* reply = parcelForJavaObject(env, replyObj);
1279 if (reply == NULL && replyObj != NULL) {
1280 return JNI_FALSE;
1281 }
1282
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001283 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 if (target == NULL) {
1285 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1286 return JNI_FALSE;
1287 }
1288
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001289 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 -08001290 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001291
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001292
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001293 bool time_binder_calls;
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001294 int64_t start_millis;
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001295 if (kEnableBinderSample) {
1296 // Only log the binder call duration for things on the Java-level main thread.
1297 // But if we don't
1298 time_binder_calls = should_time_binder_calls();
1299
1300 if (time_binder_calls) {
1301 start_millis = uptimeMillis();
1302 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001303 }
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 //printf("Transact from Java code to %p sending: ", target); data->print();
1306 status_t err = target->transact(code, *data, reply, flags);
1307 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001308
1309 if (kEnableBinderSample) {
1310 if (time_binder_calls) {
1311 conditionally_log_binder_call(start_millis, target, code);
1312 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001313 }
1314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 if (err == NO_ERROR) {
1316 return JNI_TRUE;
1317 } else if (err == UNKNOWN_TRANSACTION) {
1318 return JNI_FALSE;
1319 }
1320
Dianne Hackborne5c42622015-05-19 16:04:04 -07001321 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 return JNI_FALSE;
1323}
1324
1325static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001326 jobject recipient, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327{
1328 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001329 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 return;
1331 }
1332
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001333 BinderProxyNativeData *nd = getBPNativeData(env, obj);
1334 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335
Christopher Tate79dd31f2011-03-04 17:45:00 -08001336 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337
1338 if (!target->localBinder()) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001339 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001340 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001341 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 if (err != NO_ERROR) {
1343 // Failure adding the death recipient, so clear its reference
1344 // now.
1345 jdr->clearReference();
Jeff Brown0bde66a2011-11-07 12:50:08 -08001346 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
1348 }
1349}
1350
1351static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1352 jobject recipient, jint flags)
1353{
1354 jboolean res = JNI_FALSE;
1355 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001356 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 return res;
1358 }
1359
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001360 BinderProxyNativeData* nd = getBPNativeData(env, obj);
1361 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001363 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 return JNI_FALSE;
1365 }
1366
Christopher Tate79dd31f2011-03-04 17:45:00 -08001367 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368
1369 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001370 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001371
1372 // If we find the matching recipient, proceed to unlink using that
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001373 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001374 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001375 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001376 if (origJDR != NULL) {
1377 wp<IBinder::DeathRecipient> dr;
1378 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1379 if (err == NO_ERROR && dr != NULL) {
1380 sp<IBinder::DeathRecipient> sdr = dr.promote();
1381 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1382 if (jdr != NULL) {
1383 jdr->clearReference();
1384 }
1385 }
1386 }
1387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 if (err == NO_ERROR || err == DEAD_OBJECT) {
1389 res = JNI_TRUE;
1390 } else {
1391 jniThrowException(env, "java/util/NoSuchElementException",
1392 "Death link does not exist");
1393 }
1394 }
1395
1396 return res;
1397}
1398
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001399static void BinderProxy_destroy(void* rawNativeData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001401 BinderProxyNativeData * nativeData = (BinderProxyNativeData *) rawNativeData;
1402 LOGDEATH("Destroying BinderProxy: binder=%p drl=%p\n",
1403 nativeData->mObject.get(), nativeData->mOrgue.get());
Hans Boehm29f388f2017-10-03 18:01:20 -07001404 delete nativeData;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001405 IPCThreadState::self()->flushCommands();
Hans Boehm29f388f2017-10-03 18:01:20 -07001406 --gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407}
1408
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001409JNIEXPORT jlong JNICALL android_os_BinderProxy_getNativeFinalizer(JNIEnv*, jclass) {
1410 return (jlong) BinderProxy_destroy;
1411}
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413// ----------------------------------------------------------------------------
1414
1415static const JNINativeMethod gBinderProxyMethods[] = {
1416 /* name, signature, funcPtr */
1417 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1418 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1419 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001420 {"transactNative", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1422 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001423 {"getNativeFinalizer", "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424};
1425
1426const char* const kBinderProxyPathName = "android/os/BinderProxy";
1427
1428static int int_register_android_os_BinderProxy(JNIEnv* env)
1429{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001430 jclass clazz = FindClassOrDie(env, "java/lang/Error");
1431 gErrorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432
Andreas Gampe987f79f2014-11-18 17:29:46 -08001433 clazz = FindClassOrDie(env, kBinderProxyPathName);
1434 gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
Hans Boehm29f388f2017-10-03 18:01:20 -07001435 gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance",
1436 "(JJ)Landroid/os/BinderProxy;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001437 gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
1438 "(Landroid/os/IBinder$DeathRecipient;)V");
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001439 gBinderProxyOffsets.mNativeData = GetFieldIDOrDie(env, clazz, "mNativeData", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440
Andreas Gampe987f79f2014-11-18 17:29:46 -08001441 clazz = FindClassOrDie(env, "java/lang/Class");
1442 gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
Christopher Tate0d4a7922011-08-30 12:09:43 -07001443
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001444 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 env, kBinderProxyPathName,
1446 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1447}
1448
1449// ****************************************************************************
1450// ****************************************************************************
1451// ****************************************************************************
1452
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001453int register_android_os_Binder(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454{
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001455 if (int_register_android_os_Binder(env) < 0)
1456 return -1;
1457 if (int_register_android_os_BinderInternal(env) < 0)
1458 return -1;
1459 if (int_register_android_os_BinderProxy(env) < 0)
1460 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461
Andreas Gampe987f79f2014-11-18 17:29:46 -08001462 jclass clazz = FindClassOrDie(env, "android/util/Log");
1463 gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1464 gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
1465 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466
Andreas Gampe987f79f2014-11-18 17:29:46 -08001467 clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
1468 gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1469 gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
1470 "(Ljava/io/FileDescriptor;)V");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471
Andreas Gampe987f79f2014-11-18 17:29:46 -08001472 clazz = FindClassOrDie(env, "android/os/StrictMode");
1473 gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1474 gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
1475 "onBinderStrictModePolicyChange", "(I)V");
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001476
Andreas Gampe1cd76f52017-09-08 17:44:05 -07001477 clazz = FindClassOrDie(env, "java/lang/Thread");
1478 gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1479 gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
1480 "dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
1481 gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
1482 "()Ljava/lang/Thread;");
1483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 return 0;
1485}