blob: a236f3143f845b6d150f2c337530a8def3966ade [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{
713 if (val == NULL) return NULL;
714
715 if (val->checkSubclass(&gBinderOffsets)) {
Hans Boehm29f388f2017-10-03 18:01:20 -0700716 // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 jobject object = static_cast<JavaBBinder*>(val.get())->object();
Christopher Tate86284c62011-08-17 15:19:29 -0700718 LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 return object;
720 }
721
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200722 BinderProxyNativeData* nativeData = new BinderProxyNativeData();
723 nativeData->mOrgue = new DeathRecipientList;
724 nativeData->mObject = val;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725
Hans Boehm29f388f2017-10-03 18:01:20 -0700726 jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
727 gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
728 if (env->ExceptionCheck()) {
Hans Boehm03477cb2018-02-15 16:12:51 -0800729 // In the exception case, getInstance still took ownership of nativeData.
Hans Boehm29f388f2017-10-03 18:01:20 -0700730 return NULL;
731 }
732 BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
733 if (actualNativeData == nativeData) {
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200734 // Created a new Proxy
735 uint32_t numProxies = gNumProxies.fetch_add(1, std::memory_order_relaxed);
736 uint32_t numLastWarned = gProxiesWarned.load(std::memory_order_relaxed);
737 if (numProxies >= numLastWarned + PROXY_WARN_INTERVAL) {
738 // Multiple threads can get here, make sure only one of them gets to
739 // update the warn counter.
740 if (gProxiesWarned.compare_exchange_strong(numLastWarned,
741 numLastWarned + PROXY_WARN_INTERVAL, std::memory_order_relaxed)) {
742 ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
743 }
Hans Boehm29f388f2017-10-03 18:01:20 -0700744 }
745 } else {
Martijn Coenend3ef4bf2018-07-05 14:58:59 +0200746 delete nativeData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 }
748
749 return object;
750}
751
752sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
753{
754 if (obj == NULL) return NULL;
755
Hans Boehm29f388f2017-10-03 18:01:20 -0700756 // Instance of Binder?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
758 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000759 env->GetLongField(obj, gBinderOffsets.mObject);
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700760 return jbh->get(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762
Hans Boehm29f388f2017-10-03 18:01:20 -0700763 // Instance of BinderProxy?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700765 return getBPNativeData(env, obj)->mObject;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 }
767
Steve Block8564c8d2012-01-05 23:22:43 +0000768 ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 return NULL;
770}
771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
773{
774 return env->NewObject(
775 gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
776}
777
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -0800778void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
779{
780 // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
781 // to sync our state back to it. See the comments in StrictMode.java.
782 env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
783 gStrictModeCallbackOffsets.mCallback,
784 strict_policy);
785}
786
787void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
Dianne Hackborne5c42622015-05-19 16:04:04 -0700788 bool canThrowRemoteException, int parcelSize)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789{
790 switch (err) {
791 case UNKNOWN_ERROR:
792 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
793 break;
794 case NO_MEMORY:
795 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
796 break;
797 case INVALID_OPERATION:
798 jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
799 break;
800 case BAD_VALUE:
801 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
802 break;
803 case BAD_INDEX:
804 jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
805 break;
806 case BAD_TYPE:
807 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
808 break;
809 case NAME_NOT_FOUND:
810 jniThrowException(env, "java/util/NoSuchElementException", NULL);
811 break;
812 case PERMISSION_DENIED:
813 jniThrowException(env, "java/lang/SecurityException", NULL);
814 break;
815 case NOT_ENOUGH_DATA:
816 jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
817 break;
818 case NO_INIT:
819 jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
820 break;
821 case ALREADY_EXISTS:
822 jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
823 break;
824 case DEAD_OBJECT:
Jeff Brown0bde66a2011-11-07 12:50:08 -0800825 // DeadObjectException is a checked exception, only throw from certain methods.
826 jniThrowException(env, canThrowRemoteException
827 ? "android/os/DeadObjectException"
828 : "java/lang/RuntimeException", NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 break;
830 case UNKNOWN_TRANSACTION:
831 jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
832 break;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700833 case FAILED_TRANSACTION: {
834 ALOGE("!!! FAILED BINDER TRANSACTION !!! (parcel size = %d)", parcelSize);
Christopher Tate02ca7a72015-06-24 18:16:42 -0700835 const char* exceptionToThrow;
Dianne Hackborne5c42622015-05-19 16:04:04 -0700836 char msg[128];
Jeff Brown0bde66a2011-11-07 12:50:08 -0800837 // TransactionTooLargeException is a checked exception, only throw from certain methods.
838 // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
839 // but it is not the only one. The Binder driver can return BR_FAILED_REPLY
840 // for other reasons also, such as if the transaction is malformed or
841 // refers to an FD that has been closed. We should change the driver
842 // to enable us to distinguish these cases in the future.
Christopher Tate02ca7a72015-06-24 18:16:42 -0700843 if (canThrowRemoteException && parcelSize > 200*1024) {
844 // bona fide large payload
845 exceptionToThrow = "android/os/TransactionTooLargeException";
846 snprintf(msg, sizeof(msg)-1, "data parcel size %d bytes", parcelSize);
847 } else {
848 // Heuristic: a payload smaller than this threshold "shouldn't" be too
849 // big, so it's probably some other, more subtle problem. In practice
Christopher Tateffd58642015-06-29 11:00:15 -0700850 // it seems to always mean that the remote process died while the binder
Christopher Tate02ca7a72015-06-24 18:16:42 -0700851 // transaction was already in flight.
Christopher Tateffd58642015-06-29 11:00:15 -0700852 exceptionToThrow = (canThrowRemoteException)
853 ? "android/os/DeadObjectException"
854 : "java/lang/RuntimeException";
Christopher Tate02ca7a72015-06-24 18:16:42 -0700855 snprintf(msg, sizeof(msg)-1,
856 "Transaction failed on small parcel; remote process probably died");
857 }
858 jniThrowException(env, exceptionToThrow, msg);
Dianne Hackborne5c42622015-05-19 16:04:04 -0700859 } break;
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -0400860 case FDS_NOT_ALLOWED:
861 jniThrowException(env, "java/lang/RuntimeException",
862 "Not allowed to write file descriptors here");
863 break;
Christopher Wileya94fc522015-11-22 14:21:25 -0800864 case UNEXPECTED_NULL:
865 jniThrowNullPointerException(env, NULL);
866 break;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700867 case -EBADF:
868 jniThrowException(env, "java/lang/RuntimeException",
869 "Bad file descriptor");
870 break;
871 case -ENFILE:
872 jniThrowException(env, "java/lang/RuntimeException",
873 "File table overflow");
874 break;
875 case -EMFILE:
876 jniThrowException(env, "java/lang/RuntimeException",
877 "Too many open files");
878 break;
879 case -EFBIG:
880 jniThrowException(env, "java/lang/RuntimeException",
881 "File too large");
882 break;
883 case -ENOSPC:
884 jniThrowException(env, "java/lang/RuntimeException",
885 "No space left on device");
886 break;
887 case -ESPIPE:
888 jniThrowException(env, "java/lang/RuntimeException",
889 "Illegal seek");
890 break;
891 case -EROFS:
892 jniThrowException(env, "java/lang/RuntimeException",
893 "Read-only file system");
894 break;
895 case -EMLINK:
896 jniThrowException(env, "java/lang/RuntimeException",
897 "Too many links");
898 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 default:
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700900 ALOGE("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800901 String8 msg;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700902 msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800903 // RemoteException is a checked exception, only throw from certain methods.
904 jniThrowException(env, canThrowRemoteException
905 ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
906 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 }
908}
909
910}
911
912// ----------------------------------------------------------------------------
913
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100914static jint android_os_Binder_getCallingPid()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915{
916 return IPCThreadState::self()->getCallingPid();
917}
918
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100919static jint android_os_Binder_getCallingUid()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920{
921 return IPCThreadState::self()->getCallingUid();
922}
923
Nikita Ioffea929cf02019-01-03 13:35:22 +0000924static jboolean android_os_Binder_isHandlingTransaction()
925{
926 return IPCThreadState::self()->isServingCall();
927}
928
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100929static jlong android_os_Binder_clearCallingIdentity()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930{
931 return IPCThreadState::self()->clearCallingIdentity();
932}
933
934static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
935{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700936 // XXX temporary sanity check to debug crashes.
937 int uid = (int)(token>>32);
938 if (uid > 0 && uid < 999) {
939 // In Android currently there are no uids in this range.
940 char buf[128];
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700941 sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700942 jniThrowException(env, "java/lang/IllegalStateException", buf);
943 return;
944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 IPCThreadState::self()->restoreCallingIdentity(token);
946}
947
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100948static void android_os_Binder_setThreadStrictModePolicy(jint policyMask)
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700949{
950 IPCThreadState::self()->setStrictModePolicy(policyMask);
951}
952
Olivier Gaillardd8c3df52018-10-23 09:58:42 +0100953static jint android_os_Binder_getThreadStrictModePolicy()
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700954{
955 return IPCThreadState::self()->getStrictModePolicy();
956}
957
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000958static jlong android_os_Binder_setCallingWorkSourceUid(jint workSource)
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100959{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000960 return IPCThreadState::self()->setCallingWorkSourceUid(workSource);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100961}
962
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000963static jlong android_os_Binder_getCallingWorkSourceUid()
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100964{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000965 return IPCThreadState::self()->getCallingWorkSourceUid();
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100966}
967
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000968static jlong android_os_Binder_clearCallingWorkSource()
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100969{
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000970 return IPCThreadState::self()->clearCallingWorkSource();
971}
972
Olivier Gaillarda16b83c2018-12-11 23:09:05 +0000973static void android_os_Binder_restoreCallingWorkSource(jlong token)
Olivier Gaillardd542b1c2018-11-14 15:24:35 +0000974{
975 IPCThreadState::self()->restoreCallingWorkSource(token);
Olivier Gaillarde4ff3972018-08-16 14:01:58 +0100976}
977
Steven Morelandd587a552019-11-27 18:15:33 -0800978static void android_os_Binder_markVintfStability(JNIEnv* env, jobject clazz) {
979 JavaBBinderHolder* jbh =
980 (JavaBBinderHolder*) env->GetLongField(clazz, gBinderOffsets.mObject);
981 jbh->markVintf();
982}
983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
985{
986 IPCThreadState::self()->flushCommands();
987}
988
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700989static jlong android_os_Binder_getNativeBBinderHolder(JNIEnv* env, jobject clazz)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990{
Christopher Tate0b414482011-02-17 13:00:38 -0800991 JavaBBinderHolder* jbh = new JavaBBinderHolder();
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700992 return (jlong) jbh;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993}
994
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700995static void Binder_destroy(void* rawJbh)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996{
Hans Boehm5e5b13f2017-09-28 18:16:50 -0700997 JavaBBinderHolder* jbh = (JavaBBinderHolder*) rawJbh;
998 ALOGV("Java Binder: deleting holder %p", jbh);
999 delete jbh;
1000}
1001
1002JNIEXPORT jlong JNICALL android_os_Binder_getNativeFinalizer(JNIEnv*, jclass) {
1003 return (jlong) Binder_destroy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004}
1005
Wale Ogunwaled7fdd022015-04-13 16:22:38 -07001006static void android_os_Binder_blockUntilThreadAvailable(JNIEnv* env, jobject clazz)
1007{
1008 return IPCThreadState::self()->blockUntilThreadAvailable();
1009}
1010
Jon Spivack9e45fde2019-10-09 17:23:00 -07001011static jobject android_os_Binder_waitForService(
1012 JNIEnv *env,
1013 jclass /* clazzObj */,
1014 jstring serviceNameObj) {
1015
1016 const jchar* serviceName = env->GetStringCritical(serviceNameObj, nullptr);
1017 if (!serviceName) {
1018 signalExceptionForError(env, nullptr, BAD_VALUE, true /*canThrowRemoteException*/);
1019 return nullptr;
1020 }
1021 String16 nameCopy = String16(reinterpret_cast<const char16_t *>(serviceName),
1022 env->GetStringLength(serviceNameObj));
1023 env->ReleaseStringCritical(serviceNameObj, serviceName);
1024
1025 auto sm = android::defaultServiceManager();
1026 sp<IBinder> service = sm->waitForService(nameCopy);
1027
1028 if (!service) {
1029 signalExceptionForError(env, nullptr, NAME_NOT_FOUND, true /*canThrowRemoteException*/);
1030 return nullptr;
1031 }
1032
1033 return javaObjectForIBinder(env, service);
1034}
1035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036// ----------------------------------------------------------------------------
1037
1038static const JNINativeMethod gBinderMethods[] = {
1039 /* name, signature, funcPtr */
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001040 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001042 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001044 // @CriticalNative
Nikita Ioffea929cf02019-01-03 13:35:22 +00001045 { "isHandlingTransaction", "()Z", (void*)android_os_Binder_isHandlingTransaction },
1046 // @CriticalNative
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
1048 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001049 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001050 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
Olivier Gaillardd8c3df52018-10-23 09:58:42 +01001051 // @CriticalNative
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001052 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +01001053 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +00001054 { "setCallingWorkSourceUid", "(I)J", (void*)android_os_Binder_setCallingWorkSourceUid },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +01001055 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +00001056 { "getCallingWorkSourceUid", "()I", (void*)android_os_Binder_getCallingWorkSourceUid },
Olivier Gaillarde4ff3972018-08-16 14:01:58 +01001057 // @CriticalNative
Olivier Gaillardd542b1c2018-11-14 15:24:35 +00001058 { "clearCallingWorkSource", "()J", (void*)android_os_Binder_clearCallingWorkSource },
1059 { "restoreCallingWorkSource", "(J)V", (void*)android_os_Binder_restoreCallingWorkSource },
Steven Morelandd587a552019-11-27 18:15:33 -08001060 { "markVintfStability", "()V", (void*)android_os_Binder_markVintfStability},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001062 { "getNativeBBinderHolder", "()J", (void*)android_os_Binder_getNativeBBinderHolder },
1063 { "getNativeFinalizer", "()J", (void*)android_os_Binder_getNativeFinalizer },
Jon Spivack9e45fde2019-10-09 17:23:00 -07001064 { "blockUntilThreadAvailable", "()V", (void*)android_os_Binder_blockUntilThreadAvailable },
1065 { "waitForService", "(Ljava/lang/String;)Landroid/os/IBinder;", (void*)android_os_Binder_waitForService }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066};
1067
1068const char* const kBinderPathName = "android/os/Binder";
1069
1070static int int_register_android_os_Binder(JNIEnv* env)
1071{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001072 jclass clazz = FindClassOrDie(env, kBinderPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073
Andreas Gampe987f79f2014-11-18 17:29:46 -08001074 gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1075 gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact", "(IJJI)Z");
Steven Morelande52bb7d2018-10-10 11:24:58 -07001076 gBinderOffsets.mGetInterfaceDescriptor = GetMethodIDOrDie(env, clazz, "getInterfaceDescriptor",
1077 "()Ljava/lang/String;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001078 gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001080 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 env, kBinderPathName,
1082 gBinderMethods, NELEM(gBinderMethods));
1083}
1084
1085// ****************************************************************************
1086// ****************************************************************************
1087// ****************************************************************************
1088
1089namespace android {
1090
1091jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
1092{
Hans Boehm29f388f2017-10-03 18:01:20 -07001093 return gNumLocalRefsCreated - gNumLocalRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094}
1095
1096jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
1097{
Martijn Coenend3ef4bf2018-07-05 14:58:59 +02001098 return gNumProxies.load();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099}
1100
1101jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
1102{
Hans Boehm29f388f2017-10-03 18:01:20 -07001103 return gNumDeathRefsCreated - gNumDeathRefsDeleted;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104}
1105
1106}
1107
1108// ****************************************************************************
1109// ****************************************************************************
1110// ****************************************************************************
1111
1112static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
1113{
1114 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1115 return javaObjectForIBinder(env, b);
1116}
1117
1118static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
1119{
1120 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
1121 android::IPCThreadState::self()->joinThreadPool();
1122}
1123
Dianne Hackborn887f3552009-12-07 17:59:37 -08001124static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
1125 jobject clazz, jboolean disable)
1126{
1127 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
1128}
1129
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001130static void android_os_BinderInternal_setMaxThreads(JNIEnv* env,
1131 jobject clazz, jint maxThreads)
1132{
1133 ProcessState::self()->setThreadPoolMaxThreadCount(maxThreads);
1134}
1135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
1137{
Hans Boehm29f388f2017-10-03 18:01:20 -07001138 ALOGV("Gc has executed, updating Refs count at GC");
1139 gCollectedAtRefs = gNumLocalRefsCreated + gNumDeathRefsCreated;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140}
1141
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001142static void android_os_BinderInternal_proxyLimitcallback(int uid)
1143{
1144 JNIEnv *env = AndroidRuntime::getJNIEnv();
1145 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
1146 gBinderInternalOffsets.mProxyLimitCallback,
1147 uid);
Martijn Coenendfa390e2018-06-05 11:02:23 +02001148
1149 if (env->ExceptionCheck()) {
1150 ScopedLocalRef<jthrowable> excep(env, env->ExceptionOccurred());
1151 report_exception(env, excep.get(),
1152 "*** Uncaught exception in binderProxyLimitCallbackFromNative");
1153 }
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001154}
1155
1156static void android_os_BinderInternal_setBinderProxyCountEnabled(JNIEnv* env, jobject clazz,
1157 jboolean enable)
1158{
1159 BpBinder::setCountByUidEnabled((bool) enable);
1160}
1161
1162static jobject android_os_BinderInternal_getBinderProxyPerUidCounts(JNIEnv* env, jclass clazz)
1163{
1164 Vector<uint32_t> uids, counts;
1165 BpBinder::getCountByUid(uids, counts);
1166 jobject sparseIntArray = env->NewObject(gSparseIntArrayOffsets.classObject,
1167 gSparseIntArrayOffsets.constructor);
1168 for (size_t i = 0; i < uids.size(); i++) {
1169 env->CallVoidMethod(sparseIntArray, gSparseIntArrayOffsets.put,
1170 static_cast<jint>(uids[i]), static_cast<jint>(counts[i]));
1171 }
1172 return sparseIntArray;
1173}
1174
1175static jint android_os_BinderInternal_getBinderProxyCount(JNIEnv* env, jobject clazz, jint uid) {
1176 return static_cast<jint>(BpBinder::getBinderProxyCount(static_cast<uint32_t>(uid)));
1177}
1178
1179static void android_os_BinderInternal_setBinderProxyCountWatermarks(JNIEnv* env, jobject clazz,
1180 jint high, jint low)
1181{
1182 BpBinder::setBinderProxyCountWatermarks(high, low);
1183}
1184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185// ----------------------------------------------------------------------------
1186
1187static const JNINativeMethod gBinderInternalMethods[] = {
1188 /* name, signature, funcPtr */
1189 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
1190 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -08001191 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
Tim Murrayeef4a3d2016-04-19 14:14:20 -07001192 { "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001193 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
1194 { "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
1195 { "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
1196 { "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
1197 { "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198};
1199
1200const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
1201
1202static int int_register_android_os_BinderInternal(JNIEnv* env)
1203{
Andreas Gampe987f79f2014-11-18 17:29:46 -08001204 jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205
Andreas Gampe987f79f2014-11-18 17:29:46 -08001206 gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1207 gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
Michael Wachenschwanz55182462017-08-14 23:10:13 -07001208 gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
1209
1210 jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
1211 gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
1212 gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
1213 "<init>", "()V");
1214 gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
1215 "(II)V");
1216
1217 BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001219 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 env, kBinderInternalPathName,
1221 gBinderInternalMethods, NELEM(gBinderInternalMethods));
1222}
1223
1224// ****************************************************************************
1225// ****************************************************************************
1226// ****************************************************************************
1227
1228static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
1229{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001230 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 if (target == NULL) {
1232 return JNI_FALSE;
1233 }
1234 status_t err = target->pingBinder();
1235 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
1236}
1237
1238static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
1239{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001240 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 if (target != NULL) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001242 const String16& desc = target->getInterfaceDescriptor();
Dan Albert66987492014-11-20 11:41:21 -08001243 return env->NewString(reinterpret_cast<const jchar*>(desc.string()),
1244 desc.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 }
1246 jniThrowException(env, "java/lang/RuntimeException",
1247 "No binder found for object");
1248 return NULL;
1249}
1250
1251static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
1252{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001253 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 if (target == NULL) {
1255 return JNI_FALSE;
1256 }
1257 bool alive = target->isBinderAlive();
1258 return alive ? JNI_TRUE : JNI_FALSE;
1259}
1260
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001261static int getprocname(pid_t pid, char *buf, size_t len) {
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001262 char filename[32];
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001263 FILE *f;
1264
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001265 snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
Nick Kralevich4b3a08c2019-01-28 10:39:10 -08001266 f = fopen(filename, "re");
Sungmin Choiec3d44c2012-12-21 14:24:33 +09001267 if (!f) {
1268 *buf = '\0';
1269 return 1;
1270 }
1271 if (!fgets(buf, len, f)) {
1272 *buf = '\0';
1273 fclose(f);
1274 return 2;
1275 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001276 fclose(f);
1277 return 0;
1278}
1279
1280static bool push_eventlog_string(char** pos, const char* end, const char* str) {
1281 jint len = strlen(str);
1282 int space_needed = 1 + sizeof(len) + len;
1283 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001284 ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001285 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001286 return false;
1287 }
1288 **pos = EVENT_TYPE_STRING;
1289 (*pos)++;
1290 memcpy(*pos, &len, sizeof(len));
1291 *pos += sizeof(len);
1292 memcpy(*pos, str, len);
1293 *pos += len;
1294 return true;
1295}
1296
1297static bool push_eventlog_int(char** pos, const char* end, jint val) {
1298 int space_needed = 1 + sizeof(val);
1299 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -07001300 ALOGW("not enough space for int. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001301 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001302 return false;
1303 }
1304 **pos = EVENT_TYPE_INT;
1305 (*pos)++;
1306 memcpy(*pos, &val, sizeof(val));
1307 *pos += sizeof(val);
1308 return true;
1309}
1310
1311// From frameworks/base/core/java/android/content/EventLogTags.logtags:
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001312
1313static const bool kEnableBinderSample = false;
1314
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001315#define LOGTAG_BINDER_OPERATION 52004
1316
1317static void conditionally_log_binder_call(int64_t start_millis,
1318 IBinder* target, jint code) {
1319 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1320
1321 int sample_percent;
1322 if (duration_ms >= 500) {
1323 sample_percent = 100;
1324 } else {
1325 sample_percent = 100 * duration_ms / 500;
1326 if (sample_percent == 0) {
1327 return;
1328 }
1329 if (sample_percent < (random() % 100 + 1)) {
1330 return;
1331 }
1332 }
1333
1334 char process_name[40];
1335 getprocname(getpid(), process_name, sizeof(process_name));
1336 String8 desc(target->getInterfaceDescriptor());
1337
1338 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1339 buf[0] = EVENT_TYPE_LIST;
1340 buf[1] = 5;
1341 char* pos = &buf[2];
1342 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1343 if (!push_eventlog_string(&pos, end, desc.string())) return;
1344 if (!push_eventlog_int(&pos, end, code)) return;
1345 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1346 if (!push_eventlog_string(&pos, end, process_name)) return;
1347 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1348 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1349 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1350}
1351
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001352// We only measure binder call durations to potentially log them if
Elliott Hughes06451fe2014-08-18 10:26:52 -07001353// we're on the main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001354static bool should_time_binder_calls() {
Elliott Hughes06451fe2014-08-18 10:26:52 -07001355 return (getpid() == gettid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001356}
1357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001359 jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360{
1361 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001362 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 return JNI_FALSE;
1364 }
1365
1366 Parcel* data = parcelForJavaObject(env, dataObj);
1367 if (data == NULL) {
1368 return JNI_FALSE;
1369 }
1370 Parcel* reply = parcelForJavaObject(env, replyObj);
1371 if (reply == NULL && replyObj != NULL) {
1372 return JNI_FALSE;
1373 }
1374
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001375 IBinder* target = getBPNativeData(env, obj)->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 if (target == NULL) {
1377 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1378 return JNI_FALSE;
1379 }
1380
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001381 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 -08001382 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001383
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001384
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001385 bool time_binder_calls;
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001386 int64_t start_millis;
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001387 if (kEnableBinderSample) {
1388 // Only log the binder call duration for things on the Java-level main thread.
1389 // But if we don't
1390 time_binder_calls = should_time_binder_calls();
1391
1392 if (time_binder_calls) {
1393 start_millis = uptimeMillis();
1394 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001395 }
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 //printf("Transact from Java code to %p sending: ", target); data->print();
1398 status_t err = target->transact(code, *data, reply, flags);
1399 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Andreas Gampe0f0b4912014-11-12 08:03:48 -08001400
1401 if (kEnableBinderSample) {
1402 if (time_binder_calls) {
1403 conditionally_log_binder_call(start_millis, target, code);
1404 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001405 }
1406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 if (err == NO_ERROR) {
1408 return JNI_TRUE;
1409 } else if (err == UNKNOWN_TRANSACTION) {
1410 return JNI_FALSE;
1411 }
1412
Dianne Hackborne5c42622015-05-19 16:04:04 -07001413 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 return JNI_FALSE;
1415}
1416
1417static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001418 jobject recipient, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419{
1420 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001421 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 return;
1423 }
1424
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001425 BinderProxyNativeData *nd = getBPNativeData(env, obj);
1426 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427
Christopher Tate79dd31f2011-03-04 17:45:00 -08001428 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429
1430 if (!target->localBinder()) {
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001431 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001432 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001433 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 if (err != NO_ERROR) {
1435 // Failure adding the death recipient, so clear its reference
1436 // now.
1437 jdr->clearReference();
Jeff Brown0bde66a2011-11-07 12:50:08 -08001438 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 }
1441}
1442
1443static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1444 jobject recipient, jint flags)
1445{
1446 jboolean res = JNI_FALSE;
1447 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001448 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 return res;
1450 }
1451
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001452 BinderProxyNativeData* nd = getBPNativeData(env, obj);
1453 IBinder* target = nd->mObject.get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001455 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 return JNI_FALSE;
1457 }
1458
Christopher Tate79dd31f2011-03-04 17:45:00 -08001459 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460
1461 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001462 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001463
1464 // If we find the matching recipient, proceed to unlink using that
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001465 DeathRecipientList* list = nd->mOrgue.get();
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001466 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001467 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001468 if (origJDR != NULL) {
1469 wp<IBinder::DeathRecipient> dr;
1470 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1471 if (err == NO_ERROR && dr != NULL) {
1472 sp<IBinder::DeathRecipient> sdr = dr.promote();
1473 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1474 if (jdr != NULL) {
1475 jdr->clearReference();
1476 }
1477 }
1478 }
1479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 if (err == NO_ERROR || err == DEAD_OBJECT) {
1481 res = JNI_TRUE;
1482 } else {
1483 jniThrowException(env, "java/util/NoSuchElementException",
1484 "Death link does not exist");
1485 }
1486 }
1487
1488 return res;
1489}
1490
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001491static void BinderProxy_destroy(void* rawNativeData)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492{
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001493 BinderProxyNativeData * nativeData = (BinderProxyNativeData *) rawNativeData;
1494 LOGDEATH("Destroying BinderProxy: binder=%p drl=%p\n",
1495 nativeData->mObject.get(), nativeData->mOrgue.get());
Hans Boehm29f388f2017-10-03 18:01:20 -07001496 delete nativeData;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001497 IPCThreadState::self()->flushCommands();
Hans Boehm29f388f2017-10-03 18:01:20 -07001498 --gNumProxies;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499}
1500
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001501JNIEXPORT jlong JNICALL android_os_BinderProxy_getNativeFinalizer(JNIEnv*, jclass) {
1502 return (jlong) BinderProxy_destroy;
1503}
1504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505// ----------------------------------------------------------------------------
1506
1507static const JNINativeMethod gBinderProxyMethods[] = {
1508 /* name, signature, funcPtr */
1509 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1510 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1511 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
Dianne Hackborn017c6a22014-09-25 17:41:34 -07001512 {"transactNative", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1514 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001515 {"getNativeFinalizer", "()J", (void*)android_os_BinderProxy_getNativeFinalizer},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516};
1517
1518const char* const kBinderProxyPathName = "android/os/BinderProxy";
1519
1520static int int_register_android_os_BinderProxy(JNIEnv* env)
1521{
Andreas Gampe9ff9c402019-07-08 08:31:27 -07001522 gErrorOffsets.mError = MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/Error"));
1523 gErrorOffsets.mOutOfMemory =
1524 MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/OutOfMemoryError"));
1525 gErrorOffsets.mStackOverflow =
1526 MakeGlobalRefOrDie(env, FindClassOrDie(env, "java/lang/StackOverflowError"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527
Andreas Gampe9ff9c402019-07-08 08:31:27 -07001528 jclass clazz = FindClassOrDie(env, kBinderProxyPathName);
Andreas Gampe987f79f2014-11-18 17:29:46 -08001529 gBinderProxyOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
Hans Boehm29f388f2017-10-03 18:01:20 -07001530 gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance",
1531 "(JJ)Landroid/os/BinderProxy;");
Andreas Gampe987f79f2014-11-18 17:29:46 -08001532 gBinderProxyOffsets.mSendDeathNotice = GetStaticMethodIDOrDie(env, clazz, "sendDeathNotice",
1533 "(Landroid/os/IBinder$DeathRecipient;)V");
Hans Boehm5e5b13f2017-09-28 18:16:50 -07001534 gBinderProxyOffsets.mNativeData = GetFieldIDOrDie(env, clazz, "mNativeData", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535
Andreas Gampe987f79f2014-11-18 17:29:46 -08001536 clazz = FindClassOrDie(env, "java/lang/Class");
1537 gClassOffsets.mGetName = GetMethodIDOrDie(env, clazz, "getName", "()Ljava/lang/String;");
Christopher Tate0d4a7922011-08-30 12:09:43 -07001538
Andreas Gampeed6b9df2014-11-20 22:02:20 -08001539 return RegisterMethodsOrDie(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 env, kBinderProxyPathName,
1541 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1542}
1543
1544// ****************************************************************************
1545// ****************************************************************************
1546// ****************************************************************************
1547
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001548int register_android_os_Binder(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549{
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001550 if (int_register_android_os_Binder(env) < 0)
1551 return -1;
1552 if (int_register_android_os_BinderInternal(env) < 0)
1553 return -1;
1554 if (int_register_android_os_BinderProxy(env) < 0)
1555 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556
Andreas Gampe987f79f2014-11-18 17:29:46 -08001557 jclass clazz = FindClassOrDie(env, "android/util/Log");
1558 gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1559 gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
1560 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561
Andreas Gampe987f79f2014-11-18 17:29:46 -08001562 clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
1563 gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1564 gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
1565 "(Ljava/io/FileDescriptor;)V");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566
Andreas Gampe987f79f2014-11-18 17:29:46 -08001567 clazz = FindClassOrDie(env, "android/os/StrictMode");
1568 gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1569 gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
1570 "onBinderStrictModePolicyChange", "(I)V");
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001571
Andreas Gampe1cd76f52017-09-08 17:44:05 -07001572 clazz = FindClassOrDie(env, "java/lang/Thread");
1573 gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
1574 gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
1575 "dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
1576 gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
1577 "()Ljava/lang/Thread;");
1578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 return 0;
1580}