blob: 0992bebb5be020bcdceaf7ffbfba6595f82ab893 [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>
Michael Wachenschwanz55182462017-08-14 23:10:13 -070033#include <binder/BpBinder.h>
Steven Morelandd587a552019-11-27 18:15:33 -080034#include <binder/IInterface.h>
35#include <binder/IPCThreadState.h>
36#include <binder/IServiceManager.h>
37#include <binder/Parcel.h>
Mathias Agopian07952722009-05-19 19:08:10 -070038#include <binder/ProcessState.h>
Steven Morelandd587a552019-11-27 18:15:33 -080039#include <binder/Stability.h>
Steven Morelandfb7952f2018-02-23 14:58:50 -080040#include <cutils/atomic.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070041#include <log/log.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070042#include <utils/KeyedVector.h>
43#include <utils/List.h>
44#include <utils/Log.h>
Jeff Brown0bde66a2011-11-07 12:50:08 -080045#include <utils/String8.h>
Mark Salyzyn52eb4e02016-09-28 16:15:30 -070046#include <utils/SystemClock.h>
47#include <utils/threads.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
Andreas Gampe625e0002017-09-08 17:44:05 -070049#include <nativehelper/JNIHelp.h>
Steven Moreland2279b252017-07-19 09:50:45 -070050#include <nativehelper/ScopedLocalRef.h>
Andreas Gampe625e0002017-09-08 17:44:05 -070051#include <nativehelper/ScopedUtfChars.h>
Christopher Tateac5e3502011-08-25 15:48:09 -070052
Andreas Gampe987f79f2014-11-18 17:29:46 -080053#include "core_jni_helpers.h"
54
Steve Block71f2cf12011-10-20 11:56:00 +010055//#undef ALOGV
56//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
Christopher Tate79dd31f2011-03-04 17:45:00 -080058#define DEBUG_DEATH 0
59#if DEBUG_DEATH
Steve Block5baa3a62011-12-20 16:23:08 +000060#define LOGDEATH ALOGD
Christopher Tate79dd31f2011-03-04 17:45:00 -080061#else
Steve Block71f2cf12011-10-20 11:56:00 +010062#define LOGDEATH ALOGV
Christopher Tate79dd31f2011-03-04 17:45:00 -080063#endif
64
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065using namespace android;
66
67// ----------------------------------------------------------------------------
68
69static struct bindernative_offsets_t
70{
71 // Class state.
72 jclass mClass;
73 jmethodID mExecTransact;
Steven Morelande52bb7d2018-10-10 11:24:58 -070074 jmethodID mGetInterfaceDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
76 // Object state.
77 jfieldID mObject;
78
79} gBinderOffsets;
80
81// ----------------------------------------------------------------------------
82
83static struct binderinternal_offsets_t
84{
85 // Class state.
86 jclass mClass;
87 jmethodID mForceGc;
Michael Wachenschwanz55182462017-08-14 23:10:13 -070088 jmethodID mProxyLimitCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
90} gBinderInternalOffsets;
91
Michael Wachenschwanz55182462017-08-14 23:10:13 -070092static struct sparseintarray_offsets_t
93{
94 jclass classObject;
95 jmethodID constructor;
96 jmethodID put;
97} gSparseIntArrayOffsets;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099// ----------------------------------------------------------------------------
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101static struct error_offsets_t
102{
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700103 jclass mError;
104 jclass mOutOfMemory;
105 jclass mStackOverflow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106} gErrorOffsets;
107
108// ----------------------------------------------------------------------------
109
110static struct binderproxy_offsets_t
111{
112 // Class state.
113 jclass mClass;
Hans Boehm29f388f2017-10-03 18:01:20 -0700114 jmethodID mGetInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 jmethodID mSendDeathNotice;
116
117 // Object state.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700118 jfieldID mNativeData; // Field holds native pointer to BinderProxyNativeData.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119} gBinderProxyOffsets;
120
Christopher Tate0d4a7922011-08-30 12:09:43 -0700121static struct class_offsets_t
122{
123 jmethodID mGetName;
124} gClassOffsets;
125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126// ----------------------------------------------------------------------------
127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128static struct log_offsets_t
129{
130 // Class state.
131 jclass mClass;
132 jmethodID mLogE;
133} gLogOffsets;
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135static struct parcel_file_descriptor_offsets_t
136{
137 jclass mClass;
138 jmethodID mConstructor;
139} gParcelFileDescriptorOffsets;
140
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700141static struct strict_mode_callback_offsets_t
142{
143 jclass mClass;
144 jmethodID mCallback;
145} gStrictModeCallbackOffsets;
146
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700147static struct thread_dispatch_offsets_t
148{
149 // Class state.
150 jclass mClass;
151 jmethodID mDispatchUncaughtException;
152 jmethodID mCurrentThread;
153} gThreadDispatchOffsets;
154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155// ****************************************************************************
156// ****************************************************************************
157// ****************************************************************************
158
Hans Boehm29f388f2017-10-03 18:01:20 -0700159static constexpr int32_t PROXY_WARN_INTERVAL = 5000;
160static constexpr uint32_t GC_INTERVAL = 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200162static std::atomic<uint32_t> gNumProxies(0);
163static std::atomic<uint32_t> gProxiesWarned(0);
Hans Boehm29f388f2017-10-03 18:01:20 -0700164
165// Number of GlobalRefs held by JavaBBinders.
166static std::atomic<uint32_t> gNumLocalRefsCreated(0);
167static std::atomic<uint32_t> gNumLocalRefsDeleted(0);
168// Number of GlobalRefs held by JavaDeathRecipients.
169static std::atomic<uint32_t> gNumDeathRefsCreated(0);
170static std::atomic<uint32_t> gNumDeathRefsDeleted(0);
171
172// We collected after creating this many refs.
173static std::atomic<uint32_t> gCollectedAtRefs(0);
174
175// Garbage collect if we've allocated at least GC_INTERVAL refs since the last time.
176// TODO: Consider removing this completely. We should no longer be generating GlobalRefs
177// that are reclaimed as a result of GC action.
Ivan Lozano2ea71352017-11-02 14:10:57 -0700178__attribute__((no_sanitize("unsigned-integer-overflow")))
Hans Boehm29f388f2017-10-03 18:01:20 -0700179static void gcIfManyNewRefs(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180{
Hans Boehm29f388f2017-10-03 18:01:20 -0700181 uint32_t totalRefs = gNumLocalRefsCreated.load(std::memory_order_relaxed)
182 + gNumDeathRefsCreated.load(std::memory_order_relaxed);
183 uint32_t collectedAtRefs = gCollectedAtRefs.load(memory_order_relaxed);
184 // A bound on the number of threads that can have incremented gNum...RefsCreated before the
185 // following check is executed. Effectively a bound on #threads. Almost any value will do.
186 static constexpr uint32_t MAX_RACING = 100000;
187
188 if (totalRefs - (collectedAtRefs + GC_INTERVAL) /* modular arithmetic! */ < MAX_RACING) {
189 // Recently passed next GC interval.
190 if (gCollectedAtRefs.compare_exchange_strong(collectedAtRefs,
191 collectedAtRefs + GC_INTERVAL, std::memory_order_relaxed)) {
192 ALOGV("Binder forcing GC at %u created refs", totalRefs);
193 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
194 gBinderInternalOffsets.mForceGc);
195 } // otherwise somebody else beat us to it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 } else {
Hans Boehm29f388f2017-10-03 18:01:20 -0700197 ALOGV("Now have %d binder ops", totalRefs - collectedAtRefs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 }
199}
200
201static JavaVM* jnienv_to_javavm(JNIEnv* env)
202{
203 JavaVM* vm;
204 return env->GetJavaVM(&vm) >= 0 ? vm : NULL;
205}
206
207static JNIEnv* javavm_to_jnienv(JavaVM* vm)
208{
209 JNIEnv* env;
210 return vm->GetEnv((void **)&env, JNI_VERSION_1_4) >= 0 ? env : NULL;
211}
212
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700213static const char* GetErrorTypeName(JNIEnv* env, jthrowable error) {
214 if (env->IsInstanceOf(error, gErrorOffsets.mOutOfMemory)) {
215 return "OutOfMemoryError";
216 }
217 if (env->IsInstanceOf(error, gErrorOffsets.mStackOverflow)) {
218 return "StackOverflowError";
219 }
220 return nullptr;
221}
222
Andreas Gampe625e0002017-09-08 17:44:05 -0700223// Report a java.lang.Error (or subclass). This will terminate the runtime by
224// calling FatalError with a message derived from the given error.
225static void report_java_lang_error_fatal_error(JNIEnv* env, jthrowable error,
226 const char* msg)
227{
228 // Report an error: reraise the exception and ask the runtime to abort.
229
230 // Try to get the exception string. Sometimes logcat isn't available,
231 // so try to add it to the abort message.
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700232 std::string exc_msg;
Andreas Gampe625e0002017-09-08 17:44:05 -0700233 {
234 ScopedLocalRef<jclass> exc_class(env, env->GetObjectClass(error));
235 jmethodID method_id = env->GetMethodID(exc_class.get(), "toString",
236 "()Ljava/lang/String;");
237 ScopedLocalRef<jstring> jstr(
238 env,
239 reinterpret_cast<jstring>(
240 env->CallObjectMethod(error, method_id)));
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700241 ScopedLocalRef<jthrowable> new_error(env, nullptr);
242 bool got_jstr = false;
243 if (env->ExceptionCheck()) {
244 new_error = ScopedLocalRef<jthrowable>(env, env->ExceptionOccurred());
245 env->ExceptionClear();
246 }
Andreas Gampe625e0002017-09-08 17:44:05 -0700247 if (jstr.get() != nullptr) {
248 ScopedUtfChars jstr_utf(env, jstr.get());
249 if (jstr_utf.c_str() != nullptr) {
250 exc_msg = jstr_utf.c_str();
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700251 got_jstr = true;
Andreas Gampe625e0002017-09-08 17:44:05 -0700252 } else {
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700253 new_error = ScopedLocalRef<jthrowable>(env, env->ExceptionOccurred());
Andreas Gampe625e0002017-09-08 17:44:05 -0700254 env->ExceptionClear();
255 }
256 }
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700257 if (!got_jstr) {
258 exc_msg = "(Unknown exception message)";
259 const char* orig_type = GetErrorTypeName(env, error);
260 if (orig_type != nullptr) {
261 exc_msg = base::StringPrintf("%s (Error was %s)", exc_msg.c_str(), orig_type);
262 }
263 const char* new_type =
264 new_error == nullptr ? nullptr : GetErrorTypeName(env, new_error.get());
265 if (new_type != nullptr) {
266 exc_msg = base::StringPrintf("%s (toString() error was %s)",
267 exc_msg.c_str(),
268 new_type);
269 }
270 }
Andreas Gampe625e0002017-09-08 17:44:05 -0700271 }
272
273 env->Throw(error);
274 ALOGE("java.lang.Error thrown during binder transaction (stack trace follows) : ");
275 env->ExceptionDescribe();
276
277 std::string error_msg = base::StringPrintf(
278 "java.lang.Error thrown during binder transaction: %s",
279 exc_msg.c_str());
280 env->FatalError(error_msg.c_str());
281}
282
283// Report a java.lang.Error (or subclass). This will terminate the runtime, either by
284// the uncaught exception handler, or explicitly by calling
285// report_java_lang_error_fatal_error.
286static void report_java_lang_error(JNIEnv* env, jthrowable error, const char* msg)
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700287{
288 // Try to run the uncaught exception machinery.
289 jobject thread = env->CallStaticObjectMethod(gThreadDispatchOffsets.mClass,
290 gThreadDispatchOffsets.mCurrentThread);
291 if (thread != nullptr) {
292 env->CallVoidMethod(thread, gThreadDispatchOffsets.mDispatchUncaughtException,
293 error);
294 // Should not return here, unless more errors occured.
295 }
296 // Some error occurred that meant that either dispatchUncaughtException could not be
297 // called or that it had an error itself (as this should be unreachable under normal
Andreas Gampe625e0002017-09-08 17:44:05 -0700298 // conditions). As the binder code cannot handle Errors, attempt to log the error and
299 // abort.
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700300 env->ExceptionClear();
Andreas Gampe625e0002017-09-08 17:44:05 -0700301 report_java_lang_error_fatal_error(env, error, msg);
Andreas Gampe1cd76f52017-09-08 17:44:05 -0700302}
303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304static void report_exception(JNIEnv* env, jthrowable excep, const char* msg)
305{
306 env->ExceptionClear();
307
Andreas Gampe625e0002017-09-08 17:44:05 -0700308 ScopedLocalRef<jstring> tagstr(env, env->NewStringUTF(LOG_TAG));
Andreas Gampe8571ec32017-09-21 10:55:59 -0700309 ScopedLocalRef<jstring> msgstr(env);
Andreas Gampe625e0002017-09-08 17:44:05 -0700310 if (tagstr != nullptr) {
311 msgstr.reset(env->NewStringUTF(msg));
Mathieu Chartiercf6775e2014-08-06 13:39:17 -0700312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
Andreas Gampe625e0002017-09-08 17:44:05 -0700314 if ((tagstr != nullptr) && (msgstr != nullptr)) {
315 env->CallStaticIntMethod(gLogOffsets.mClass, gLogOffsets.mLogE,
316 tagstr.get(), msgstr.get(), excep);
317 if (env->ExceptionCheck()) {
318 // Attempting to log the failure has failed.
319 ALOGW("Failed trying to log exception, msg='%s'\n", msg);
320 env->ExceptionClear();
321 }
322 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 env->ExceptionClear(); /* assume exception (OOM?) was thrown */
Steve Block3762c312012-01-06 19:20:56 +0000324 ALOGE("Unable to call Log.e()\n");
325 ALOGE("%s", msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 }
327
Andreas Gampe9ff9c402019-07-08 08:31:27 -0700328 if (env->IsInstanceOf(excep, gErrorOffsets.mError)) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700329 report_java_lang_error(env, excep, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331}
332
333class JavaBBinderHolder;
334
335class JavaBBinder : public BBinder
336{
337public:
Hans Boehm29f388f2017-10-03 18:01:20 -0700338 JavaBBinder(JNIEnv* env, jobject /* Java Binder */ object)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))
340 {
Steve Block71f2cf12011-10-20 11:56:00 +0100341 ALOGV("Creating JavaBBinder %p\n", this);
Hans Boehm29f388f2017-10-03 18:01:20 -0700342 gNumLocalRefsCreated.fetch_add(1, std::memory_order_relaxed);
343 gcIfManyNewRefs(env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 }
345
346 bool checkSubclass(const void* subclassID) const
347 {
348 return subclassID == &gBinderOffsets;
349 }
350
351 jobject object() const
352 {
353 return mObject;
354 }
355
356protected:
357 virtual ~JavaBBinder()
358 {
Steve Block71f2cf12011-10-20 11:56:00 +0100359 ALOGV("Destroying JavaBBinder %p\n", this);
Hans Boehm29f388f2017-10-03 18:01:20 -0700360 gNumLocalRefsDeleted.fetch_add(1, memory_order_relaxed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 JNIEnv* env = javavm_to_jnienv(mVM);
362 env->DeleteGlobalRef(mObject);
363 }
364
Steven Morelande52bb7d2018-10-10 11:24:58 -0700365 const String16& getInterfaceDescriptor() const override
366 {
367 call_once(mPopulateDescriptor, [this] {
368 JNIEnv* env = javavm_to_jnienv(mVM);
369
370 ALOGV("getInterfaceDescriptor() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
371
372 jstring descriptor = (jstring)env->CallObjectMethod(mObject, gBinderOffsets.mGetInterfaceDescriptor);
373
374 if (descriptor == nullptr) {
375 return;
376 }
377
378 static_assert(sizeof(jchar) == sizeof(char16_t), "");
379 const jchar* descriptorChars = env->GetStringChars(descriptor, nullptr);
380 const char16_t* rawDescriptor = reinterpret_cast<const char16_t*>(descriptorChars);
381 jsize rawDescriptorLen = env->GetStringLength(descriptor);
382 mDescriptor = String16(rawDescriptor, rawDescriptorLen);
383 env->ReleaseStringChars(descriptor, descriptorChars);
384 });
385
386 return mDescriptor;
387 }
388
389 status_t onTransact(
390 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0) override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 {
392 JNIEnv* env = javavm_to_jnienv(mVM);
393
Steve Block71f2cf12011-10-20 11:56:00 +0100394 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 -0800395
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700396 IPCThreadState* thread_state = IPCThreadState::self();
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700397 const int32_t strict_policy_before = thread_state->getStrictModePolicy();
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 //printf("Transact from %p to Java code sending: ", this);
400 //data.print();
401 //printf("\n");
402 jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000403 code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700404
Mathieu Chartier98671c32014-08-20 10:04:08 -0700405 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700406 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
407 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100408 "*** Uncaught remote exception! "
409 "(Exceptions are not yet supported across processes.)");
410 res = JNI_FALSE;
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100411 }
412
Dianne Hackbornce92b0d2014-09-30 11:28:18 -0700413 // Check if the strict mode state changed while processing the
414 // call. The Binder state will be restored by the underlying
415 // Binder system in IPCThreadState, however we need to take care
416 // of the parallel Java state as well.
417 if (thread_state->getStrictModePolicy() != strict_policy_before) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700418 set_dalvik_blockguard_policy(env, strict_policy_before);
419 }
420
Mathieu Chartier98671c32014-08-20 10:04:08 -0700421 if (env->ExceptionCheck()) {
Andreas Gampe625e0002017-09-08 17:44:05 -0700422 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
423 report_exception(env, excep.get(),
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100424 "*** Uncaught exception in onBinderStrictModePolicyChange");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 }
426
Dianne Hackborna53de062012-05-08 18:53:51 -0700427 // Need to always call through the native implementation of
428 // SYSPROPS_TRANSACTION.
429 if (code == SYSPROPS_TRANSACTION) {
430 BBinder::onTransact(code, data, reply, flags);
431 }
432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 //aout << "onTransact to Java code; result=" << res << endl
434 // << "Transact from " << this << " to Java code returning "
435 // << reply << ": " << *reply << endl;
436 return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
437 }
438
Steven Morelande52bb7d2018-10-10 11:24:58 -0700439 status_t dump(int fd, const Vector<String16>& args) override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 {
441 return 0;
442 }
443
444private:
445 JavaVM* const mVM;
Hans Boehm29f388f2017-10-03 18:01:20 -0700446 jobject const mObject; // GlobalRef to Java Binder
Steven Morelande52bb7d2018-10-10 11:24:58 -0700447
448 mutable std::once_flag mPopulateDescriptor;
449 mutable String16 mDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450};
451
452// ----------------------------------------------------------------------------
453
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700454class JavaBBinderHolder
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455{
456public:
Christopher Tate0b414482011-02-17 13:00:38 -0800457 sp<JavaBBinder> get(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 {
459 AutoMutex _l(mLock);
460 sp<JavaBBinder> b = mBinder.promote();
461 if (b == NULL) {
Christopher Tate0b414482011-02-17 13:00:38 -0800462 b = new JavaBBinder(env, obj);
Steven Morelandd587a552019-11-27 18:15:33 -0800463 if (mVintf) {
464 ::android::internal::Stability::markVintf(b.get());
465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 mBinder = b;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700467 ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
Christopher Tate0b414482011-02-17 13:00:38 -0800468 b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
470
471 return b;
472 }
473
474 sp<JavaBBinder> getExisting()
475 {
476 AutoMutex _l(mLock);
477 return mBinder.promote();
478 }
479
Steven Morelandd587a552019-11-27 18:15:33 -0800480 void markVintf() {
481 mVintf = true;
482 }
483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484private:
485 Mutex mLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 wp<JavaBBinder> mBinder;
Steven Morelandd587a552019-11-27 18:15:33 -0800487
488 // in the future, we might condense this into int32_t stability, or if there
489 // is too much binder state here, we can think about making JavaBBinder an
490 // sp here (avoid recreating it)
491 bool mVintf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492};
493
494// ----------------------------------------------------------------------------
495
Christopher Tate0b414482011-02-17 13:00:38 -0800496// Per-IBinder death recipient bookkeeping. This is how we reconcile local jobject
497// death recipient references passed in through JNI with the permanent corresponding
498// JavaDeathRecipient objects.
499
500class JavaDeathRecipient;
501
502class DeathRecipientList : public RefBase {
503 List< sp<JavaDeathRecipient> > mList;
504 Mutex mLock;
505
506public:
Christopher Tate79dd31f2011-03-04 17:45:00 -0800507 DeathRecipientList();
Christopher Tate0b414482011-02-17 13:00:38 -0800508 ~DeathRecipientList();
509
510 void add(const sp<JavaDeathRecipient>& recipient);
511 void remove(const sp<JavaDeathRecipient>& recipient);
512 sp<JavaDeathRecipient> find(jobject recipient);
Christopher Tate090c08f2015-05-19 18:16:58 -0700513
514 Mutex& lock(); // Use with care; specifically for mutual exclusion during binder death
Christopher Tate0b414482011-02-17 13:00:38 -0800515};
516
517// ----------------------------------------------------------------------------
518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519class JavaDeathRecipient : public IBinder::DeathRecipient
520{
521public:
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800522 JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
Christopher Tate86284c62011-08-17 15:19:29 -0700523 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
524 mObjectWeak(NULL), mList(list)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 {
Christopher Tate0b414482011-02-17 13:00:38 -0800526 // These objects manage their own lifetimes so are responsible for final bookkeeping.
527 // The list holds a strong reference to this object.
Christopher Tate79dd31f2011-03-04 17:45:00 -0800528 LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800529 list->add(this);
Christopher Tate0b414482011-02-17 13:00:38 -0800530
Hans Boehm29f388f2017-10-03 18:01:20 -0700531 gNumDeathRefsCreated.fetch_add(1, std::memory_order_relaxed);
532 gcIfManyNewRefs(env);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
534
535 void binderDied(const wp<IBinder>& who)
536 {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800537 LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
Christopher Tate86284c62011-08-17 15:19:29 -0700538 if (mObject != NULL) {
539 JNIEnv* env = javavm_to_jnienv(mVM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540
Christopher Tate86284c62011-08-17 15:19:29 -0700541 env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
542 gBinderProxyOffsets.mSendDeathNotice, mObject);
Mathieu Chartier98671c32014-08-20 10:04:08 -0700543 if (env->ExceptionCheck()) {
544 jthrowable excep = env->ExceptionOccurred();
Christopher Tate86284c62011-08-17 15:19:29 -0700545 report_exception(env, excep,
546 "*** Uncaught exception returned from death notification!");
547 }
548
Christopher Tate090c08f2015-05-19 18:16:58 -0700549 // Serialize with our containing DeathRecipientList so that we can't
550 // delete the global ref on mObject while the list is being iterated.
551 sp<DeathRecipientList> list = mList.promote();
552 if (list != NULL) {
553 AutoMutex _l(list->lock());
554
555 // Demote from strong ref to weak after binderDied() has been delivered,
556 // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
557 mObjectWeak = env->NewWeakGlobalRef(mObject);
558 env->DeleteGlobalRef(mObject);
559 mObject = NULL;
560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 }
563
564 void clearReference()
565 {
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800566 sp<DeathRecipientList> list = mList.promote();
567 if (list != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800568 LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800569 list->remove(this);
Christopher Tate79dd31f2011-03-04 17:45:00 -0800570 } else {
571 LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800572 }
Christopher Tate0b414482011-02-17 13:00:38 -0800573 }
574
575 bool matches(jobject obj) {
Christopher Tate86284c62011-08-17 15:19:29 -0700576 bool result;
Christopher Tate0b414482011-02-17 13:00:38 -0800577 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700578
579 if (mObject != NULL) {
580 result = env->IsSameObject(obj, mObject);
581 } else {
Andreas Gampe625e0002017-09-08 17:44:05 -0700582 ScopedLocalRef<jobject> me(env, env->NewLocalRef(mObjectWeak));
583 result = env->IsSameObject(obj, me.get());
Christopher Tate86284c62011-08-17 15:19:29 -0700584 }
585 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 }
587
Christopher Tateac5e3502011-08-25 15:48:09 -0700588 void warnIfStillLive() {
589 if (mObject != NULL) {
590 // Okay, something is wrong -- we have a hard reference to a live death
591 // recipient on the VM side, but the list is being torn down.
592 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate0d4a7922011-08-30 12:09:43 -0700593 ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
594 ScopedLocalRef<jstring> nameRef(env,
595 (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
596 ScopedUtfChars nameUtf(env, nameRef.get());
597 if (nameUtf.c_str() != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000598 ALOGW("BinderProxy is being destroyed but the application did not call "
Christopher Tate0d4a7922011-08-30 12:09:43 -0700599 "unlinkToDeath to unlink all of its death recipients beforehand. "
600 "Releasing leaked death recipient: %s", nameUtf.c_str());
601 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000602 ALOGW("BinderProxy being destroyed; unable to get DR object name");
Christopher Tate0d4a7922011-08-30 12:09:43 -0700603 env->ExceptionClear();
604 }
Christopher Tateac5e3502011-08-25 15:48:09 -0700605 }
606 }
607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608protected:
609 virtual ~JavaDeathRecipient()
610 {
Steve Block6215d3f2012-01-04 20:05:49 +0000611 //ALOGI("Removing death ref: recipient=%p\n", mObject);
Hans Boehm29f388f2017-10-03 18:01:20 -0700612 gNumDeathRefsDeleted.fetch_add(1, std::memory_order_relaxed);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700614 if (mObject != NULL) {
615 env->DeleteGlobalRef(mObject);
616 } else {
617 env->DeleteWeakGlobalRef(mObjectWeak);
618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
620
621private:
Christopher Tate86284c62011-08-17 15:19:29 -0700622 JavaVM* const mVM;
Hans Boehmeb6d62c2017-09-20 15:59:12 -0700623 jobject mObject; // Initial strong ref to Java-side DeathRecipient. Cleared on binderDied().
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700624 jweak mObjectWeak; // Weak ref to the same Java-side DeathRecipient after binderDied().
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800625 wp<DeathRecipientList> mList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626};
627
628// ----------------------------------------------------------------------------
629
Christopher Tate79dd31f2011-03-04 17:45:00 -0800630DeathRecipientList::DeathRecipientList() {
631 LOGDEATH("New DRL @ %p", this);
632}
633
Christopher Tate0b414482011-02-17 13:00:38 -0800634DeathRecipientList::~DeathRecipientList() {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800635 LOGDEATH("Destroy DRL @ %p", this);
Christopher Tate0b414482011-02-17 13:00:38 -0800636 AutoMutex _l(mLock);
637
638 // Should never happen -- the JavaDeathRecipient objects that have added themselves
639 // to the list are holding references on the list object. Only when they are torn
640 // down can the list header be destroyed.
641 if (mList.size() > 0) {
Christopher Tateac5e3502011-08-25 15:48:09 -0700642 List< sp<JavaDeathRecipient> >::iterator iter;
643 for (iter = mList.begin(); iter != mList.end(); iter++) {
644 (*iter)->warnIfStillLive();
645 }
Christopher Tate0b414482011-02-17 13:00:38 -0800646 }
647}
648
649void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
650 AutoMutex _l(mLock);
651
Christopher Tate79dd31f2011-03-04 17:45:00 -0800652 LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800653 mList.push_back(recipient);
654}
655
656void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
657 AutoMutex _l(mLock);
658
659 List< sp<JavaDeathRecipient> >::iterator iter;
660 for (iter = mList.begin(); iter != mList.end(); iter++) {
661 if (*iter == recipient) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800662 LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800663 mList.erase(iter);
664 return;
665 }
666 }
667}
668
669sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
670 AutoMutex _l(mLock);
671
672 List< sp<JavaDeathRecipient> >::iterator iter;
673 for (iter = mList.begin(); iter != mList.end(); iter++) {
674 if ((*iter)->matches(recipient)) {
675 return *iter;
676 }
677 }
678 return NULL;
679}
680
Christopher Tate090c08f2015-05-19 18:16:58 -0700681Mutex& DeathRecipientList::lock() {
682 return mLock;
683}
684
Christopher Tate0b414482011-02-17 13:00:38 -0800685// ----------------------------------------------------------------------------
686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687namespace android {
688
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700689// We aggregate native pointer fields for BinderProxy in a single object to allow
690// management with a single NativeAllocationRegistry, and to reduce the number of JNI
691// Java field accesses. This costs us some extra indirections here.
692struct BinderProxyNativeData {
Hans Boehm29f388f2017-10-03 18:01:20 -0700693 // Both fields are constant and not null once javaObjectForIBinder returns this as
694 // part of a BinderProxy.
695
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700696 // The native IBinder proxied by this BinderProxy.
Hans Boehm29f388f2017-10-03 18:01:20 -0700697 sp<IBinder> mObject;
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700698
699 // Death recipients for mObject. Reference counted only because DeathRecipients
700 // hold a weak reference that can be temporarily promoted.
Hans Boehm29f388f2017-10-03 18:01:20 -0700701 sp<DeathRecipientList> mOrgue; // Death recipients for mObject.
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700702};
703
704BinderProxyNativeData* getBPNativeData(JNIEnv* env, jobject obj) {
705 return (BinderProxyNativeData *) env->GetLongField(obj, gBinderProxyOffsets.mNativeData);
706}
707
Hans Boehm29f388f2017-10-03 18:01:20 -0700708// If the argument is a JavaBBinder, return the Java object that was used to create it.
709// Otherwise return a BinderProxy for the IBinder. If a previous call was passed the
710// same IBinder, and the original BinderProxy is still alive, return the same BinderProxy.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
712{
Daniel Colascione012ab8e2019-10-07 14:18:09 -0700713 // N.B. This function is called from a @FastNative JNI method, so don't take locks around
714 // calls to Java code or block the calling thread for a long time for any reason.
715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 if (val == NULL) return NULL;
717
718 if (val->checkSubclass(&gBinderOffsets)) {
Hans Boehm29f388f2017-10-03 18:01:20 -0700719 // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 jobject object = static_cast<JavaBBinder*>(val.get())->object();
Christopher Tate86284c62011-08-17 15:19:29 -0700721 LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 return object;
723 }
724
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200725 BinderProxyNativeData* nativeData = new BinderProxyNativeData();
726 nativeData->mOrgue = new DeathRecipientList;
727 nativeData->mObject = val;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728
Hans Boehm29f388f2017-10-03 18:01:20 -0700729 jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
730 gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
731 if (env->ExceptionCheck()) {
Hans Boehm03477cb2018-02-15 16:12:51 -0800732 // In the exception case, getInstance still took ownership of nativeData.
Hans Boehm29f388f2017-10-03 18:01:20 -0700733 return NULL;
734 }
735 BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
736 if (actualNativeData == nativeData) {
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200737 // Created a new Proxy
738 uint32_t numProxies = gNumProxies.fetch_add(1, std::memory_order_relaxed);
739 uint32_t numLastWarned = gProxiesWarned.load(std::memory_order_relaxed);
740 if (numProxies >= numLastWarned + PROXY_WARN_INTERVAL) {
741 // Multiple threads can get here, make sure only one of them gets to
742 // update the warn counter.
743 if (gProxiesWarned.compare_exchange_strong(numLastWarned,
744 numLastWarned + PROXY_WARN_INTERVAL, std::memory_order_relaxed)) {
745 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
746 }
Hans Boehm29f388f2017-10-03 18:01:20 -0700747 }
748 } else {
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200749 delete nativeData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 }
751
752 return object;
753}
754
755sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
756{
757 if (obj == NULL) return NULL;
758
Hans Boehm29f388f2017-10-03 18:01:20 -0700759 // Instance of Binder?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
761 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000762 env->GetLongField(obj, gBinderOffsets.mObject);
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700763 return jbh->get(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 }
765
Hans Boehm29f388f2017-10-03 18:01:20 -0700766 // Instance of BinderProxy?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700768 return getBPNativeData(env, obj)->mObject;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
770
Steve Block8564c8d2012-01-05 23:22:43 +0000771 ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 return NULL;
773}
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
776{
777 return env->NewObject(
778 gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
779}
780
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -0800781void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
782{
783 // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
784 // to sync our state back to it. See the comments in StrictMode.java.
785 env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
786 gStrictModeCallbackOffsets.mCallback,
787 strict_policy);
788}
789
790void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
Dianne Hackborne5c42622015-05-19 16:04:04 -0700791 bool canThrowRemoteException, int parcelSize)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792{
793 switch (err) {
794 case UNKNOWN_ERROR:
795 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
796 break;
797 case NO_MEMORY:
798 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
799 break;
800 case INVALID_OPERATION:
801 jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
802 break;
803 case BAD_VALUE:
804 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
805 break;
806 case BAD_INDEX:
807 jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
808 break;
809 case BAD_TYPE:
810 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
811 break;
812 case NAME_NOT_FOUND:
813 jniThrowException(env, "java/util/NoSuchElementException", NULL);
814 break;
815 case PERMISSION_DENIED:
816 jniThrowException(env, "java/lang/SecurityException", NULL);
817 break;
818 case NOT_ENOUGH_DATA:
819 jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
820 break;
821 case NO_INIT:
822 jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
823 break;
824 case ALREADY_EXISTS:
825 jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
826 break;
827 case DEAD_OBJECT:
Jeff Brown0bde66a2011-11-07 12:50:08 -0800828 // DeadObjectException is a checked exception, only throw from certain methods.
829 jniThrowException(env, canThrowRemoteException
830 ? "android/os/DeadObjectException"
831 : "java/lang/RuntimeException", NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 break;
833 case UNKNOWN_TRANSACTION:
834 jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
835 break;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700836 case FAILED_TRANSACTION: {
837 ALOGE("!!! FAILED BINDER TRANSACTION !!! (parcel size = %d)", parcelSize);
Christopher Tate02ca7a72015-06-24 18:16:42 -0700838 const char* exceptionToThrow;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700839 char msg[128];
Jeff Brown0bde66a2011-11-07 12:50:08 -0800840 // TransactionTooLargeException is a checked exception, only throw from certain methods.
841 // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
842 // but it is not the only one. The Binder driver can return BR_FAILED_REPLY
843 // for other reasons also, such as if the transaction is malformed or
844 // refers to an FD that has been closed. We should change the driver
845 // to enable us to distinguish these cases in the future.
Christopher Tate02ca7a72015-06-24 18:16:42 -0700846 if (canThrowRemoteException && parcelSize > 200*1024) {
847 // bona fide large payload
848 exceptionToThrow = "android/os/TransactionTooLargeException";
849 snprintf(msg, sizeof(msg)-1, "data parcel size %d bytes", parcelSize);
850 } else {
851 // Heuristic: a payload smaller than this threshold "shouldn't" be too
852 // big, so it's probably some other, more subtle problem. In practice
Christopher Tateffd58642015-06-29 11:00:15 -0700853 // it seems to always mean that the remote process died while the binder
Christopher Tate02ca7a72015-06-24 18:16:42 -0700854 // transaction was already in flight.
Christopher Tateffd58642015-06-29 11:00:15 -0700855 exceptionToThrow = (canThrowRemoteException)
856 ? "android/os/DeadObjectException"
857 : "java/lang/RuntimeException";
Christopher Tate02ca7a72015-06-24 18:16:42 -0700858 snprintf(msg, sizeof(msg)-1,
859 "Transaction failed on small parcel; remote process probably died");
860 }
861 jniThrowException(env, exceptionToThrow, msg);
Dianne Hackborne5c42622015-05-19 16:04:04 -0700862 } break;
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -0400863 case FDS_NOT_ALLOWED:
864 jniThrowException(env, "java/lang/RuntimeException",
865 "Not allowed to write file descriptors here");
866 break;
Christopher Wileya94fc522015-11-22 14:21:25 -0800867 case UNEXPECTED_NULL:
868 jniThrowNullPointerException(env, NULL);
869 break;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700870 case -EBADF:
871 jniThrowException(env, "java/lang/RuntimeException",
872 "Bad file descriptor");
873 break;
874 case -ENFILE:
875 jniThrowException(env, "java/lang/RuntimeException",
876 "File table overflow");
877 break;
878 case -EMFILE:
879 jniThrowException(env, "java/lang/RuntimeException",
880 "Too many open files");
881 break;
882 case -EFBIG:
883 jniThrowException(env, "java/lang/RuntimeException",
884 "File too large");
885 break;
886 case -ENOSPC:
887 jniThrowException(env, "java/lang/RuntimeException",
888 "No space left on device");
889 break;
890 case -ESPIPE:
891 jniThrowException(env, "java/lang/RuntimeException",
892 "Illegal seek");
893 break;
894 case -EROFS:
895 jniThrowException(env, "java/lang/RuntimeException",
896 "Read-only file system");
897 break;
898 case -EMLINK:
899 jniThrowException(env, "java/lang/RuntimeException",
900 "Too many links");
901 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 default:
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700903 ALOGE("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800904 String8 msg;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700905 msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800906 // RemoteException is a checked exception, only throw from certain methods.
907 jniThrowException(env, canThrowRemoteException
908 ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
909 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911}
912
913}
914
915// ----------------------------------------------------------------------------
916
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100917static jint android_os_Binder_getCallingPid()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918{
919 return IPCThreadState::self()->getCallingPid();
920}
921
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100922static jint android_os_Binder_getCallingUid()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923{
924 return IPCThreadState::self()->getCallingUid();
925}
926
Nikita Ioffea929cf02019-01-03 13:35:22 +0000927static jboolean android_os_Binder_isHandlingTransaction()
928{
929 return IPCThreadState::self()->isServingCall();
930}
931
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100932static jlong android_os_Binder_clearCallingIdentity()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933{
934 return IPCThreadState::self()->clearCallingIdentity();
935}
936
937static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
938{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700939 // XXX temporary sanity check to debug crashes.
940 int uid = (int)(token>>32);
941 if (uid > 0 && uid < 999) {
942 // In Android currently there are no uids in this range.
943 char buf[128];
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700944 sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700945 jniThrowException(env, "java/lang/IllegalStateException", buf);
946 return;
947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 IPCThreadState::self()->restoreCallingIdentity(token);
949}
950
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100951static void android_os_Binder_setThreadStrictModePolicy(jint policyMask)
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700952{
953 IPCThreadState::self()->setStrictModePolicy(policyMask);
954}
955
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100956static jint android_os_Binder_getThreadStrictModePolicy()
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700957{
958 return IPCThreadState::self()->getStrictModePolicy();
959}
960
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000961static jlong android_os_Binder_setCallingWorkSourceUid(jint workSource)
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100962{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000963 return IPCThreadState::self()->setCallingWorkSourceUid(workSource);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100964}
965
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000966static jlong android_os_Binder_getCallingWorkSourceUid()
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100967{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000968 return IPCThreadState::self()->getCallingWorkSourceUid();
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100969}
970
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000971static jlong android_os_Binder_clearCallingWorkSource()
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100972{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000973 return IPCThreadState::self()->clearCallingWorkSource();
974}
975
Olivier Gaillarda16b83c2018-12-11 23:09:05 +0000976static void android_os_Binder_restoreCallingWorkSource(jlong token)
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000977{
978 IPCThreadState::self()->restoreCallingWorkSource(token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100979}
980
Steven Morelandd587a552019-11-27 18:15:33 -0800981static void android_os_Binder_markVintfStability(JNIEnv* env, jobject clazz) {
982 JavaBBinderHolder* jbh =
983 (JavaBBinderHolder*) env->GetLongField(clazz, gBinderOffsets.mObject);
984 jbh->markVintf();
985}
986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
988{
989 IPCThreadState::self()->flushCommands();
990}
991
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700992static jlong android_os_Binder_getNativeBBinderHolder(JNIEnv* env, jobject clazz)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993{
Christopher Tate0b414482011-02-17 13:00:38 -0800994 JavaBBinderHolder* jbh = new JavaBBinderHolder();
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700995 return (jlong) jbh;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996}
997
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700998static void Binder_destroy(void* rawJbh)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001000 JavaBBinderHolder* jbh = (JavaBBinderHolder*) rawJbh;
1001 ALOGV("Java Binder: deleting holder %p", jbh);
1002 delete jbh;
1003}
1004
1005JNIEXPORT jlong JNICALL android_os_Binder_getNativeFinalizer(JNIEnv*, jclass) {
1006 return (jlong) Binder_destroy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007}
1008
Wale Ogunwaled7fdd022015-04-13 16:22:38 -07001009static void android_os_Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz)
1010{
1011 return IPCThreadState::self()->blockUntilThreadAvailable();
1012}
1013
Jon Spivack9e45fde2019-10-09 17:23:00 -07001014static jobject android_os_Binder_waitForService(
1015 JNIEnv *env,
1016 jclass /* clazzObj */,
1017 jstring serviceNameObj) {
1018
1019 const jchar* serviceName = env->GetStringCritical(serviceNameObj, nullptr);
1020 if (!serviceName) {
1021 signalExceptionForError(env, nullptr, BAD_VALUE, true /*canThrowRemoteException*/);
1022 return nullptr;
1023 }
1024 String16 nameCopy = String16(reinterpret_cast<const char16_t *>(serviceName),
1025 env->GetStringLength(serviceNameObj));
1026 env->ReleaseStringCritical(serviceNameObj, serviceName);
1027
1028 auto sm = android::defaultServiceManager();
1029 sp<IBinder> service = sm->waitForService(nameCopy);
1030
1031 if (!service) {
1032 signalExceptionForError(env, nullptr, NAME_NOT_FOUND, true /*canThrowRemoteException*/);
1033 return nullptr;
1034 }
1035
1036 return javaObjectForIBinder(env, service);
1037}
1038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039// ----------------------------------------------------------------------------
1040
1041static const JNINativeMethod gBinderMethods[] = {
1042 /* name, signature, funcPtr */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001043 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001045 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001047 // @CriticalNative
Nikita Ioffea929cf02019-01-03 13:35:22 +00001048 { "isHandlingTransaction", "()Z", (void*)android_os_Binder_isHandlingTransaction },
1049 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
1051 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001052 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001053 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001054 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001055 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +01001056 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +00001057 { "setCallingWorkSourceUid", "(I)J", (void*)android_os_Binder_setCallingWorkSourceUid },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +01001058 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +00001059 { "getCallingWorkSourceUid", "()I", (void*)android_os_Binder_getCallingWorkSourceUid },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +01001060 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +00001061 { "clearCallingWorkSource", "()J", (void*)android_os_Binder_clearCallingWorkSource },
1062 { "restoreCallingWorkSource", "(J)V", (void*)android_os_Binder_restoreCallingWorkSource },
Steven Morelandd587a552019-11-27 18:15:33 -08001063 { "markVintfStability", "()V", (void*)android_os_Binder_markVintfStability},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001065 { "getNativeBBinderHolder", "()J", (void*)android_os_Binder_getNativeBBinderHolder },
1066 { "getNativeFinalizer", "()J", (void*)android_os_Binder_getNativeFinalizer },
Jon Spivack9e45fde2019-10-09 17:23:00 -07001067 { "blockUntilThreadAvailable", "()V", (void*)android_os_Binder_blockUntilThreadAvailable },
1068 { "waitForService", "(Ljava/lang/String;)Landroid/os/IBinder;", (void*)android_os_Binder_waitForService }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069};
1070
1071const char* const kBinderPathName = "android/os/Binder";
1072
1073static int int_register_android_os_Binder(JNIEnv* env)
1074{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001075 jclass clazz = FindClassOrDie(env, kBinderPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076
Andreas Gampe987f79f2014-11-18 17:29:46 -08001077 gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1078 gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
Steven Morelande52bb7d2018-10-10 11:24:58 -07001079 gBinderOffsets.mGetInterfaceDescriptor = GetMethodIDOrDie(env, clazz, "getInterfaceDescriptor",
1080 "()Ljava/lang/String;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001081 gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001083 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 env, kBinderPathName,
1085 gBinderMethods, NELEM(gBinderMethods));
1086}
1087
1088// ****************************************************************************
1089// ****************************************************************************
1090// ****************************************************************************
1091
1092namespace android {
1093
1094jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
1095{
Hans Boehm29f388f2017-10-03 18:01:20 -07001096 return gNumLocalRefsCreated - gNumLocalRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097}
1098
1099jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
1100{
Martijn Coenend3ef4bf2018-07-05 14:58:59 +02001101 return gNumProxies.load();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102}
1103
1104jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
1105{
Hans Boehm29f388f2017-10-03 18:01:20 -07001106 return gNumDeathRefsCreated - gNumDeathRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107}
1108
1109}
1110
1111// ****************************************************************************
1112// ****************************************************************************
1113// ****************************************************************************
1114
1115static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
1116{
1117 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1118 return javaObjectForIBinder(env, b);
1119}
1120
1121static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
1122{
1123 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1124 android::IPCThreadState::self()->joinThreadPool();
1125}
1126
Dianne Hackborn887f3552009-12-07 17:59:37 -08001127static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
1128 jobject clazz, jboolean disable)
1129{
1130 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
1131}
1132
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001133static void android_os_BinderInternal_setMaxThreads(JNIEnv* env,
1134 jobject clazz, jint maxThreads)
1135{
1136 ProcessState::self()->setThreadPoolMaxThreadCount(maxThreads);
1137}
1138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
1140{
Hans Boehm29f388f2017-10-03 18:01:20 -07001141 ALOGV("Gc has executed, updating Refs count at GC");
1142 gCollectedAtRefs = gNumLocalRefsCreated + gNumDeathRefsCreated;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143}
1144
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001145static void android_os_BinderInternal_proxyLimitcallback(int uid)
1146{
1147 JNIEnv *env = AndroidRuntime::getJNIEnv();
1148 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
1149 gBinderInternalOffsets.mProxyLimitCallback,
1150 uid);
Martijn Coenendfa390e2018-06-05 11:02:23 +02001151
1152 if (env->ExceptionCheck()) {
1153 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
1154 report_exception(env, excep.get(),
1155 "*** Uncaught exception in binderProxyLimitCallbackFromNative");
1156 }
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001157}
1158
1159static void android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv* env, jobject clazz,
1160 jboolean enable)
1161{
1162 BpBinder::setCountByUidEnabled((bool) enable);
1163}
1164
1165static jobject android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv* env, jclass clazz)
1166{
1167 Vector<uint32_t> uids, counts;
1168 BpBinder::getCountByUid(uids, counts);
1169 jobject sparseIntArray = env->NewObject(gSparseIntArrayOffsets.classObject,
1170 gSparseIntArrayOffsets.constructor);
1171 for (size_t i = 0; i < uids.size(); i++) {
1172 env->CallVoidMethod(sparseIntArray, gSparseIntArrayOffsets.put,
1173 static_cast<jint>(uids[i]), static_cast<jint>(counts[i]));
1174 }
1175 return sparseIntArray;
1176}
1177
1178static jint android_os_BinderInternal_getBinderProxyCount(JNIEnv* env, jobject clazz, jint uid) {
1179 return static_cast<jint>(BpBinder::getBinderProxyCount(static_cast<uint32_t>(uid)));
1180}
1181
1182static void android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv* env, jobject clazz,
1183 jint high, jint low)
1184{
1185 BpBinder::setBinderProxyCountWatermarks(high, low);
1186}
1187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188// ----------------------------------------------------------------------------
1189
1190static const JNINativeMethod gBinderInternalMethods[] = {
1191 /* name, signature, funcPtr */
1192 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
1193 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -08001194 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001195 { "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001196 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
1197 { "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
1198 { "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
1199 { "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
1200 { "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201};
1202
1203const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
1204
1205static int int_register_android_os_BinderInternal(JNIEnv* env)
1206{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001207 jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208
Andreas Gampe987f79f2014-11-18 17:29:46 -08001209 gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1210 gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001211 gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
1212
1213 jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
1214 gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
1215 gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
1216 "<init>", "()V");
1217 gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
1218 "(II)V");
1219
1220 BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001222 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 env, kBinderInternalPathName,
1224 gBinderInternalMethods, NELEM(gBinderInternalMethods));
1225}
1226
1227// ****************************************************************************
1228// ****************************************************************************
1229// ****************************************************************************
1230
1231static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
1232{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001233 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 if (target == NULL) {
1235 return JNI_FALSE;
1236 }
1237 status_t err = target->pingBinder();
1238 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
1239}
1240
1241static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
1242{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001243 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 if (target != NULL) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001245 const String16& desc = target->getInterfaceDescriptor();
Dan Albert66987492014-11-20 11:41:21 -08001246 return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
1247 desc.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 }
1249 jniThrowException(env, "java/lang/RuntimeException",
1250 "No binder found for object");
1251 return NULL;
1252}
1253
1254static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
1255{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001256 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 if (target == NULL) {
1258 return JNI_FALSE;
1259 }
1260 bool alive = target->isBinderAlive();
1261 return alive ? JNI_TRUE : JNI_FALSE;
1262}
1263
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001264static int getprocname(pid_t pid, char *buf, size_t len) {
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001265 char filename[32];
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001266 FILE *f;
1267
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001268 snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
Nick Kralevich4b3a08c2019-01-28 10:39:10 -08001269 f = fopen(filename, "re");
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001270 if (!f) {
1271 *buf = '\0';
1272 return 1;
1273 }
1274 if (!fgets(buf, len, f)) {
1275 *buf = '\0';
1276 fclose(f);
1277 return 2;
1278 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001279 fclose(f);
1280 return 0;
1281}
1282
1283static bool push_eventlog_string(char** pos, const char* end, const char* str) {
1284 jint len = strlen(str);
1285 int space_needed = 1 + sizeof(len) + len;
1286 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001287 ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001288 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001289 return false;
1290 }
1291 **pos = EVENT_TYPE_STRING;
1292 (*pos)++;
1293 memcpy(*pos, &len, sizeof(len));
1294 *pos += sizeof(len);
1295 memcpy(*pos, str, len);
1296 *pos += len;
1297 return true;
1298}
1299
1300static bool push_eventlog_int(char** pos, const char* end, jint val) {
1301 int space_needed = 1 + sizeof(val);
1302 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001303 ALOGW("not enough space for int. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001304 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001305 return false;
1306 }
1307 **pos = EVENT_TYPE_INT;
1308 (*pos)++;
1309 memcpy(*pos, &val, sizeof(val));
1310 *pos += sizeof(val);
1311 return true;
1312}
1313
1314// From frameworks/base/core/java/android/content/EventLogTags.logtags:
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001315
1316static const bool kEnableBinderSample = false;
1317
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001318#define LOGTAG_BINDER_OPERATION 52004
1319
1320static void conditionally_log_binder_call(int64_t start_millis,
1321 IBinder* target, jint code) {
1322 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1323
1324 int sample_percent;
1325 if (duration_ms >= 500) {
1326 sample_percent = 100;
1327 } else {
1328 sample_percent = 100 * duration_ms / 500;
1329 if (sample_percent == 0) {
1330 return;
1331 }
1332 if (sample_percent < (random() % 100 + 1)) {
1333 return;
1334 }
1335 }
1336
1337 char process_name[40];
1338 getprocname(getpid(), process_name, sizeof(process_name));
1339 String8 desc(target->getInterfaceDescriptor());
1340
1341 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1342 buf[0] = EVENT_TYPE_LIST;
1343 buf[1] = 5;
1344 char* pos = &buf[2];
1345 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1346 if (!push_eventlog_string(&pos, end, desc.string())) return;
1347 if (!push_eventlog_int(&pos, end, code)) return;
1348 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1349 if (!push_eventlog_string(&pos, end, process_name)) return;
1350 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1351 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1352 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1353}
1354
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001355// We only measure binder call durations to potentially log them if
Elliott Hughes06451fe2014-08-18 10:26:52 -07001356// we're on the main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001357static bool should_time_binder_calls() {
Elliott Hughes06451fe2014-08-18 10:26:52 -07001358 return (getpid() == gettid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001359}
1360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001362 jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363{
1364 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001365 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 return JNI_FALSE;
1367 }
1368
1369 Parcel* data = parcelForJavaObject(env, dataObj);
1370 if (data == NULL) {
1371 return JNI_FALSE;
1372 }
1373 Parcel* reply = parcelForJavaObject(env, replyObj);
1374 if (reply == NULL && replyObj != NULL) {
1375 return JNI_FALSE;
1376 }
1377
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001378 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 if (target == NULL) {
1380 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1381 return JNI_FALSE;
1382 }
1383
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001384 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 -08001385 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001386
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001387
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001388 bool time_binder_calls;
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001389 int64_t start_millis;
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001390 if (kEnableBinderSample) {
1391 // Only log the binder call duration for things on the Java-level main thread.
1392 // But if we don't
1393 time_binder_calls = should_time_binder_calls();
1394
1395 if (time_binder_calls) {
1396 start_millis = uptimeMillis();
1397 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001398 }
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 //printf("Transact from Java code to %p sending: ", target); data->print();
1401 status_t err = target->transact(code, *data, reply, flags);
1402 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001403
1404 if (kEnableBinderSample) {
1405 if (time_binder_calls) {
1406 conditionally_log_binder_call(start_millis, target, code);
1407 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001408 }
1409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 if (err == NO_ERROR) {
1411 return JNI_TRUE;
1412 } else if (err == UNKNOWN_TRANSACTION) {
1413 return JNI_FALSE;
1414 }
1415
Dianne Hackborne5c42622015-05-19 16:04:04 -07001416 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 return JNI_FALSE;
1418}
1419
1420static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001421 jobject recipient, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422{
1423 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001424 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 return;
1426 }
1427
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001428 BinderProxyNativeData *nd = getBPNativeData(env, obj);
1429 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430
Christopher Tate79dd31f2011-03-04 17:45:00 -08001431 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432
1433 if (!target->localBinder()) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001434 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001435 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001436 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 if (err != NO_ERROR) {
1438 // Failure adding the death recipient, so clear its reference
1439 // now.
1440 jdr->clearReference();
Jeff Brown0bde66a2011-11-07 12:50:08 -08001441 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443 }
1444}
1445
1446static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1447 jobject recipient, jint flags)
1448{
1449 jboolean res = JNI_FALSE;
1450 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001451 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 return res;
1453 }
1454
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001455 BinderProxyNativeData* nd = getBPNativeData(env, obj);
1456 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001458 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 return JNI_FALSE;
1460 }
1461
Christopher Tate79dd31f2011-03-04 17:45:00 -08001462 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463
1464 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001465 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001466
1467 // If we find the matching recipient, proceed to unlink using that
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001468 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001469 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001470 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001471 if (origJDR != NULL) {
1472 wp<IBinder::DeathRecipient> dr;
1473 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1474 if (err == NO_ERROR && dr != NULL) {
1475 sp<IBinder::DeathRecipient> sdr = dr.promote();
1476 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1477 if (jdr != NULL) {
1478 jdr->clearReference();
1479 }
1480 }
1481 }
1482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 if (err == NO_ERROR || err == DEAD_OBJECT) {
1484 res = JNI_TRUE;
1485 } else {
1486 jniThrowException(env, "java/util/NoSuchElementException",
1487 "Death link does not exist");
1488 }
1489 }
1490
1491 return res;
1492}
1493
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001494static void BinderProxy_destroy(void* rawNativeData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001496 BinderProxyNativeData * nativeData = (BinderProxyNativeData *) rawNativeData;
1497 LOGDEATH("Destroying BinderProxy: binder=%p drl=%p\n",
1498 nativeData->mObject.get(), nativeData->mOrgue.get());
Hans Boehm29f388f2017-10-03 18:01:20 -07001499 delete nativeData;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001500 IPCThreadState::self()->flushCommands();
Hans Boehm29f388f2017-10-03 18:01:20 -07001501 --gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502}
1503
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001504JNIEXPORT jlong JNICALL android_os_BinderProxy_getNativeFinalizer(JNIEnv*, jclass) {
1505 return (jlong) BinderProxy_destroy;
1506}
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508// ----------------------------------------------------------------------------
1509
1510static const JNINativeMethod gBinderProxyMethods[] = {
1511 /* name, signature, funcPtr */
1512 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1513 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1514 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001515 {"transactNative", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1517 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001518 {"getNativeFinalizer", "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519};
1520
1521const char* const kBinderProxyPathName = "android/os/BinderProxy";
1522
1523static int int_register_android_os_BinderProxy(JNIEnv* env)
1524{
Andreas Gampe9ff9c402019-07-08 08:31:27 -07001525 gErrorOffsets.mError = MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/Error"));
1526 gErrorOffsets.mOutOfMemory =
1527 MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/OutOfMemoryError"));
1528 gErrorOffsets.mStackOverflow =
1529 MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/StackOverflowError"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530
Andreas Gampe9ff9c402019-07-08 08:31:27 -07001531 jclass clazz = FindClassOrDie(env, kBinderProxyPathName);
Andreas Gampe987f79f2014-11-18 17:29:46 -08001532 gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
Hans Boehm29f388f2017-10-03 18:01:20 -07001533 gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance",
1534 "(JJ)Landroid/os/BinderProxy;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001535 gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
1536 "(Landroid/os/IBinder$DeathRecipient;)V");
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001537 gBinderProxyOffsets.mNativeData = GetFieldIDOrDie(env, clazz, "mNativeData", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538
Andreas Gampe987f79f2014-11-18 17:29:46 -08001539 clazz = FindClassOrDie(env, "java/lang/Class");
1540 gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
Christopher Tate0d4a7922011-08-30 12:09:43 -07001541
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001542 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 env, kBinderProxyPathName,
1544 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1545}
1546
1547// ****************************************************************************
1548// ****************************************************************************
1549// ****************************************************************************
1550
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001551int register_android_os_Binder(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552{
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001553 if (int_register_android_os_Binder(env) < 0)
1554 return -1;
1555 if (int_register_android_os_BinderInternal(env) < 0)
1556 return -1;
1557 if (int_register_android_os_BinderProxy(env) < 0)
1558 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559
Andreas Gampe987f79f2014-11-18 17:29:46 -08001560 jclass clazz = FindClassOrDie(env, "android/util/Log");
1561 gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1562 gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
1563 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564
Andreas Gampe987f79f2014-11-18 17:29:46 -08001565 clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
1566 gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1567 gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
1568 "(Ljava/io/FileDescriptor;)V");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569
Andreas Gampe987f79f2014-11-18 17:29:46 -08001570 clazz = FindClassOrDie(env, "android/os/StrictMode");
1571 gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1572 gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
1573 "onBinderStrictModePolicyChange", "(I)V");
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001574
Andreas Gampe1cd76f52017-09-08 17:44:05 -07001575 clazz = FindClassOrDie(env, "java/lang/Thread");
1576 gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1577 gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
1578 "dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
1579 gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
1580 "()Ljava/lang/Thread;");
1581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 return 0;
1583}