blob: df98cdc9f1f918879e1ecb27a9483aacba2bac41 [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
Nikita Ioffea929cf02019-01-03 13:35:22 +0000878static jboolean android_os_Binder_isHandlingTransaction()
879{
880 return IPCThreadState::self()->isServingCall();
881}
882
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100883static jlong android_os_Binder_clearCallingIdentity()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884{
885 return IPCThreadState::self()->clearCallingIdentity();
886}
887
888static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
889{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700890 // XXX temporary sanity check to debug crashes.
891 int uid = (int)(token>>32);
892 if (uid > 0 && uid < 999) {
893 // In Android currently there are no uids in this range.
894 char buf[128];
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700895 sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700896 jniThrowException(env, "java/lang/IllegalStateException", buf);
897 return;
898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 IPCThreadState::self()->restoreCallingIdentity(token);
900}
901
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100902static void android_os_Binder_setThreadStrictModePolicy(jint policyMask)
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700903{
904 IPCThreadState::self()->setStrictModePolicy(policyMask);
905}
906
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100907static jint android_os_Binder_getThreadStrictModePolicy()
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700908{
909 return IPCThreadState::self()->getStrictModePolicy();
910}
911
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000912static jlong android_os_Binder_setCallingWorkSourceUid(jint workSource)
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100913{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000914 return IPCThreadState::self()->setCallingWorkSourceUid(workSource);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100915}
916
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000917static jlong android_os_Binder_getCallingWorkSourceUid()
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100918{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000919 return IPCThreadState::self()->getCallingWorkSourceUid();
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100920}
921
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000922static jlong android_os_Binder_clearCallingWorkSource()
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100923{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000924 return IPCThreadState::self()->clearCallingWorkSource();
925}
926
Olivier Gaillarda16b83c2018-12-11 23:09:05 +0000927static void android_os_Binder_restoreCallingWorkSource(jlong token)
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000928{
929 IPCThreadState::self()->restoreCallingWorkSource(token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100930}
931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
933{
934 IPCThreadState::self()->flushCommands();
935}
936
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700937static jlong android_os_Binder_getNativeBBinderHolder(JNIEnv* env, jobject clazz)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938{
Christopher Tate0b414482011-02-17 13:00:38 -0800939 JavaBBinderHolder* jbh = new JavaBBinderHolder();
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700940 return (jlong) jbh;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941}
942
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700943static void Binder_destroy(void* rawJbh)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944{
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700945 JavaBBinderHolder* jbh = (JavaBBinderHolder*) rawJbh;
946 ALOGV("Java Binder: deleting holder %p", jbh);
947 delete jbh;
948}
949
950JNIEXPORT jlong JNICALL android_os_Binder_getNativeFinalizer(JNIEnv*, jclass) {
951 return (jlong) Binder_destroy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952}
953
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700954static void android_os_Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz)
955{
956 return IPCThreadState::self()->blockUntilThreadAvailable();
957}
958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959// ----------------------------------------------------------------------------
960
961static const JNINativeMethod gBinderMethods[] = {
962 /* name, signature, funcPtr */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100963 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100965 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100967 // @CriticalNative
Nikita Ioffea929cf02019-01-03 13:35:22 +0000968 { "isHandlingTransaction", "()Z", (void*)android_os_Binder_isHandlingTransaction },
969 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
971 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100972 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700973 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100974 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700975 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100976 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000977 { "setCallingWorkSourceUid", "(I)J", (void*)android_os_Binder_setCallingWorkSourceUid },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100978 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000979 { "getCallingWorkSourceUid", "()I", (void*)android_os_Binder_getCallingWorkSourceUid },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100980 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000981 { "clearCallingWorkSource", "()J", (void*)android_os_Binder_clearCallingWorkSource },
982 { "restoreCallingWorkSource", "(J)V", (void*)android_os_Binder_restoreCallingWorkSource },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700984 { "getNativeBBinderHolder", "()J", (void*)android_os_Binder_getNativeBBinderHolder },
985 { "getNativeFinalizer", "()J", (void*)android_os_Binder_getNativeFinalizer },
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700986 { "blockUntilThreadAvailable", "()V", (void*)android_os_Binder_blockUntilThreadAvailable }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987};
988
989const char* const kBinderPathName = "android/os/Binder";
990
991static int int_register_android_os_Binder(JNIEnv* env)
992{
Andreas Gampe987f79f2014-11-18 17:29:46 -0800993 jclass clazz = FindClassOrDie(env, kBinderPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994
Andreas Gampe987f79f2014-11-18 17:29:46 -0800995 gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
996 gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
Steven Morelande52bb7d2018-10-10 11:24:58 -0700997 gBinderOffsets.mGetInterfaceDescriptor = GetMethodIDOrDie(env, clazz, "getInterfaceDescriptor",
998 "()Ljava/lang/String;");
Andreas Gampe987f79f2014-11-18 17:29:46 -0800999 gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001001 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 env, kBinderPathName,
1003 gBinderMethods, NELEM(gBinderMethods));
1004}
1005
1006// ****************************************************************************
1007// ****************************************************************************
1008// ****************************************************************************
1009
1010namespace android {
1011
1012jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
1013{
Hans Boehm29f388f2017-10-03 18:01:20 -07001014 return gNumLocalRefsCreated - gNumLocalRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015}
1016
1017jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
1018{
Martijn Coenend3ef4bf2018-07-05 14:58:59 +02001019 return gNumProxies.load();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020}
1021
1022jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
1023{
Hans Boehm29f388f2017-10-03 18:01:20 -07001024 return gNumDeathRefsCreated - gNumDeathRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025}
1026
1027}
1028
1029// ****************************************************************************
1030// ****************************************************************************
1031// ****************************************************************************
1032
1033static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
1034{
1035 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1036 return javaObjectForIBinder(env, b);
1037}
1038
1039static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
1040{
1041 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1042 android::IPCThreadState::self()->joinThreadPool();
1043}
1044
Dianne Hackborn887f3552009-12-07 17:59:37 -08001045static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
1046 jobject clazz, jboolean disable)
1047{
1048 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
1049}
1050
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001051static void android_os_BinderInternal_setMaxThreads(JNIEnv* env,
1052 jobject clazz, jint maxThreads)
1053{
1054 ProcessState::self()->setThreadPoolMaxThreadCount(maxThreads);
1055}
1056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
1058{
Hans Boehm29f388f2017-10-03 18:01:20 -07001059 ALOGV("Gc has executed, updating Refs count at GC");
1060 gCollectedAtRefs = gNumLocalRefsCreated + gNumDeathRefsCreated;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061}
1062
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001063static void android_os_BinderInternal_proxyLimitcallback(int uid)
1064{
1065 JNIEnv *env = AndroidRuntime::getJNIEnv();
1066 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
1067 gBinderInternalOffsets.mProxyLimitCallback,
1068 uid);
Martijn Coenendfa390e2018-06-05 11:02:23 +02001069
1070 if (env->ExceptionCheck()) {
1071 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
1072 report_exception(env, excep.get(),
1073 "*** Uncaught exception in binderProxyLimitCallbackFromNative");
1074 }
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001075}
1076
1077static void android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv* env, jobject clazz,
1078 jboolean enable)
1079{
1080 BpBinder::setCountByUidEnabled((bool) enable);
1081}
1082
1083static jobject android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv* env, jclass clazz)
1084{
1085 Vector<uint32_t> uids, counts;
1086 BpBinder::getCountByUid(uids, counts);
1087 jobject sparseIntArray = env->NewObject(gSparseIntArrayOffsets.classObject,
1088 gSparseIntArrayOffsets.constructor);
1089 for (size_t i = 0; i < uids.size(); i++) {
1090 env->CallVoidMethod(sparseIntArray, gSparseIntArrayOffsets.put,
1091 static_cast<jint>(uids[i]), static_cast<jint>(counts[i]));
1092 }
1093 return sparseIntArray;
1094}
1095
1096static jint android_os_BinderInternal_getBinderProxyCount(JNIEnv* env, jobject clazz, jint uid) {
1097 return static_cast<jint>(BpBinder::getBinderProxyCount(static_cast<uint32_t>(uid)));
1098}
1099
1100static void android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv* env, jobject clazz,
1101 jint high, jint low)
1102{
1103 BpBinder::setBinderProxyCountWatermarks(high, low);
1104}
1105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106// ----------------------------------------------------------------------------
1107
1108static const JNINativeMethod gBinderInternalMethods[] = {
1109 /* name, signature, funcPtr */
1110 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
1111 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -08001112 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001113 { "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001114 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
1115 { "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
1116 { "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
1117 { "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
1118 { "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119};
1120
1121const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
1122
1123static int int_register_android_os_BinderInternal(JNIEnv* env)
1124{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001125 jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126
Andreas Gampe987f79f2014-11-18 17:29:46 -08001127 gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1128 gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001129 gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
1130
1131 jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
1132 gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
1133 gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
1134 "<init>", "()V");
1135 gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
1136 "(II)V");
1137
1138 BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001140 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 env, kBinderInternalPathName,
1142 gBinderInternalMethods, NELEM(gBinderInternalMethods));
1143}
1144
1145// ****************************************************************************
1146// ****************************************************************************
1147// ****************************************************************************
1148
1149static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
1150{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001151 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 if (target == NULL) {
1153 return JNI_FALSE;
1154 }
1155 status_t err = target->pingBinder();
1156 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
1157}
1158
1159static jstring android_os_BinderProxy_getInterfaceDescriptor(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) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001163 const String16& desc = target->getInterfaceDescriptor();
Dan Albert66987492014-11-20 11:41:21 -08001164 return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
1165 desc.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167 jniThrowException(env, "java/lang/RuntimeException",
1168 "No binder found for object");
1169 return NULL;
1170}
1171
1172static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
1173{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001174 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 if (target == NULL) {
1176 return JNI_FALSE;
1177 }
1178 bool alive = target->isBinderAlive();
1179 return alive ? JNI_TRUE : JNI_FALSE;
1180}
1181
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001182static int getprocname(pid_t pid, char *buf, size_t len) {
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001183 char filename[32];
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001184 FILE *f;
1185
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001186 snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
Nick Kralevich4b3a08c2019-01-28 10:39:10 -08001187 f = fopen(filename, "re");
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001188 if (!f) {
1189 *buf = '\0';
1190 return 1;
1191 }
1192 if (!fgets(buf, len, f)) {
1193 *buf = '\0';
1194 fclose(f);
1195 return 2;
1196 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001197 fclose(f);
1198 return 0;
1199}
1200
1201static bool push_eventlog_string(char** pos, const char* end, const char* str) {
1202 jint len = strlen(str);
1203 int space_needed = 1 + sizeof(len) + len;
1204 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001205 ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001206 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001207 return false;
1208 }
1209 **pos = EVENT_TYPE_STRING;
1210 (*pos)++;
1211 memcpy(*pos, &len, sizeof(len));
1212 *pos += sizeof(len);
1213 memcpy(*pos, str, len);
1214 *pos += len;
1215 return true;
1216}
1217
1218static bool push_eventlog_int(char** pos, const char* end, jint val) {
1219 int space_needed = 1 + sizeof(val);
1220 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001221 ALOGW("not enough space for int. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001222 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001223 return false;
1224 }
1225 **pos = EVENT_TYPE_INT;
1226 (*pos)++;
1227 memcpy(*pos, &val, sizeof(val));
1228 *pos += sizeof(val);
1229 return true;
1230}
1231
1232// From frameworks/base/core/java/android/content/EventLogTags.logtags:
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001233
1234static const bool kEnableBinderSample = false;
1235
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001236#define LOGTAG_BINDER_OPERATION 52004
1237
1238static void conditionally_log_binder_call(int64_t start_millis,
1239 IBinder* target, jint code) {
1240 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1241
1242 int sample_percent;
1243 if (duration_ms >= 500) {
1244 sample_percent = 100;
1245 } else {
1246 sample_percent = 100 * duration_ms / 500;
1247 if (sample_percent == 0) {
1248 return;
1249 }
1250 if (sample_percent < (random() % 100 + 1)) {
1251 return;
1252 }
1253 }
1254
1255 char process_name[40];
1256 getprocname(getpid(), process_name, sizeof(process_name));
1257 String8 desc(target->getInterfaceDescriptor());
1258
1259 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1260 buf[0] = EVENT_TYPE_LIST;
1261 buf[1] = 5;
1262 char* pos = &buf[2];
1263 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1264 if (!push_eventlog_string(&pos, end, desc.string())) return;
1265 if (!push_eventlog_int(&pos, end, code)) return;
1266 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1267 if (!push_eventlog_string(&pos, end, process_name)) return;
1268 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1269 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1270 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1271}
1272
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001273// We only measure binder call durations to potentially log them if
Elliott Hughes06451fe2014-08-18 10:26:52 -07001274// we're on the main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001275static bool should_time_binder_calls() {
Elliott Hughes06451fe2014-08-18 10:26:52 -07001276 return (getpid() == gettid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001277}
1278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001280 jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281{
1282 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001283 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 return JNI_FALSE;
1285 }
1286
1287 Parcel* data = parcelForJavaObject(env, dataObj);
1288 if (data == NULL) {
1289 return JNI_FALSE;
1290 }
1291 Parcel* reply = parcelForJavaObject(env, replyObj);
1292 if (reply == NULL && replyObj != NULL) {
1293 return JNI_FALSE;
1294 }
1295
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001296 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 if (target == NULL) {
1298 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1299 return JNI_FALSE;
1300 }
1301
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001302 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 -08001303 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001304
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001305
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001306 bool time_binder_calls;
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001307 int64_t start_millis;
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001308 if (kEnableBinderSample) {
1309 // Only log the binder call duration for things on the Java-level main thread.
1310 // But if we don't
1311 time_binder_calls = should_time_binder_calls();
1312
1313 if (time_binder_calls) {
1314 start_millis = uptimeMillis();
1315 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001316 }
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 //printf("Transact from Java code to %p sending: ", target); data->print();
1319 status_t err = target->transact(code, *data, reply, flags);
1320 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001321
1322 if (kEnableBinderSample) {
1323 if (time_binder_calls) {
1324 conditionally_log_binder_call(start_millis, target, code);
1325 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001326 }
1327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 if (err == NO_ERROR) {
1329 return JNI_TRUE;
1330 } else if (err == UNKNOWN_TRANSACTION) {
1331 return JNI_FALSE;
1332 }
1333
Dianne Hackborne5c42622015-05-19 16:04:04 -07001334 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 return JNI_FALSE;
1336}
1337
1338static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001339 jobject recipient, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340{
1341 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001342 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 return;
1344 }
1345
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001346 BinderProxyNativeData *nd = getBPNativeData(env, obj);
1347 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348
Christopher Tate79dd31f2011-03-04 17:45:00 -08001349 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350
1351 if (!target->localBinder()) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001352 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001353 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001354 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 if (err != NO_ERROR) {
1356 // Failure adding the death recipient, so clear its reference
1357 // now.
1358 jdr->clearReference();
Jeff Brown0bde66a2011-11-07 12:50:08 -08001359 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
1361 }
1362}
1363
1364static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1365 jobject recipient, jint flags)
1366{
1367 jboolean res = JNI_FALSE;
1368 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001369 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 return res;
1371 }
1372
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001373 BinderProxyNativeData* nd = getBPNativeData(env, obj);
1374 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001376 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 return JNI_FALSE;
1378 }
1379
Christopher Tate79dd31f2011-03-04 17:45:00 -08001380 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381
1382 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001383 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001384
1385 // If we find the matching recipient, proceed to unlink using that
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001386 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001387 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001388 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001389 if (origJDR != NULL) {
1390 wp<IBinder::DeathRecipient> dr;
1391 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1392 if (err == NO_ERROR && dr != NULL) {
1393 sp<IBinder::DeathRecipient> sdr = dr.promote();
1394 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1395 if (jdr != NULL) {
1396 jdr->clearReference();
1397 }
1398 }
1399 }
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 if (err == NO_ERROR || err == DEAD_OBJECT) {
1402 res = JNI_TRUE;
1403 } else {
1404 jniThrowException(env, "java/util/NoSuchElementException",
1405 "Death link does not exist");
1406 }
1407 }
1408
1409 return res;
1410}
1411
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001412static void BinderProxy_destroy(void* rawNativeData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001414 BinderProxyNativeData * nativeData = (BinderProxyNativeData *) rawNativeData;
1415 LOGDEATH("Destroying BinderProxy: binder=%p drl=%p\n",
1416 nativeData->mObject.get(), nativeData->mOrgue.get());
Hans Boehm29f388f2017-10-03 18:01:20 -07001417 delete nativeData;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001418 IPCThreadState::self()->flushCommands();
Hans Boehm29f388f2017-10-03 18:01:20 -07001419 --gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420}
1421
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001422JNIEXPORT jlong JNICALL android_os_BinderProxy_getNativeFinalizer(JNIEnv*, jclass) {
1423 return (jlong) BinderProxy_destroy;
1424}
1425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426// ----------------------------------------------------------------------------
1427
1428static const JNINativeMethod gBinderProxyMethods[] = {
1429 /* name, signature, funcPtr */
1430 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1431 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1432 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001433 {"transactNative", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1435 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001436 {"getNativeFinalizer", "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437};
1438
1439const char* const kBinderProxyPathName = "android/os/BinderProxy";
1440
1441static int int_register_android_os_BinderProxy(JNIEnv* env)
1442{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001443 jclass clazz = FindClassOrDie(env, "java/lang/Error");
1444 gErrorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445
Andreas Gampe987f79f2014-11-18 17:29:46 -08001446 clazz = FindClassOrDie(env, kBinderProxyPathName);
1447 gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
Hans Boehm29f388f2017-10-03 18:01:20 -07001448 gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance",
1449 "(JJ)Landroid/os/BinderProxy;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001450 gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
1451 "(Landroid/os/IBinder$DeathRecipient;)V");
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001452 gBinderProxyOffsets.mNativeData = GetFieldIDOrDie(env, clazz, "mNativeData", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453
Andreas Gampe987f79f2014-11-18 17:29:46 -08001454 clazz = FindClassOrDie(env, "java/lang/Class");
1455 gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
Christopher Tate0d4a7922011-08-30 12:09:43 -07001456
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001457 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 env, kBinderProxyPathName,
1459 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1460}
1461
1462// ****************************************************************************
1463// ****************************************************************************
1464// ****************************************************************************
1465
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001466int register_android_os_Binder(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467{
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001468 if (int_register_android_os_Binder(env) < 0)
1469 return -1;
1470 if (int_register_android_os_BinderInternal(env) < 0)
1471 return -1;
1472 if (int_register_android_os_BinderProxy(env) < 0)
1473 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474
Andreas Gampe987f79f2014-11-18 17:29:46 -08001475 jclass clazz = FindClassOrDie(env, "android/util/Log");
1476 gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1477 gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
1478 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479
Andreas Gampe987f79f2014-11-18 17:29:46 -08001480 clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
1481 gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1482 gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
1483 "(Ljava/io/FileDescriptor;)V");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484
Andreas Gampe987f79f2014-11-18 17:29:46 -08001485 clazz = FindClassOrDie(env, "android/os/StrictMode");
1486 gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1487 gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
1488 "onBinderStrictModePolicyChange", "(I)V");
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001489
Andreas Gampe1cd76f52017-09-08 17:44:05 -07001490 clazz = FindClassOrDie(env, "java/lang/Thread");
1491 gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1492 gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
1493 "dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
1494 gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
1495 "()Ljava/lang/Thread;");
1496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 return 0;
1498}