blob: e0003b8150ac6b4a104387e9a840b71b630c0d98 [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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023#include "JNIHelp.h"
24
25#include <fcntl.h>
Mark Salyzyncfd91e72014-04-17 15:40:01 -070026#include <inttypes.h>
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
32#include <utils/Atomic.h>
Mathias Agopian07952722009-05-19 19:08:10 -070033#include <binder/IInterface.h>
34#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035#include <utils/Log.h>
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -070036#include <utils/SystemClock.h>
Christopher Tate0b414482011-02-17 13:00:38 -080037#include <utils/List.h>
38#include <utils/KeyedVector.h>
Colin Cross44bc1862013-07-23 18:17:08 -070039#include <log/logger.h>
Mathias Agopian07952722009-05-19 19:08:10 -070040#include <binder/Parcel.h>
41#include <binder/ProcessState.h>
42#include <binder/IServiceManager.h>
Brad Fitzpatrick5348c012010-03-25 12:43:56 -070043#include <utils/threads.h>
Jeff Brown0bde66a2011-11-07 12:50:08 -080044#include <utils/String8.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
Christopher Tateac5e3502011-08-25 15:48:09 -070046#include <ScopedUtfChars.h>
47#include <ScopedLocalRef.h>
48
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049#include <android_runtime/AndroidRuntime.h>
50
Steve Block71f2cf12011-10-20 11:56:00 +010051//#undef ALOGV
52//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053
Christopher Tate79dd31f2011-03-04 17:45:00 -080054#define DEBUG_DEATH 0
55#if DEBUG_DEATH
Steve Block5baa3a62011-12-20 16:23:08 +000056#define LOGDEATH ALOGD
Christopher Tate79dd31f2011-03-04 17:45:00 -080057#else
Steve Block71f2cf12011-10-20 11:56:00 +010058#define LOGDEATH ALOGV
Christopher Tate79dd31f2011-03-04 17:45:00 -080059#endif
60
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061using namespace android;
62
63// ----------------------------------------------------------------------------
64
65static struct bindernative_offsets_t
66{
67 // Class state.
68 jclass mClass;
69 jmethodID mExecTransact;
70
71 // Object state.
72 jfieldID mObject;
73
74} gBinderOffsets;
75
76// ----------------------------------------------------------------------------
77
78static struct binderinternal_offsets_t
79{
80 // Class state.
81 jclass mClass;
82 jmethodID mForceGc;
83
84} gBinderInternalOffsets;
85
86// ----------------------------------------------------------------------------
87
88static struct debug_offsets_t
89{
90 // Class state.
91 jclass mClass;
92
93} gDebugOffsets;
94
95// ----------------------------------------------------------------------------
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097static struct error_offsets_t
98{
99 jclass mClass;
100} gErrorOffsets;
101
102// ----------------------------------------------------------------------------
103
104static struct binderproxy_offsets_t
105{
106 // Class state.
107 jclass mClass;
108 jmethodID mConstructor;
109 jmethodID mSendDeathNotice;
110
111 // Object state.
112 jfieldID mObject;
113 jfieldID mSelf;
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800114 jfieldID mOrgue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
116} gBinderProxyOffsets;
117
Christopher Tate0d4a7922011-08-30 12:09:43 -0700118static struct class_offsets_t
119{
120 jmethodID mGetName;
121} gClassOffsets;
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123// ----------------------------------------------------------------------------
124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125static struct log_offsets_t
126{
127 // Class state.
128 jclass mClass;
129 jmethodID mLogE;
130} gLogOffsets;
131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132static struct parcel_file_descriptor_offsets_t
133{
134 jclass mClass;
135 jmethodID mConstructor;
136} gParcelFileDescriptorOffsets;
137
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700138static struct strict_mode_callback_offsets_t
139{
140 jclass mClass;
141 jmethodID mCallback;
142} gStrictModeCallbackOffsets;
143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144// ****************************************************************************
145// ****************************************************************************
146// ****************************************************************************
147
148static volatile int32_t gNumRefsCreated = 0;
149static volatile int32_t gNumProxyRefs = 0;
150static volatile int32_t gNumLocalRefs = 0;
151static volatile int32_t gNumDeathRefs = 0;
152
153static void incRefsCreated(JNIEnv* env)
154{
155 int old = android_atomic_inc(&gNumRefsCreated);
156 if (old == 200) {
157 android_atomic_and(0, &gNumRefsCreated);
158 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
159 gBinderInternalOffsets.mForceGc);
160 } else {
Steve Block71f2cf12011-10-20 11:56:00 +0100161 ALOGV("Now have %d binder ops", old);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 }
163}
164
165static JavaVM* jnienv_to_javavm(JNIEnv* env)
166{
167 JavaVM* vm;
168 return env->GetJavaVM(&vm) >= 0 ? vm : NULL;
169}
170
171static JNIEnv* javavm_to_jnienv(JavaVM* vm)
172{
173 JNIEnv* env;
174 return vm->GetEnv((void **)&env, JNI_VERSION_1_4) >= 0 ? env : NULL;
175}
176
177static void report_exception(JNIEnv* env, jthrowable excep, const char* msg)
178{
179 env->ExceptionClear();
180
181 jstring tagstr = env->NewStringUTF(LOG_TAG);
Mathieu Chartiercf6775e2014-08-06 13:39:17 -0700182 jstring msgstr = NULL;
183 if (tagstr != NULL) {
184 msgstr = env->NewStringUTF(msg);
185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
187 if ((tagstr == NULL) || (msgstr == NULL)) {
188 env->ExceptionClear(); /* assume exception (OOM?) was thrown */
Steve Block3762c312012-01-06 19:20:56 +0000189 ALOGE("Unable to call Log.e()\n");
190 ALOGE("%s", msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 goto bail;
192 }
193
194 env->CallStaticIntMethod(
195 gLogOffsets.mClass, gLogOffsets.mLogE, tagstr, msgstr, excep);
196 if (env->ExceptionCheck()) {
197 /* attempting to log the failure has failed */
Steve Block8564c8d2012-01-05 23:22:43 +0000198 ALOGW("Failed trying to log exception, msg='%s'\n", msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 env->ExceptionClear();
200 }
201
202 if (env->IsInstanceOf(excep, gErrorOffsets.mClass)) {
203 /*
204 * It's an Error: Reraise the exception, detach this thread, and
205 * wait for the fireworks. Die even more blatantly after a minute
206 * if the gentler attempt doesn't do the trick.
207 *
208 * The GetJavaVM function isn't on the "approved" list of JNI calls
209 * that can be made while an exception is pending, so we want to
210 * get the VM ptr, throw the exception, and then detach the thread.
211 */
212 JavaVM* vm = jnienv_to_javavm(env);
213 env->Throw(excep);
214 vm->DetachCurrentThread();
215 sleep(60);
Steve Block3762c312012-01-06 19:20:56 +0000216 ALOGE("Forcefully exiting");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 exit(1);
218 *((int *) 1) = 1;
219 }
220
221bail:
222 /* discard local refs created for us by VM */
223 env->DeleteLocalRef(tagstr);
224 env->DeleteLocalRef(msgstr);
225}
226
227class JavaBBinderHolder;
228
229class JavaBBinder : public BBinder
230{
231public:
232 JavaBBinder(JNIEnv* env, jobject object)
233 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))
234 {
Steve Block71f2cf12011-10-20 11:56:00 +0100235 ALOGV("Creating JavaBBinder %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 android_atomic_inc(&gNumLocalRefs);
237 incRefsCreated(env);
238 }
239
240 bool checkSubclass(const void* subclassID) const
241 {
242 return subclassID == &gBinderOffsets;
243 }
244
245 jobject object() const
246 {
247 return mObject;
248 }
249
250protected:
251 virtual ~JavaBBinder()
252 {
Steve Block71f2cf12011-10-20 11:56:00 +0100253 ALOGV("Destroying JavaBBinder %p\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 android_atomic_dec(&gNumLocalRefs);
255 JNIEnv* env = javavm_to_jnienv(mVM);
256 env->DeleteGlobalRef(mObject);
257 }
258
259 virtual status_t onTransact(
260 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0)
261 {
262 JNIEnv* env = javavm_to_jnienv(mVM);
263
Steve Block71f2cf12011-10-20 11:56:00 +0100264 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 -0800265
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700266 IPCThreadState* thread_state = IPCThreadState::self();
267 const int strict_policy_before = thread_state->getStrictModePolicy();
Brad Fitzpatrick02343762010-08-30 16:01:16 -0700268 thread_state->setLastTransactionBinderFlags(flags);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 //printf("Transact from %p to Java code sending: ", this);
271 //data.print();
272 //printf("\n");
273 jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000274 code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply), flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 jthrowable excep = env->ExceptionOccurred();
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700276
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100277 if (excep) {
278 report_exception(env, excep,
279 "*** Uncaught remote exception! "
280 "(Exceptions are not yet supported across processes.)");
281 res = JNI_FALSE;
282
283 /* clean up JNI local ref -- we don't return to Java code */
284 env->DeleteLocalRef(excep);
285 }
286
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700287 // Restore the Java binder thread's state if it changed while
288 // processing a call (as it would if the Parcel's header had a
289 // new policy mask and Parcel.enforceInterface() changed
290 // it...)
291 const int strict_policy_after = thread_state->getStrictModePolicy();
292 if (strict_policy_after != strict_policy_before) {
293 // Our thread-local...
294 thread_state->setStrictModePolicy(strict_policy_before);
295 // And the Java-level thread-local...
296 set_dalvik_blockguard_policy(env, strict_policy_before);
297 }
298
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100299 jthrowable excep2 = env->ExceptionOccurred();
300 if (excep2) {
301 report_exception(env, excep2,
302 "*** Uncaught exception in onBinderStrictModePolicyChange");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 /* clean up JNI local ref -- we don't return to Java code */
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100304 env->DeleteLocalRef(excep2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 }
306
Dianne Hackborna53de062012-05-08 18:53:51 -0700307 // Need to always call through the native implementation of
308 // SYSPROPS_TRANSACTION.
309 if (code == SYSPROPS_TRANSACTION) {
310 BBinder::onTransact(code, data, reply, flags);
311 }
312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 //aout << "onTransact to Java code; result=" << res << endl
314 // << "Transact from " << this << " to Java code returning "
315 // << reply << ": " << *reply << endl;
316 return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
317 }
318
319 virtual status_t dump(int fd, const Vector<String16>& args)
320 {
321 return 0;
322 }
323
324private:
325 JavaVM* const mVM;
326 jobject const mObject;
327};
328
329// ----------------------------------------------------------------------------
330
331class JavaBBinderHolder : public RefBase
332{
333public:
Christopher Tate0b414482011-02-17 13:00:38 -0800334 sp<JavaBBinder> get(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 {
336 AutoMutex _l(mLock);
337 sp<JavaBBinder> b = mBinder.promote();
338 if (b == NULL) {
Christopher Tate0b414482011-02-17 13:00:38 -0800339 b = new JavaBBinder(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 mBinder = b;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700341 ALOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%" PRId32 "\n",
Christopher Tate0b414482011-02-17 13:00:38 -0800342 b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 }
344
345 return b;
346 }
347
348 sp<JavaBBinder> getExisting()
349 {
350 AutoMutex _l(mLock);
351 return mBinder.promote();
352 }
353
354private:
355 Mutex mLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 wp<JavaBBinder> mBinder;
357};
358
359// ----------------------------------------------------------------------------
360
Christopher Tate0b414482011-02-17 13:00:38 -0800361// Per-IBinder death recipient bookkeeping. This is how we reconcile local jobject
362// death recipient references passed in through JNI with the permanent corresponding
363// JavaDeathRecipient objects.
364
365class JavaDeathRecipient;
366
367class DeathRecipientList : public RefBase {
368 List< sp<JavaDeathRecipient> > mList;
369 Mutex mLock;
370
371public:
Christopher Tate79dd31f2011-03-04 17:45:00 -0800372 DeathRecipientList();
Christopher Tate0b414482011-02-17 13:00:38 -0800373 ~DeathRecipientList();
374
375 void add(const sp<JavaDeathRecipient>& recipient);
376 void remove(const sp<JavaDeathRecipient>& recipient);
377 sp<JavaDeathRecipient> find(jobject recipient);
378};
379
380// ----------------------------------------------------------------------------
381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382class JavaDeathRecipient : public IBinder::DeathRecipient
383{
384public:
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800385 JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
Christopher Tate86284c62011-08-17 15:19:29 -0700386 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
387 mObjectWeak(NULL), mList(list)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 {
Christopher Tate0b414482011-02-17 13:00:38 -0800389 // These objects manage their own lifetimes so are responsible for final bookkeeping.
390 // The list holds a strong reference to this object.
Christopher Tate79dd31f2011-03-04 17:45:00 -0800391 LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800392 list->add(this);
Christopher Tate0b414482011-02-17 13:00:38 -0800393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 android_atomic_inc(&gNumDeathRefs);
395 incRefsCreated(env);
396 }
397
398 void binderDied(const wp<IBinder>& who)
399 {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800400 LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
Christopher Tate86284c62011-08-17 15:19:29 -0700401 if (mObject != NULL) {
402 JNIEnv* env = javavm_to_jnienv(mVM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403
Christopher Tate86284c62011-08-17 15:19:29 -0700404 env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
405 gBinderProxyOffsets.mSendDeathNotice, mObject);
406 jthrowable excep = env->ExceptionOccurred();
407 if (excep) {
408 report_exception(env, excep,
409 "*** Uncaught exception returned from death notification!");
410 }
411
412 // Demote from strong ref to weak after binderDied() has been delivered,
413 // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
414 mObjectWeak = env->NewWeakGlobalRef(mObject);
415 env->DeleteGlobalRef(mObject);
416 mObject = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800418 }
419
420 void clearReference()
421 {
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800422 sp<DeathRecipientList> list = mList.promote();
423 if (list != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800424 LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800425 list->remove(this);
Christopher Tate79dd31f2011-03-04 17:45:00 -0800426 } else {
427 LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800428 }
Christopher Tate0b414482011-02-17 13:00:38 -0800429 }
430
431 bool matches(jobject obj) {
Christopher Tate86284c62011-08-17 15:19:29 -0700432 bool result;
Christopher Tate0b414482011-02-17 13:00:38 -0800433 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700434
435 if (mObject != NULL) {
436 result = env->IsSameObject(obj, mObject);
437 } else {
438 jobject me = env->NewLocalRef(mObjectWeak);
439 result = env->IsSameObject(obj, me);
440 env->DeleteLocalRef(me);
441 }
442 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 }
444
Christopher Tateac5e3502011-08-25 15:48:09 -0700445 void warnIfStillLive() {
446 if (mObject != NULL) {
447 // Okay, something is wrong -- we have a hard reference to a live death
448 // recipient on the VM side, but the list is being torn down.
449 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate0d4a7922011-08-30 12:09:43 -0700450 ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
451 ScopedLocalRef<jstring> nameRef(env,
452 (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
453 ScopedUtfChars nameUtf(env, nameRef.get());
454 if (nameUtf.c_str() != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +0000455 ALOGW("BinderProxy is being destroyed but the application did not call "
Christopher Tate0d4a7922011-08-30 12:09:43 -0700456 "unlinkToDeath to unlink all of its death recipients beforehand. "
457 "Releasing leaked death recipient: %s", nameUtf.c_str());
458 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000459 ALOGW("BinderProxy being destroyed; unable to get DR object name");
Christopher Tate0d4a7922011-08-30 12:09:43 -0700460 env->ExceptionClear();
461 }
Christopher Tateac5e3502011-08-25 15:48:09 -0700462 }
463 }
464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465protected:
466 virtual ~JavaDeathRecipient()
467 {
Steve Block6215d3f2012-01-04 20:05:49 +0000468 //ALOGI("Removing death ref: recipient=%p\n", mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 android_atomic_dec(&gNumDeathRefs);
470 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700471 if (mObject != NULL) {
472 env->DeleteGlobalRef(mObject);
473 } else {
474 env->DeleteWeakGlobalRef(mObjectWeak);
475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 }
477
478private:
Christopher Tate86284c62011-08-17 15:19:29 -0700479 JavaVM* const mVM;
480 jobject mObject;
481 jweak mObjectWeak; // will be a weak ref to the same VM-side DeathRecipient after binderDied()
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800482 wp<DeathRecipientList> mList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483};
484
485// ----------------------------------------------------------------------------
486
Christopher Tate79dd31f2011-03-04 17:45:00 -0800487DeathRecipientList::DeathRecipientList() {
488 LOGDEATH("New DRL @ %p", this);
489}
490
Christopher Tate0b414482011-02-17 13:00:38 -0800491DeathRecipientList::~DeathRecipientList() {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800492 LOGDEATH("Destroy DRL @ %p", this);
Christopher Tate0b414482011-02-17 13:00:38 -0800493 AutoMutex _l(mLock);
494
495 // Should never happen -- the JavaDeathRecipient objects that have added themselves
496 // to the list are holding references on the list object. Only when they are torn
497 // down can the list header be destroyed.
498 if (mList.size() > 0) {
Christopher Tateac5e3502011-08-25 15:48:09 -0700499 List< sp<JavaDeathRecipient> >::iterator iter;
500 for (iter = mList.begin(); iter != mList.end(); iter++) {
501 (*iter)->warnIfStillLive();
502 }
Christopher Tate0b414482011-02-17 13:00:38 -0800503 }
504}
505
506void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
507 AutoMutex _l(mLock);
508
Christopher Tate79dd31f2011-03-04 17:45:00 -0800509 LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800510 mList.push_back(recipient);
511}
512
513void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
514 AutoMutex _l(mLock);
515
516 List< sp<JavaDeathRecipient> >::iterator iter;
517 for (iter = mList.begin(); iter != mList.end(); iter++) {
518 if (*iter == recipient) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800519 LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800520 mList.erase(iter);
521 return;
522 }
523 }
524}
525
526sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
527 AutoMutex _l(mLock);
528
529 List< sp<JavaDeathRecipient> >::iterator iter;
530 for (iter = mList.begin(); iter != mList.end(); iter++) {
531 if ((*iter)->matches(recipient)) {
532 return *iter;
533 }
534 }
535 return NULL;
536}
537
Christopher Tate0b414482011-02-17 13:00:38 -0800538// ----------------------------------------------------------------------------
539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540namespace android {
541
542static void proxy_cleanup(const void* id, void* obj, void* cleanupCookie)
543{
544 android_atomic_dec(&gNumProxyRefs);
545 JNIEnv* env = javavm_to_jnienv((JavaVM*)cleanupCookie);
546 env->DeleteGlobalRef((jobject)obj);
547}
548
549static Mutex mProxyLock;
550
551jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
552{
553 if (val == NULL) return NULL;
554
555 if (val->checkSubclass(&gBinderOffsets)) {
556 // One of our own!
557 jobject object = static_cast<JavaBBinder*>(val.get())->object();
Christopher Tate86284c62011-08-17 15:19:29 -0700558 LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 return object;
560 }
561
562 // For the rest of the function we will hold this lock, to serialize
563 // looking/creation of Java proxies for native Binder proxies.
564 AutoMutex _l(mProxyLock);
565
566 // Someone else's... do we know about it?
567 jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
568 if (object != NULL) {
Jeff Browna4ca8ea2013-04-02 18:01:38 -0700569 jobject res = jniGetReferent(env, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 if (res != NULL) {
Steve Block71f2cf12011-10-20 11:56:00 +0100571 ALOGV("objectForBinder %p: found existing %p!\n", val.get(), res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 return res;
573 }
Christopher Tate86284c62011-08-17 15:19:29 -0700574 LOGDEATH("Proxy object %p of IBinder %p no longer in working set!!!", object, val.get());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 android_atomic_dec(&gNumProxyRefs);
576 val->detachObject(&gBinderProxyOffsets);
577 env->DeleteGlobalRef(object);
578 }
579
580 object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
581 if (object != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800582 LOGDEATH("objectForBinder %p: created new proxy %p !\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 // The proxy holds a reference to the native object.
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000584 env->SetLongField(object, gBinderProxyOffsets.mObject, (jlong)val.get());
Mathias Agopianb1d90c82013-03-06 17:45:42 -0800585 val->incStrong((void*)javaObjectForIBinder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 // The native object needs to hold a weak reference back to the
588 // proxy, so we can retrieve the same proxy if it is still active.
589 jobject refObject = env->NewGlobalRef(
590 env->GetObjectField(object, gBinderProxyOffsets.mSelf));
591 val->attachObject(&gBinderProxyOffsets, refObject,
592 jnienv_to_javavm(env), proxy_cleanup);
593
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800594 // Also remember the death recipients registered on this proxy
595 sp<DeathRecipientList> drl = new DeathRecipientList;
596 drl->incStrong((void*)javaObjectForIBinder);
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000597 env->SetLongField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast<jlong>(drl.get()));
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 // Note that a new object reference has been created.
600 android_atomic_inc(&gNumProxyRefs);
601 incRefsCreated(env);
602 }
603
604 return object;
605}
606
607sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
608{
609 if (obj == NULL) return NULL;
610
611 if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
612 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000613 env->GetLongField(obj, gBinderOffsets.mObject);
Christopher Tate0b414482011-02-17 13:00:38 -0800614 return jbh != NULL ? jbh->get(env, obj) : NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 }
616
617 if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
618 return (IBinder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000619 env->GetLongField(obj, gBinderProxyOffsets.mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 }
621
Steve Block8564c8d2012-01-05 23:22:43 +0000622 ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 return NULL;
624}
625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
627{
628 return env->NewObject(
629 gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
630}
631
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -0800632void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
633{
634 // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
635 // to sync our state back to it. See the comments in StrictMode.java.
636 env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
637 gStrictModeCallbackOffsets.mCallback,
638 strict_policy);
639}
640
641void signalExceptionForError(JNIEnv* env, jobject obj, status_t err,
642 bool canThrowRemoteException)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643{
644 switch (err) {
645 case UNKNOWN_ERROR:
646 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
647 break;
648 case NO_MEMORY:
649 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
650 break;
651 case INVALID_OPERATION:
652 jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
653 break;
654 case BAD_VALUE:
655 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
656 break;
657 case BAD_INDEX:
658 jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
659 break;
660 case BAD_TYPE:
661 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
662 break;
663 case NAME_NOT_FOUND:
664 jniThrowException(env, "java/util/NoSuchElementException", NULL);
665 break;
666 case PERMISSION_DENIED:
667 jniThrowException(env, "java/lang/SecurityException", NULL);
668 break;
669 case NOT_ENOUGH_DATA:
670 jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
671 break;
672 case NO_INIT:
673 jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
674 break;
675 case ALREADY_EXISTS:
676 jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
677 break;
678 case DEAD_OBJECT:
Jeff Brown0bde66a2011-11-07 12:50:08 -0800679 // DeadObjectException is a checked exception, only throw from certain methods.
680 jniThrowException(env, canThrowRemoteException
681 ? "android/os/DeadObjectException"
682 : "java/lang/RuntimeException", NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 break;
684 case UNKNOWN_TRANSACTION:
685 jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
686 break;
687 case FAILED_TRANSACTION:
Steve Block3762c312012-01-06 19:20:56 +0000688 ALOGE("!!! FAILED BINDER TRANSACTION !!!");
Jeff Brown0bde66a2011-11-07 12:50:08 -0800689 // TransactionTooLargeException is a checked exception, only throw from certain methods.
690 // FIXME: Transaction too large is the most common reason for FAILED_TRANSACTION
691 // but it is not the only one. The Binder driver can return BR_FAILED_REPLY
692 // for other reasons also, such as if the transaction is malformed or
693 // refers to an FD that has been closed. We should change the driver
694 // to enable us to distinguish these cases in the future.
695 jniThrowException(env, canThrowRemoteException
696 ? "android/os/TransactionTooLargeException"
697 : "java/lang/RuntimeException", NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 break;
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -0400699 case FDS_NOT_ALLOWED:
700 jniThrowException(env, "java/lang/RuntimeException",
701 "Not allowed to write file descriptors here");
702 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 default:
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700704 ALOGE("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800705 String8 msg;
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700706 msg.appendFormat("Unknown binder error code. 0x%" PRIx32, err);
Jeff Brown0bde66a2011-11-07 12:50:08 -0800707 // RemoteException is a checked exception, only throw from certain methods.
708 jniThrowException(env, canThrowRemoteException
709 ? "android/os/RemoteException" : "java/lang/RuntimeException", msg.string());
710 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712}
713
714}
715
716// ----------------------------------------------------------------------------
717
718static jint android_os_Binder_getCallingPid(JNIEnv* env, jobject clazz)
719{
720 return IPCThreadState::self()->getCallingPid();
721}
722
723static jint android_os_Binder_getCallingUid(JNIEnv* env, jobject clazz)
724{
725 return IPCThreadState::self()->getCallingUid();
726}
727
728static jlong android_os_Binder_clearCallingIdentity(JNIEnv* env, jobject clazz)
729{
730 return IPCThreadState::self()->clearCallingIdentity();
731}
732
733static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
734{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700735 // XXX temporary sanity check to debug crashes.
736 int uid = (int)(token>>32);
737 if (uid > 0 && uid < 999) {
738 // In Android currently there are no uids in this range.
739 char buf[128];
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700740 sprintf(buf, "Restoring bad calling ident: 0x%" PRIx64, token);
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700741 jniThrowException(env, "java/lang/IllegalStateException", buf);
742 return;
743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 IPCThreadState::self()->restoreCallingIdentity(token);
745}
746
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700747static void android_os_Binder_setThreadStrictModePolicy(JNIEnv* env, jobject clazz, jint policyMask)
748{
749 IPCThreadState::self()->setStrictModePolicy(policyMask);
750}
751
752static jint android_os_Binder_getThreadStrictModePolicy(JNIEnv* env, jobject clazz)
753{
754 return IPCThreadState::self()->getStrictModePolicy();
755}
756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
758{
759 IPCThreadState::self()->flushCommands();
760}
761
Christopher Tate0b414482011-02-17 13:00:38 -0800762static void android_os_Binder_init(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763{
Christopher Tate0b414482011-02-17 13:00:38 -0800764 JavaBBinderHolder* jbh = new JavaBBinderHolder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 if (jbh == NULL) {
766 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
767 return;
768 }
Steve Block71f2cf12011-10-20 11:56:00 +0100769 ALOGV("Java Binder %p: acquiring first ref on holder %p", obj, jbh);
Christopher Tate0b414482011-02-17 13:00:38 -0800770 jbh->incStrong((void*)android_os_Binder_init);
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000771 env->SetLongField(obj, gBinderOffsets.mObject, (jlong)jbh);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772}
773
Christopher Tate0b414482011-02-17 13:00:38 -0800774static void android_os_Binder_destroy(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775{
776 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000777 env->GetLongField(obj, gBinderOffsets.mObject);
Jeff Brown582763a2010-03-24 18:56:57 -0700778 if (jbh != NULL) {
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000779 env->SetLongField(obj, gBinderOffsets.mObject, 0);
Steve Block71f2cf12011-10-20 11:56:00 +0100780 ALOGV("Java Binder %p: removing ref on holder %p", obj, jbh);
Christopher Tate0b414482011-02-17 13:00:38 -0800781 jbh->decStrong((void*)android_os_Binder_init);
Jeff Brown582763a2010-03-24 18:56:57 -0700782 } else {
783 // Encountering an uninitialized binder is harmless. All it means is that
784 // the Binder was only partially initialized when its finalizer ran and called
785 // destroy(). The Binder could be partially initialized for several reasons.
786 // For example, a Binder subclass constructor might have thrown an exception before
787 // it could delegate to its superclass's constructor. Consequently init() would
788 // not have been called and the holder pointer would remain NULL.
Steve Block71f2cf12011-10-20 11:56:00 +0100789 ALOGV("Java Binder %p: ignoring uninitialized binder", obj);
Jeff Brown582763a2010-03-24 18:56:57 -0700790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791}
792
793// ----------------------------------------------------------------------------
794
795static const JNINativeMethod gBinderMethods[] = {
796 /* name, signature, funcPtr */
797 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
798 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
799 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
800 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700801 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
802 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
804 { "init", "()V", (void*)android_os_Binder_init },
805 { "destroy", "()V", (void*)android_os_Binder_destroy }
806};
807
808const char* const kBinderPathName = "android/os/Binder";
809
810static int int_register_android_os_Binder(JNIEnv* env)
811{
812 jclass clazz;
813
814 clazz = env->FindClass(kBinderPathName);
815 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Binder");
816
817 gBinderOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
818 gBinderOffsets.mExecTransact
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000819 = env->GetMethodID(clazz, "execTransact", "(IJJI)Z");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 assert(gBinderOffsets.mExecTransact);
821
822 gBinderOffsets.mObject
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000823 = env->GetFieldID(clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 assert(gBinderOffsets.mObject);
825
826 return AndroidRuntime::registerNativeMethods(
827 env, kBinderPathName,
828 gBinderMethods, NELEM(gBinderMethods));
829}
830
831// ****************************************************************************
832// ****************************************************************************
833// ****************************************************************************
834
835namespace android {
836
837jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
838{
839 return gNumLocalRefs;
840}
841
842jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
843{
844 return gNumProxyRefs;
845}
846
847jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
848{
849 return gNumDeathRefs;
850}
851
852}
853
854// ****************************************************************************
855// ****************************************************************************
856// ****************************************************************************
857
858static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
859{
860 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
861 return javaObjectForIBinder(env, b);
862}
863
864static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
865{
866 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
867 android::IPCThreadState::self()->joinThreadPool();
868}
869
Dianne Hackborn887f3552009-12-07 17:59:37 -0800870static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
871 jobject clazz, jboolean disable)
872{
873 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
874}
875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
877{
Steve Block71f2cf12011-10-20 11:56:00 +0100878 ALOGV("Gc has executed, clearing binder ops");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 android_atomic_and(0, &gNumRefsCreated);
880}
881
882// ----------------------------------------------------------------------------
883
884static const JNINativeMethod gBinderInternalMethods[] = {
885 /* name, signature, funcPtr */
886 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
887 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -0800888 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc }
890};
891
892const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
893
894static int int_register_android_os_BinderInternal(JNIEnv* env)
895{
896 jclass clazz;
897
898 clazz = env->FindClass(kBinderInternalPathName);
899 LOG_FATAL_IF(clazz == NULL, "Unable to find class com.android.internal.os.BinderInternal");
900
901 gBinderInternalOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
902 gBinderInternalOffsets.mForceGc
903 = env->GetStaticMethodID(clazz, "forceBinderGc", "()V");
904 assert(gBinderInternalOffsets.mForceGc);
905
906 return AndroidRuntime::registerNativeMethods(
907 env, kBinderInternalPathName,
908 gBinderInternalMethods, NELEM(gBinderInternalMethods));
909}
910
911// ****************************************************************************
912// ****************************************************************************
913// ****************************************************************************
914
915static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
916{
917 IBinder* target = (IBinder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000918 env->GetLongField(obj, gBinderProxyOffsets.mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 if (target == NULL) {
920 return JNI_FALSE;
921 }
922 status_t err = target->pingBinder();
923 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
924}
925
926static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
927{
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000928 IBinder* target = (IBinder*) env->GetLongField(obj, gBinderProxyOffsets.mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 if (target != NULL) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700930 const String16& desc = target->getInterfaceDescriptor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 return env->NewString(desc.string(), desc.size());
932 }
933 jniThrowException(env, "java/lang/RuntimeException",
934 "No binder found for object");
935 return NULL;
936}
937
938static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
939{
940 IBinder* target = (IBinder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +0000941 env->GetLongField(obj, gBinderProxyOffsets.mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 if (target == NULL) {
943 return JNI_FALSE;
944 }
945 bool alive = target->isBinderAlive();
946 return alive ? JNI_TRUE : JNI_FALSE;
947}
948
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700949static int getprocname(pid_t pid, char *buf, size_t len) {
Sungmin Choiec3d44c2012-12-21 14:24:33 +0900950 char filename[32];
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700951 FILE *f;
952
Sungmin Choiec3d44c2012-12-21 14:24:33 +0900953 snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700954 f = fopen(filename, "r");
Sungmin Choiec3d44c2012-12-21 14:24:33 +0900955 if (!f) {
956 *buf = '\0';
957 return 1;
958 }
959 if (!fgets(buf, len, f)) {
960 *buf = '\0';
961 fclose(f);
962 return 2;
963 }
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700964 fclose(f);
965 return 0;
966}
967
968static bool push_eventlog_string(char** pos, const char* end, const char* str) {
969 jint len = strlen(str);
970 int space_needed = 1 + sizeof(len) + len;
971 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -0700972 ALOGW("not enough space for string. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700973 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700974 return false;
975 }
976 **pos = EVENT_TYPE_STRING;
977 (*pos)++;
978 memcpy(*pos, &len, sizeof(len));
979 *pos += sizeof(len);
980 memcpy(*pos, str, len);
981 *pos += len;
982 return true;
983}
984
985static bool push_eventlog_int(char** pos, const char* end, jint val) {
986 int space_needed = 1 + sizeof(val);
987 if (end - *pos < space_needed) {
Mark Salyzyn5b6da1a2014-04-17 17:25:36 -0700988 ALOGW("not enough space for int. remain=%" PRIdPTR "; needed=%d",
Mark Salyzyncfd91e72014-04-17 15:40:01 -0700989 end - *pos, space_needed);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700990 return false;
991 }
992 **pos = EVENT_TYPE_INT;
993 (*pos)++;
994 memcpy(*pos, &val, sizeof(val));
995 *pos += sizeof(val);
996 return true;
997}
998
999// From frameworks/base/core/java/android/content/EventLogTags.logtags:
Jeff Sharkey2b4d22c2013-04-26 10:52:00 -07001000#define ENABLE_BINDER_SAMPLE 0
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001001#define LOGTAG_BINDER_OPERATION 52004
1002
1003static void conditionally_log_binder_call(int64_t start_millis,
1004 IBinder* target, jint code) {
1005 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
1006
1007 int sample_percent;
1008 if (duration_ms >= 500) {
1009 sample_percent = 100;
1010 } else {
1011 sample_percent = 100 * duration_ms / 500;
1012 if (sample_percent == 0) {
1013 return;
1014 }
1015 if (sample_percent < (random() % 100 + 1)) {
1016 return;
1017 }
1018 }
1019
1020 char process_name[40];
1021 getprocname(getpid(), process_name, sizeof(process_name));
1022 String8 desc(target->getInterfaceDescriptor());
1023
1024 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1025 buf[0] = EVENT_TYPE_LIST;
1026 buf[1] = 5;
1027 char* pos = &buf[2];
1028 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1029 if (!push_eventlog_string(&pos, end, desc.string())) return;
1030 if (!push_eventlog_int(&pos, end, code)) return;
1031 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1032 if (!push_eventlog_string(&pos, end, process_name)) return;
1033 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1034 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1035 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1036}
1037
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001038// We only measure binder call durations to potentially log them if
Elliott Hughes06451fe2014-08-18 10:26:52 -07001039// we're on the main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001040static bool should_time_binder_calls() {
Elliott Hughes06451fe2014-08-18 10:26:52 -07001041 return (getpid() == gettid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001042}
1043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001045 jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046{
1047 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001048 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 return JNI_FALSE;
1050 }
1051
1052 Parcel* data = parcelForJavaObject(env, dataObj);
1053 if (data == NULL) {
1054 return JNI_FALSE;
1055 }
1056 Parcel* reply = parcelForJavaObject(env, replyObj);
1057 if (reply == NULL && replyObj != NULL) {
1058 return JNI_FALSE;
1059 }
1060
1061 IBinder* target = (IBinder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001062 env->GetLongField(obj, gBinderProxyOffsets.mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 if (target == NULL) {
1064 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1065 return JNI_FALSE;
1066 }
1067
Mark Salyzyncfd91e72014-04-17 15:40:01 -07001068 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 -08001069 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001070
Jeff Sharkey2b4d22c2013-04-26 10:52:00 -07001071#if ENABLE_BINDER_SAMPLE
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001072 // Only log the binder call duration for things on the Java-level main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001073 // But if we don't
1074 const bool time_binder_calls = should_time_binder_calls();
1075
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001076 int64_t start_millis;
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001077 if (time_binder_calls) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001078 start_millis = uptimeMillis();
1079 }
Jeff Sharkey2b4d22c2013-04-26 10:52:00 -07001080#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 //printf("Transact from Java code to %p sending: ", target); data->print();
1082 status_t err = target->transact(code, *data, reply, flags);
1083 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Jeff Sharkey2b4d22c2013-04-26 10:52:00 -07001084#if ENABLE_BINDER_SAMPLE
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001085 if (time_binder_calls) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001086 conditionally_log_binder_call(start_millis, target, code);
1087 }
Jeff Sharkey2b4d22c2013-04-26 10:52:00 -07001088#endif
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 if (err == NO_ERROR) {
1091 return JNI_TRUE;
1092 } else if (err == UNKNOWN_TRANSACTION) {
1093 return JNI_FALSE;
1094 }
1095
Jeff Brown0bde66a2011-11-07 12:50:08 -08001096 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 return JNI_FALSE;
1098}
1099
1100static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
Jeff Brown0bde66a2011-11-07 12:50:08 -08001101 jobject recipient, jint flags) // throws RemoteException
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102{
1103 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001104 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 return;
1106 }
1107
1108 IBinder* target = (IBinder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001109 env->GetLongField(obj, gBinderProxyOffsets.mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001111 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 assert(false);
1113 }
1114
Christopher Tate79dd31f2011-03-04 17:45:00 -08001115 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116
1117 if (!target->localBinder()) {
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001118 DeathRecipientList* list = (DeathRecipientList*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001119 env->GetLongField(obj, gBinderProxyOffsets.mOrgue);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001120 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001121 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 if (err != NO_ERROR) {
1123 // Failure adding the death recipient, so clear its reference
1124 // now.
1125 jdr->clearReference();
Jeff Brown0bde66a2011-11-07 12:50:08 -08001126 signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 }
1128 }
1129}
1130
1131static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1132 jobject recipient, jint flags)
1133{
1134 jboolean res = JNI_FALSE;
1135 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001136 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 return res;
1138 }
1139
1140 IBinder* target = (IBinder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001141 env->GetLongField(obj, gBinderProxyOffsets.mObject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 if (target == NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001143 ALOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 return JNI_FALSE;
1145 }
1146
Christopher Tate79dd31f2011-03-04 17:45:00 -08001147 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148
1149 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001150 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001151
1152 // If we find the matching recipient, proceed to unlink using that
1153 DeathRecipientList* list = (DeathRecipientList*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001154 env->GetLongField(obj, gBinderProxyOffsets.mOrgue);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001155 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001156 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001157 if (origJDR != NULL) {
1158 wp<IBinder::DeathRecipient> dr;
1159 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1160 if (err == NO_ERROR && dr != NULL) {
1161 sp<IBinder::DeathRecipient> sdr = dr.promote();
1162 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1163 if (jdr != NULL) {
1164 jdr->clearReference();
1165 }
1166 }
1167 }
1168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 if (err == NO_ERROR || err == DEAD_OBJECT) {
1170 res = JNI_TRUE;
1171 } else {
1172 jniThrowException(env, "java/util/NoSuchElementException",
1173 "Death link does not exist");
1174 }
1175 }
1176
1177 return res;
1178}
1179
1180static void android_os_BinderProxy_destroy(JNIEnv* env, jobject obj)
1181{
1182 IBinder* b = (IBinder*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001183 env->GetLongField(obj, gBinderProxyOffsets.mObject);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001184 DeathRecipientList* drl = (DeathRecipientList*)
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001185 env->GetLongField(obj, gBinderProxyOffsets.mOrgue);
Christopher Tate0b414482011-02-17 13:00:38 -08001186
Christopher Tate79dd31f2011-03-04 17:45:00 -08001187 LOGDEATH("Destroying BinderProxy %p: binder=%p drl=%p\n", obj, b, drl);
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001188 env->SetLongField(obj, gBinderProxyOffsets.mObject, 0);
1189 env->SetLongField(obj, gBinderProxyOffsets.mOrgue, 0);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001190 drl->decStrong((void*)javaObjectForIBinder);
Mathias Agopianb1d90c82013-03-06 17:45:42 -08001191 b->decStrong((void*)javaObjectForIBinder);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001192
1193 IPCThreadState::self()->flushCommands();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194}
1195
1196// ----------------------------------------------------------------------------
1197
1198static const JNINativeMethod gBinderProxyMethods[] = {
1199 /* name, signature, funcPtr */
1200 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1201 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1202 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
1203 {"transact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
1204 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1205 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
1206 {"destroy", "()V", (void*)android_os_BinderProxy_destroy},
1207};
1208
1209const char* const kBinderProxyPathName = "android/os/BinderProxy";
1210
1211static int int_register_android_os_BinderProxy(JNIEnv* env)
1212{
1213 jclass clazz;
1214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 clazz = env->FindClass("java/lang/Error");
1216 LOG_FATAL_IF(clazz == NULL, "Unable to find class java.lang.Error");
1217 gErrorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 clazz = env->FindClass(kBinderProxyPathName);
1220 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.BinderProxy");
1221
1222 gBinderProxyOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1223 gBinderProxyOffsets.mConstructor
1224 = env->GetMethodID(clazz, "<init>", "()V");
1225 assert(gBinderProxyOffsets.mConstructor);
1226 gBinderProxyOffsets.mSendDeathNotice
1227 = env->GetStaticMethodID(clazz, "sendDeathNotice", "(Landroid/os/IBinder$DeathRecipient;)V");
1228 assert(gBinderProxyOffsets.mSendDeathNotice);
1229
1230 gBinderProxyOffsets.mObject
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001231 = env->GetFieldID(clazz, "mObject", "J");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 assert(gBinderProxyOffsets.mObject);
1233 gBinderProxyOffsets.mSelf
1234 = env->GetFieldID(clazz, "mSelf", "Ljava/lang/ref/WeakReference;");
1235 assert(gBinderProxyOffsets.mSelf);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001236 gBinderProxyOffsets.mOrgue
Ashok Bhat8ab665d2014-01-22 16:00:20 +00001237 = env->GetFieldID(clazz, "mOrgue", "J");
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001238 assert(gBinderProxyOffsets.mOrgue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239
Christopher Tate0d4a7922011-08-30 12:09:43 -07001240 clazz = env->FindClass("java/lang/Class");
1241 LOG_FATAL_IF(clazz == NULL, "Unable to find java.lang.Class");
1242 gClassOffsets.mGetName = env->GetMethodID(clazz, "getName", "()Ljava/lang/String;");
1243 assert(gClassOffsets.mGetName);
1244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 return AndroidRuntime::registerNativeMethods(
1246 env, kBinderProxyPathName,
1247 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1248}
1249
1250// ****************************************************************************
1251// ****************************************************************************
1252// ****************************************************************************
1253
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001254int register_android_os_Binder(JNIEnv* env)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255{
Jeff Sharkeyd84e1ce2012-03-06 18:26:19 -08001256 if (int_register_android_os_Binder(env) < 0)
1257 return -1;
1258 if (int_register_android_os_BinderInternal(env) < 0)
1259 return -1;
1260 if (int_register_android_os_BinderProxy(env) < 0)
1261 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 jclass clazz;
1264
1265 clazz = env->FindClass("android/util/Log");
1266 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.util.Log");
1267 gLogOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1268 gLogOffsets.mLogE = env->GetStaticMethodID(
1269 clazz, "e", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
1270 assert(gLogOffsets.mLogE);
1271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 clazz = env->FindClass("android/os/ParcelFileDescriptor");
1273 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor");
1274 gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1275 gParcelFileDescriptorOffsets.mConstructor
1276 = env->GetMethodID(clazz, "<init>", "(Ljava/io/FileDescriptor;)V");
1277
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001278 clazz = env->FindClass("android/os/StrictMode");
1279 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.StrictMode");
1280 gStrictModeCallbackOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1281 gStrictModeCallbackOffsets.mCallback = env->GetStaticMethodID(
1282 clazz, "onBinderStrictModePolicyChange", "(I)V");
1283 LOG_FATAL_IF(gStrictModeCallbackOffsets.mCallback == NULL,
1284 "Unable to find strict mode callback.");
1285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 return 0;
1287}