blob: 494a2b33ade21b1ac9cb40306c623dcc3ff07224 [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
20#include "android_util_Binder.h"
21#include "JNIHelp.h"
22
23#include <fcntl.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024#include <stdio.h>
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -070025#include <sys/stat.h>
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -070026#include <sys/types.h>
Brad Fitzpatrick8f26b322010-03-25 00:25:37 -070027#include <unistd.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028
29#include <utils/Atomic.h>
Mathias Agopian07952722009-05-19 19:08:10 -070030#include <binder/IInterface.h>
31#include <binder/IPCThreadState.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032#include <utils/Log.h>
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -070033#include <utils/SystemClock.h>
Christopher Tate0b414482011-02-17 13:00:38 -080034#include <utils/List.h>
35#include <utils/KeyedVector.h>
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -070036#include <cutils/logger.h>
Mathias Agopian07952722009-05-19 19:08:10 -070037#include <binder/Parcel.h>
38#include <binder/ProcessState.h>
39#include <binder/IServiceManager.h>
Brad Fitzpatrick5348c012010-03-25 12:43:56 -070040#include <utils/threads.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041
Christopher Tateac5e3502011-08-25 15:48:09 -070042#include <ScopedUtfChars.h>
43#include <ScopedLocalRef.h>
44
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045#include <android_runtime/AndroidRuntime.h>
46
47//#undef LOGV
48//#define LOGV(...) fprintf(stderr, __VA_ARGS__)
49
Christopher Tate79dd31f2011-03-04 17:45:00 -080050#define DEBUG_DEATH 0
51#if DEBUG_DEATH
52#define LOGDEATH LOGD
53#else
54#define LOGDEATH LOGV
55#endif
56
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057using namespace android;
58
59// ----------------------------------------------------------------------------
60
61static struct bindernative_offsets_t
62{
63 // Class state.
64 jclass mClass;
65 jmethodID mExecTransact;
66
67 // Object state.
68 jfieldID mObject;
69
70} gBinderOffsets;
71
72// ----------------------------------------------------------------------------
73
74static struct binderinternal_offsets_t
75{
76 // Class state.
77 jclass mClass;
78 jmethodID mForceGc;
79
80} gBinderInternalOffsets;
81
82// ----------------------------------------------------------------------------
83
84static struct debug_offsets_t
85{
86 // Class state.
87 jclass mClass;
88
89} gDebugOffsets;
90
91// ----------------------------------------------------------------------------
92
93static struct weakreference_offsets_t
94{
95 // Class state.
96 jclass mClass;
97 jmethodID mGet;
98
99} gWeakReferenceOffsets;
100
101static struct error_offsets_t
102{
103 jclass mClass;
104} gErrorOffsets;
105
106// ----------------------------------------------------------------------------
107
108static struct binderproxy_offsets_t
109{
110 // Class state.
111 jclass mClass;
112 jmethodID mConstructor;
113 jmethodID mSendDeathNotice;
114
115 // Object state.
116 jfieldID mObject;
117 jfieldID mSelf;
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800118 jfieldID mOrgue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
120} gBinderProxyOffsets;
121
Christopher Tate0d4a7922011-08-30 12:09:43 -0700122static struct class_offsets_t
123{
124 jmethodID mGetName;
125} gClassOffsets;
126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127// ----------------------------------------------------------------------------
128
129static struct parcel_offsets_t
130{
131 jfieldID mObject;
132 jfieldID mOwnObject;
133} gParcelOffsets;
134
135static struct log_offsets_t
136{
137 // Class state.
138 jclass mClass;
139 jmethodID mLogE;
140} gLogOffsets;
141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142static struct parcel_file_descriptor_offsets_t
143{
144 jclass mClass;
145 jmethodID mConstructor;
146} gParcelFileDescriptorOffsets;
147
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700148static struct strict_mode_callback_offsets_t
149{
150 jclass mClass;
151 jmethodID mCallback;
152} gStrictModeCallbackOffsets;
153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154// ****************************************************************************
155// ****************************************************************************
156// ****************************************************************************
157
158static volatile int32_t gNumRefsCreated = 0;
159static volatile int32_t gNumProxyRefs = 0;
160static volatile int32_t gNumLocalRefs = 0;
161static volatile int32_t gNumDeathRefs = 0;
162
163static void incRefsCreated(JNIEnv* env)
164{
165 int old = android_atomic_inc(&gNumRefsCreated);
166 if (old == 200) {
167 android_atomic_and(0, &gNumRefsCreated);
168 env->CallStaticVoidMethod(gBinderInternalOffsets.mClass,
169 gBinderInternalOffsets.mForceGc);
170 } else {
171 LOGV("Now have %d binder ops", old);
172 }
173}
174
175static JavaVM* jnienv_to_javavm(JNIEnv* env)
176{
177 JavaVM* vm;
178 return env->GetJavaVM(&vm) >= 0 ? vm : NULL;
179}
180
181static JNIEnv* javavm_to_jnienv(JavaVM* vm)
182{
183 JNIEnv* env;
184 return vm->GetEnv((void **)&env, JNI_VERSION_1_4) >= 0 ? env : NULL;
185}
186
187static void report_exception(JNIEnv* env, jthrowable excep, const char* msg)
188{
189 env->ExceptionClear();
190
191 jstring tagstr = env->NewStringUTF(LOG_TAG);
192 jstring msgstr = env->NewStringUTF(msg);
193
194 if ((tagstr == NULL) || (msgstr == NULL)) {
195 env->ExceptionClear(); /* assume exception (OOM?) was thrown */
196 LOGE("Unable to call Log.e()\n");
197 LOGE("%s", msg);
198 goto bail;
199 }
200
201 env->CallStaticIntMethod(
202 gLogOffsets.mClass, gLogOffsets.mLogE, tagstr, msgstr, excep);
203 if (env->ExceptionCheck()) {
204 /* attempting to log the failure has failed */
205 LOGW("Failed trying to log exception, msg='%s'\n", msg);
206 env->ExceptionClear();
207 }
208
209 if (env->IsInstanceOf(excep, gErrorOffsets.mClass)) {
210 /*
211 * It's an Error: Reraise the exception, detach this thread, and
212 * wait for the fireworks. Die even more blatantly after a minute
213 * if the gentler attempt doesn't do the trick.
214 *
215 * The GetJavaVM function isn't on the "approved" list of JNI calls
216 * that can be made while an exception is pending, so we want to
217 * get the VM ptr, throw the exception, and then detach the thread.
218 */
219 JavaVM* vm = jnienv_to_javavm(env);
220 env->Throw(excep);
221 vm->DetachCurrentThread();
222 sleep(60);
223 LOGE("Forcefully exiting");
224 exit(1);
225 *((int *) 1) = 1;
226 }
227
228bail:
229 /* discard local refs created for us by VM */
230 env->DeleteLocalRef(tagstr);
231 env->DeleteLocalRef(msgstr);
232}
233
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700234static void set_dalvik_blockguard_policy(JNIEnv* env, jint strict_policy)
235{
236 // Call back into android.os.StrictMode#onBinderStrictModePolicyChange
237 // to sync our state back to it. See the comments in StrictMode.java.
238 env->CallStaticVoidMethod(gStrictModeCallbackOffsets.mClass,
239 gStrictModeCallbackOffsets.mCallback,
240 strict_policy);
241}
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243class JavaBBinderHolder;
244
245class JavaBBinder : public BBinder
246{
247public:
248 JavaBBinder(JNIEnv* env, jobject object)
249 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object))
250 {
251 LOGV("Creating JavaBBinder %p\n", this);
252 android_atomic_inc(&gNumLocalRefs);
253 incRefsCreated(env);
254 }
255
256 bool checkSubclass(const void* subclassID) const
257 {
258 return subclassID == &gBinderOffsets;
259 }
260
261 jobject object() const
262 {
263 return mObject;
264 }
265
266protected:
267 virtual ~JavaBBinder()
268 {
269 LOGV("Destroying JavaBBinder %p\n", this);
270 android_atomic_dec(&gNumLocalRefs);
271 JNIEnv* env = javavm_to_jnienv(mVM);
272 env->DeleteGlobalRef(mObject);
273 }
274
275 virtual status_t onTransact(
276 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0)
277 {
278 JNIEnv* env = javavm_to_jnienv(mVM);
279
280 LOGV("onTransact() on %p calling object %p in env %p vm %p\n", this, mObject, env, mVM);
281
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700282 IPCThreadState* thread_state = IPCThreadState::self();
283 const int strict_policy_before = thread_state->getStrictModePolicy();
Brad Fitzpatrick02343762010-08-30 16:01:16 -0700284 thread_state->setLastTransactionBinderFlags(flags);
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 //printf("Transact from %p to Java code sending: ", this);
287 //data.print();
288 //printf("\n");
289 jboolean res = env->CallBooleanMethod(mObject, gBinderOffsets.mExecTransact,
290 code, (int32_t)&data, (int32_t)reply, flags);
291 jthrowable excep = env->ExceptionOccurred();
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700292
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100293 if (excep) {
294 report_exception(env, excep,
295 "*** Uncaught remote exception! "
296 "(Exceptions are not yet supported across processes.)");
297 res = JNI_FALSE;
298
299 /* clean up JNI local ref -- we don't return to Java code */
300 env->DeleteLocalRef(excep);
301 }
302
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700303 // Restore the Java binder thread's state if it changed while
304 // processing a call (as it would if the Parcel's header had a
305 // new policy mask and Parcel.enforceInterface() changed
306 // it...)
307 const int strict_policy_after = thread_state->getStrictModePolicy();
308 if (strict_policy_after != strict_policy_before) {
309 // Our thread-local...
310 thread_state->setStrictModePolicy(strict_policy_before);
311 // And the Java-level thread-local...
312 set_dalvik_blockguard_policy(env, strict_policy_before);
313 }
314
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100315 jthrowable excep2 = env->ExceptionOccurred();
316 if (excep2) {
317 report_exception(env, excep2,
318 "*** Uncaught exception in onBinderStrictModePolicyChange");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 /* clean up JNI local ref -- we don't return to Java code */
Bjorn Bringert9013ccd2011-04-26 19:10:58 +0100320 env->DeleteLocalRef(excep2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321 }
322
323 //aout << "onTransact to Java code; result=" << res << endl
324 // << "Transact from " << this << " to Java code returning "
325 // << reply << ": " << *reply << endl;
326 return res != JNI_FALSE ? NO_ERROR : UNKNOWN_TRANSACTION;
327 }
328
329 virtual status_t dump(int fd, const Vector<String16>& args)
330 {
331 return 0;
332 }
333
334private:
335 JavaVM* const mVM;
336 jobject const mObject;
337};
338
339// ----------------------------------------------------------------------------
340
341class JavaBBinderHolder : public RefBase
342{
343public:
Christopher Tate0b414482011-02-17 13:00:38 -0800344 sp<JavaBBinder> get(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 {
346 AutoMutex _l(mLock);
347 sp<JavaBBinder> b = mBinder.promote();
348 if (b == NULL) {
Christopher Tate0b414482011-02-17 13:00:38 -0800349 b = new JavaBBinder(env, obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 mBinder = b;
351 LOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%d\n",
Christopher Tate0b414482011-02-17 13:00:38 -0800352 b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 }
354
355 return b;
356 }
357
358 sp<JavaBBinder> getExisting()
359 {
360 AutoMutex _l(mLock);
361 return mBinder.promote();
362 }
363
364private:
365 Mutex mLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 wp<JavaBBinder> mBinder;
367};
368
369// ----------------------------------------------------------------------------
370
Christopher Tate0b414482011-02-17 13:00:38 -0800371// Per-IBinder death recipient bookkeeping. This is how we reconcile local jobject
372// death recipient references passed in through JNI with the permanent corresponding
373// JavaDeathRecipient objects.
374
375class JavaDeathRecipient;
376
377class DeathRecipientList : public RefBase {
378 List< sp<JavaDeathRecipient> > mList;
379 Mutex mLock;
380
381public:
Christopher Tate79dd31f2011-03-04 17:45:00 -0800382 DeathRecipientList();
Christopher Tate0b414482011-02-17 13:00:38 -0800383 ~DeathRecipientList();
384
385 void add(const sp<JavaDeathRecipient>& recipient);
386 void remove(const sp<JavaDeathRecipient>& recipient);
387 sp<JavaDeathRecipient> find(jobject recipient);
388};
389
390// ----------------------------------------------------------------------------
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392class JavaDeathRecipient : public IBinder::DeathRecipient
393{
394public:
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800395 JavaDeathRecipient(JNIEnv* env, jobject object, const sp<DeathRecipientList>& list)
Christopher Tate86284c62011-08-17 15:19:29 -0700396 : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
397 mObjectWeak(NULL), mList(list)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 {
Christopher Tate0b414482011-02-17 13:00:38 -0800399 // These objects manage their own lifetimes so are responsible for final bookkeeping.
400 // The list holds a strong reference to this object.
Christopher Tate79dd31f2011-03-04 17:45:00 -0800401 LOGDEATH("Adding JDR %p to DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800402 list->add(this);
Christopher Tate0b414482011-02-17 13:00:38 -0800403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 android_atomic_inc(&gNumDeathRefs);
405 incRefsCreated(env);
406 }
407
408 void binderDied(const wp<IBinder>& who)
409 {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800410 LOGDEATH("Receiving binderDied() on JavaDeathRecipient %p\n", this);
Christopher Tate86284c62011-08-17 15:19:29 -0700411 if (mObject != NULL) {
412 JNIEnv* env = javavm_to_jnienv(mVM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413
Christopher Tate86284c62011-08-17 15:19:29 -0700414 env->CallStaticVoidMethod(gBinderProxyOffsets.mClass,
415 gBinderProxyOffsets.mSendDeathNotice, mObject);
416 jthrowable excep = env->ExceptionOccurred();
417 if (excep) {
418 report_exception(env, excep,
419 "*** Uncaught exception returned from death notification!");
420 }
421
422 // Demote from strong ref to weak after binderDied() has been delivered,
423 // to allow the DeathRecipient and BinderProxy to be GC'd if no longer needed.
424 mObjectWeak = env->NewWeakGlobalRef(mObject);
425 env->DeleteGlobalRef(mObject);
426 mObject = NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 }
429
430 void clearReference()
431 {
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800432 sp<DeathRecipientList> list = mList.promote();
433 if (list != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800434 LOGDEATH("Removing JDR %p from DRL %p", this, list.get());
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800435 list->remove(this);
Christopher Tate79dd31f2011-03-04 17:45:00 -0800436 } else {
437 LOGDEATH("clearReference() on JDR %p but DRL wp purged", this);
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800438 }
Christopher Tate0b414482011-02-17 13:00:38 -0800439 }
440
441 bool matches(jobject obj) {
Christopher Tate86284c62011-08-17 15:19:29 -0700442 bool result;
Christopher Tate0b414482011-02-17 13:00:38 -0800443 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700444
445 if (mObject != NULL) {
446 result = env->IsSameObject(obj, mObject);
447 } else {
448 jobject me = env->NewLocalRef(mObjectWeak);
449 result = env->IsSameObject(obj, me);
450 env->DeleteLocalRef(me);
451 }
452 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
454
Christopher Tateac5e3502011-08-25 15:48:09 -0700455 void warnIfStillLive() {
456 if (mObject != NULL) {
457 // Okay, something is wrong -- we have a hard reference to a live death
458 // recipient on the VM side, but the list is being torn down.
459 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate0d4a7922011-08-30 12:09:43 -0700460 ScopedLocalRef<jclass> objClassRef(env, env->GetObjectClass(mObject));
461 ScopedLocalRef<jstring> nameRef(env,
462 (jstring) env->CallObjectMethod(objClassRef.get(), gClassOffsets.mGetName));
463 ScopedUtfChars nameUtf(env, nameRef.get());
464 if (nameUtf.c_str() != NULL) {
465 LOGW("BinderProxy is being destroyed but the application did not call "
466 "unlinkToDeath to unlink all of its death recipients beforehand. "
467 "Releasing leaked death recipient: %s", nameUtf.c_str());
468 } else {
469 LOGW("BinderProxy being destroyed; unable to get DR object name");
470 env->ExceptionClear();
471 }
Christopher Tateac5e3502011-08-25 15:48:09 -0700472 }
473 }
474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475protected:
476 virtual ~JavaDeathRecipient()
477 {
478 //LOGI("Removing death ref: recipient=%p\n", mObject);
479 android_atomic_dec(&gNumDeathRefs);
480 JNIEnv* env = javavm_to_jnienv(mVM);
Christopher Tate86284c62011-08-17 15:19:29 -0700481 if (mObject != NULL) {
482 env->DeleteGlobalRef(mObject);
483 } else {
484 env->DeleteWeakGlobalRef(mObjectWeak);
485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 }
487
488private:
Christopher Tate86284c62011-08-17 15:19:29 -0700489 JavaVM* const mVM;
490 jobject mObject;
491 jweak mObjectWeak; // will be a weak ref to the same VM-side DeathRecipient after binderDied()
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800492 wp<DeathRecipientList> mList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493};
494
495// ----------------------------------------------------------------------------
496
Christopher Tate79dd31f2011-03-04 17:45:00 -0800497DeathRecipientList::DeathRecipientList() {
498 LOGDEATH("New DRL @ %p", this);
499}
500
Christopher Tate0b414482011-02-17 13:00:38 -0800501DeathRecipientList::~DeathRecipientList() {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800502 LOGDEATH("Destroy DRL @ %p", this);
Christopher Tate0b414482011-02-17 13:00:38 -0800503 AutoMutex _l(mLock);
504
505 // Should never happen -- the JavaDeathRecipient objects that have added themselves
506 // to the list are holding references on the list object. Only when they are torn
507 // down can the list header be destroyed.
508 if (mList.size() > 0) {
Christopher Tateac5e3502011-08-25 15:48:09 -0700509 List< sp<JavaDeathRecipient> >::iterator iter;
510 for (iter = mList.begin(); iter != mList.end(); iter++) {
511 (*iter)->warnIfStillLive();
512 }
Christopher Tate0b414482011-02-17 13:00:38 -0800513 }
514}
515
516void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
517 AutoMutex _l(mLock);
518
Christopher Tate79dd31f2011-03-04 17:45:00 -0800519 LOGDEATH("DRL @ %p : add JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800520 mList.push_back(recipient);
521}
522
523void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
524 AutoMutex _l(mLock);
525
526 List< sp<JavaDeathRecipient> >::iterator iter;
527 for (iter = mList.begin(); iter != mList.end(); iter++) {
528 if (*iter == recipient) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800529 LOGDEATH("DRL @ %p : remove JDR %p", this, recipient.get());
Christopher Tate0b414482011-02-17 13:00:38 -0800530 mList.erase(iter);
531 return;
532 }
533 }
534}
535
536sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
537 AutoMutex _l(mLock);
538
539 List< sp<JavaDeathRecipient> >::iterator iter;
540 for (iter = mList.begin(); iter != mList.end(); iter++) {
541 if ((*iter)->matches(recipient)) {
542 return *iter;
543 }
544 }
545 return NULL;
546}
547
Christopher Tate0b414482011-02-17 13:00:38 -0800548// ----------------------------------------------------------------------------
549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550namespace android {
551
552static void proxy_cleanup(const void* id, void* obj, void* cleanupCookie)
553{
554 android_atomic_dec(&gNumProxyRefs);
555 JNIEnv* env = javavm_to_jnienv((JavaVM*)cleanupCookie);
556 env->DeleteGlobalRef((jobject)obj);
557}
558
559static Mutex mProxyLock;
560
561jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
562{
563 if (val == NULL) return NULL;
564
565 if (val->checkSubclass(&gBinderOffsets)) {
566 // One of our own!
567 jobject object = static_cast<JavaBBinder*>(val.get())->object();
Christopher Tate86284c62011-08-17 15:19:29 -0700568 LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 return object;
570 }
571
572 // For the rest of the function we will hold this lock, to serialize
573 // looking/creation of Java proxies for native Binder proxies.
574 AutoMutex _l(mProxyLock);
575
576 // Someone else's... do we know about it?
577 jobject object = (jobject)val->findObject(&gBinderProxyOffsets);
578 if (object != NULL) {
579 jobject res = env->CallObjectMethod(object, gWeakReferenceOffsets.mGet);
580 if (res != NULL) {
581 LOGV("objectForBinder %p: found existing %p!\n", val.get(), res);
582 return res;
583 }
Christopher Tate86284c62011-08-17 15:19:29 -0700584 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 -0800585 android_atomic_dec(&gNumProxyRefs);
586 val->detachObject(&gBinderProxyOffsets);
587 env->DeleteGlobalRef(object);
588 }
589
590 object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
591 if (object != NULL) {
Christopher Tate79dd31f2011-03-04 17:45:00 -0800592 LOGDEATH("objectForBinder %p: created new proxy %p !\n", val.get(), object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 // The proxy holds a reference to the native object.
594 env->SetIntField(object, gBinderProxyOffsets.mObject, (int)val.get());
595 val->incStrong(object);
596
597 // The native object needs to hold a weak reference back to the
598 // proxy, so we can retrieve the same proxy if it is still active.
599 jobject refObject = env->NewGlobalRef(
600 env->GetObjectField(object, gBinderProxyOffsets.mSelf));
601 val->attachObject(&gBinderProxyOffsets, refObject,
602 jnienv_to_javavm(env), proxy_cleanup);
603
Christopher Tatebd8b6f22011-03-01 11:55:27 -0800604 // Also remember the death recipients registered on this proxy
605 sp<DeathRecipientList> drl = new DeathRecipientList;
606 drl->incStrong((void*)javaObjectForIBinder);
607 env->SetIntField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast<jint>(drl.get()));
608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 // Note that a new object reference has been created.
610 android_atomic_inc(&gNumProxyRefs);
611 incRefsCreated(env);
612 }
613
614 return object;
615}
616
617sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
618{
619 if (obj == NULL) return NULL;
620
621 if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
622 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
623 env->GetIntField(obj, gBinderOffsets.mObject);
Christopher Tate0b414482011-02-17 13:00:38 -0800624 return jbh != NULL ? jbh->get(env, obj) : NULL;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626
627 if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
628 return (IBinder*)
629 env->GetIntField(obj, gBinderProxyOffsets.mObject);
630 }
631
632 LOGW("ibinderForJavaObject: %p is not a Binder object", obj);
633 return NULL;
634}
635
636Parcel* parcelForJavaObject(JNIEnv* env, jobject obj)
637{
638 if (obj) {
639 Parcel* p = (Parcel*)env->GetIntField(obj, gParcelOffsets.mObject);
640 if (p != NULL) {
641 return p;
642 }
643 jniThrowException(env, "java/lang/IllegalStateException", "Parcel has been finalized!");
644 }
645 return NULL;
646}
647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648jobject newParcelFileDescriptor(JNIEnv* env, jobject fileDesc)
649{
650 return env->NewObject(
651 gParcelFileDescriptorOffsets.mClass, gParcelFileDescriptorOffsets.mConstructor, fileDesc);
652}
653
654void signalExceptionForError(JNIEnv* env, jobject obj, status_t err)
655{
656 switch (err) {
657 case UNKNOWN_ERROR:
658 jniThrowException(env, "java/lang/RuntimeException", "Unknown error");
659 break;
660 case NO_MEMORY:
661 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
662 break;
663 case INVALID_OPERATION:
664 jniThrowException(env, "java/lang/UnsupportedOperationException", NULL);
665 break;
666 case BAD_VALUE:
667 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
668 break;
669 case BAD_INDEX:
670 jniThrowException(env, "java/lang/IndexOutOfBoundsException", NULL);
671 break;
672 case BAD_TYPE:
673 jniThrowException(env, "java/lang/IllegalArgumentException", NULL);
674 break;
675 case NAME_NOT_FOUND:
676 jniThrowException(env, "java/util/NoSuchElementException", NULL);
677 break;
678 case PERMISSION_DENIED:
679 jniThrowException(env, "java/lang/SecurityException", NULL);
680 break;
681 case NOT_ENOUGH_DATA:
682 jniThrowException(env, "android/os/ParcelFormatException", "Not enough data");
683 break;
684 case NO_INIT:
685 jniThrowException(env, "java/lang/RuntimeException", "Not initialized");
686 break;
687 case ALREADY_EXISTS:
688 jniThrowException(env, "java/lang/RuntimeException", "Item already exists");
689 break;
690 case DEAD_OBJECT:
691 jniThrowException(env, "android/os/DeadObjectException", NULL);
692 break;
693 case UNKNOWN_TRANSACTION:
694 jniThrowException(env, "java/lang/RuntimeException", "Unknown transaction code");
695 break;
696 case FAILED_TRANSACTION:
697 LOGE("!!! FAILED BINDER TRANSACTION !!!");
698 //jniThrowException(env, "java/lang/OutOfMemoryError", "Binder transaction too large");
699 break;
700 default:
701 LOGE("Unknown binder error code. 0x%x", err);
702 }
703}
704
705}
706
707// ----------------------------------------------------------------------------
708
709static jint android_os_Binder_getCallingPid(JNIEnv* env, jobject clazz)
710{
711 return IPCThreadState::self()->getCallingPid();
712}
713
714static jint android_os_Binder_getCallingUid(JNIEnv* env, jobject clazz)
715{
716 return IPCThreadState::self()->getCallingUid();
717}
718
719static jlong android_os_Binder_clearCallingIdentity(JNIEnv* env, jobject clazz)
720{
721 return IPCThreadState::self()->clearCallingIdentity();
722}
723
724static void android_os_Binder_restoreCallingIdentity(JNIEnv* env, jobject clazz, jlong token)
725{
Dianne Hackborncf3004a2011-03-14 14:24:04 -0700726 // XXX temporary sanity check to debug crashes.
727 int uid = (int)(token>>32);
728 if (uid > 0 && uid < 999) {
729 // In Android currently there are no uids in this range.
730 char buf[128];
731 sprintf(buf, "Restoring bad calling ident: 0x%Lx", token);
732 jniThrowException(env, "java/lang/IllegalStateException", buf);
733 return;
734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 IPCThreadState::self()->restoreCallingIdentity(token);
736}
737
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700738static void android_os_Binder_setThreadStrictModePolicy(JNIEnv* env, jobject clazz, jint policyMask)
739{
740 IPCThreadState::self()->setStrictModePolicy(policyMask);
741}
742
743static jint android_os_Binder_getThreadStrictModePolicy(JNIEnv* env, jobject clazz)
744{
745 return IPCThreadState::self()->getStrictModePolicy();
746}
747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748static void android_os_Binder_flushPendingCommands(JNIEnv* env, jobject clazz)
749{
750 IPCThreadState::self()->flushCommands();
751}
752
Christopher Tate0b414482011-02-17 13:00:38 -0800753static void android_os_Binder_init(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754{
Christopher Tate0b414482011-02-17 13:00:38 -0800755 JavaBBinderHolder* jbh = new JavaBBinderHolder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 if (jbh == NULL) {
757 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
758 return;
759 }
Christopher Tate0b414482011-02-17 13:00:38 -0800760 LOGV("Java Binder %p: acquiring first ref on holder %p", obj, jbh);
761 jbh->incStrong((void*)android_os_Binder_init);
762 env->SetIntField(obj, gBinderOffsets.mObject, (int)jbh);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763}
764
Christopher Tate0b414482011-02-17 13:00:38 -0800765static void android_os_Binder_destroy(JNIEnv* env, jobject obj)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766{
767 JavaBBinderHolder* jbh = (JavaBBinderHolder*)
Christopher Tate0b414482011-02-17 13:00:38 -0800768 env->GetIntField(obj, gBinderOffsets.mObject);
Jeff Brown582763a2010-03-24 18:56:57 -0700769 if (jbh != NULL) {
Christopher Tate0b414482011-02-17 13:00:38 -0800770 env->SetIntField(obj, gBinderOffsets.mObject, 0);
771 LOGV("Java Binder %p: removing ref on holder %p", obj, jbh);
772 jbh->decStrong((void*)android_os_Binder_init);
Jeff Brown582763a2010-03-24 18:56:57 -0700773 } else {
774 // Encountering an uninitialized binder is harmless. All it means is that
775 // the Binder was only partially initialized when its finalizer ran and called
776 // destroy(). The Binder could be partially initialized for several reasons.
777 // For example, a Binder subclass constructor might have thrown an exception before
778 // it could delegate to its superclass's constructor. Consequently init() would
779 // not have been called and the holder pointer would remain NULL.
Christopher Tate0b414482011-02-17 13:00:38 -0800780 LOGV("Java Binder %p: ignoring uninitialized binder", obj);
Jeff Brown582763a2010-03-24 18:56:57 -0700781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782}
783
784// ----------------------------------------------------------------------------
785
786static const JNINativeMethod gBinderMethods[] = {
787 /* name, signature, funcPtr */
788 { "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
789 { "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
790 { "clearCallingIdentity", "()J", (void*)android_os_Binder_clearCallingIdentity },
791 { "restoreCallingIdentity", "(J)V", (void*)android_os_Binder_restoreCallingIdentity },
Brad Fitzpatrick727de402010-07-07 16:06:39 -0700792 { "setThreadStrictModePolicy", "(I)V", (void*)android_os_Binder_setThreadStrictModePolicy },
793 { "getThreadStrictModePolicy", "()I", (void*)android_os_Binder_getThreadStrictModePolicy },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 { "flushPendingCommands", "()V", (void*)android_os_Binder_flushPendingCommands },
795 { "init", "()V", (void*)android_os_Binder_init },
796 { "destroy", "()V", (void*)android_os_Binder_destroy }
797};
798
799const char* const kBinderPathName = "android/os/Binder";
800
801static int int_register_android_os_Binder(JNIEnv* env)
802{
803 jclass clazz;
804
805 clazz = env->FindClass(kBinderPathName);
806 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Binder");
807
808 gBinderOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
809 gBinderOffsets.mExecTransact
810 = env->GetMethodID(clazz, "execTransact", "(IIII)Z");
811 assert(gBinderOffsets.mExecTransact);
812
813 gBinderOffsets.mObject
814 = env->GetFieldID(clazz, "mObject", "I");
815 assert(gBinderOffsets.mObject);
816
817 return AndroidRuntime::registerNativeMethods(
818 env, kBinderPathName,
819 gBinderMethods, NELEM(gBinderMethods));
820}
821
822// ****************************************************************************
823// ****************************************************************************
824// ****************************************************************************
825
826namespace android {
827
828jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz)
829{
830 return gNumLocalRefs;
831}
832
833jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz)
834{
835 return gNumProxyRefs;
836}
837
838jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz)
839{
840 return gNumDeathRefs;
841}
842
843}
844
845// ****************************************************************************
846// ****************************************************************************
847// ****************************************************************************
848
849static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
850{
851 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
852 return javaObjectForIBinder(env, b);
853}
854
855static void android_os_BinderInternal_joinThreadPool(JNIEnv* env, jobject clazz)
856{
857 sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
858 android::IPCThreadState::self()->joinThreadPool();
859}
860
Dianne Hackborn887f3552009-12-07 17:59:37 -0800861static void android_os_BinderInternal_disableBackgroundScheduling(JNIEnv* env,
862 jobject clazz, jboolean disable)
863{
864 IPCThreadState::disableBackgroundScheduling(disable ? true : false);
865}
866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867static void android_os_BinderInternal_handleGc(JNIEnv* env, jobject clazz)
868{
869 LOGV("Gc has executed, clearing binder ops");
870 android_atomic_and(0, &gNumRefsCreated);
871}
872
873// ----------------------------------------------------------------------------
874
875static const JNINativeMethod gBinderInternalMethods[] = {
876 /* name, signature, funcPtr */
877 { "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
878 { "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
Dianne Hackborn887f3552009-12-07 17:59:37 -0800879 { "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 { "handleGc", "()V", (void*)android_os_BinderInternal_handleGc }
881};
882
883const char* const kBinderInternalPathName = "com/android/internal/os/BinderInternal";
884
885static int int_register_android_os_BinderInternal(JNIEnv* env)
886{
887 jclass clazz;
888
889 clazz = env->FindClass(kBinderInternalPathName);
890 LOG_FATAL_IF(clazz == NULL, "Unable to find class com.android.internal.os.BinderInternal");
891
892 gBinderInternalOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
893 gBinderInternalOffsets.mForceGc
894 = env->GetStaticMethodID(clazz, "forceBinderGc", "()V");
895 assert(gBinderInternalOffsets.mForceGc);
896
897 return AndroidRuntime::registerNativeMethods(
898 env, kBinderInternalPathName,
899 gBinderInternalMethods, NELEM(gBinderInternalMethods));
900}
901
902// ****************************************************************************
903// ****************************************************************************
904// ****************************************************************************
905
906static jboolean android_os_BinderProxy_pingBinder(JNIEnv* env, jobject obj)
907{
908 IBinder* target = (IBinder*)
909 env->GetIntField(obj, gBinderProxyOffsets.mObject);
910 if (target == NULL) {
911 return JNI_FALSE;
912 }
913 status_t err = target->pingBinder();
914 return err == NO_ERROR ? JNI_TRUE : JNI_FALSE;
915}
916
917static jstring android_os_BinderProxy_getInterfaceDescriptor(JNIEnv* env, jobject obj)
918{
919 IBinder* target = (IBinder*) env->GetIntField(obj, gBinderProxyOffsets.mObject);
920 if (target != NULL) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700921 const String16& desc = target->getInterfaceDescriptor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 return env->NewString(desc.string(), desc.size());
923 }
924 jniThrowException(env, "java/lang/RuntimeException",
925 "No binder found for object");
926 return NULL;
927}
928
929static jboolean android_os_BinderProxy_isBinderAlive(JNIEnv* env, jobject obj)
930{
931 IBinder* target = (IBinder*)
932 env->GetIntField(obj, gBinderProxyOffsets.mObject);
933 if (target == NULL) {
934 return JNI_FALSE;
935 }
936 bool alive = target->isBinderAlive();
937 return alive ? JNI_TRUE : JNI_FALSE;
938}
939
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -0700940static int getprocname(pid_t pid, char *buf, size_t len) {
941 char filename[20];
942 FILE *f;
943
944 sprintf(filename, "/proc/%d/cmdline", pid);
945 f = fopen(filename, "r");
946 if (!f) { *buf = '\0'; return 1; }
947 if (!fgets(buf, len, f)) { *buf = '\0'; return 2; }
948 fclose(f);
949 return 0;
950}
951
952static bool push_eventlog_string(char** pos, const char* end, const char* str) {
953 jint len = strlen(str);
954 int space_needed = 1 + sizeof(len) + len;
955 if (end - *pos < space_needed) {
956 LOGW("not enough space for string. remain=%d; needed=%d",
957 (end - *pos), space_needed);
958 return false;
959 }
960 **pos = EVENT_TYPE_STRING;
961 (*pos)++;
962 memcpy(*pos, &len, sizeof(len));
963 *pos += sizeof(len);
964 memcpy(*pos, str, len);
965 *pos += len;
966 return true;
967}
968
969static bool push_eventlog_int(char** pos, const char* end, jint val) {
970 int space_needed = 1 + sizeof(val);
971 if (end - *pos < space_needed) {
972 LOGW("not enough space for int. remain=%d; needed=%d",
973 (end - *pos), space_needed);
974 return false;
975 }
976 **pos = EVENT_TYPE_INT;
977 (*pos)++;
978 memcpy(*pos, &val, sizeof(val));
979 *pos += sizeof(val);
980 return true;
981}
982
983// From frameworks/base/core/java/android/content/EventLogTags.logtags:
984#define LOGTAG_BINDER_OPERATION 52004
985
986static void conditionally_log_binder_call(int64_t start_millis,
987 IBinder* target, jint code) {
988 int duration_ms = static_cast<int>(uptimeMillis() - start_millis);
989
990 int sample_percent;
991 if (duration_ms >= 500) {
992 sample_percent = 100;
993 } else {
994 sample_percent = 100 * duration_ms / 500;
995 if (sample_percent == 0) {
996 return;
997 }
998 if (sample_percent < (random() % 100 + 1)) {
999 return;
1000 }
1001 }
1002
1003 char process_name[40];
1004 getprocname(getpid(), process_name, sizeof(process_name));
1005 String8 desc(target->getInterfaceDescriptor());
1006
1007 char buf[LOGGER_ENTRY_MAX_PAYLOAD];
1008 buf[0] = EVENT_TYPE_LIST;
1009 buf[1] = 5;
1010 char* pos = &buf[2];
1011 char* end = &buf[LOGGER_ENTRY_MAX_PAYLOAD - 1]; // leave room for final \n
1012 if (!push_eventlog_string(&pos, end, desc.string())) return;
1013 if (!push_eventlog_int(&pos, end, code)) return;
1014 if (!push_eventlog_int(&pos, end, duration_ms)) return;
1015 if (!push_eventlog_string(&pos, end, process_name)) return;
1016 if (!push_eventlog_int(&pos, end, sample_percent)) return;
1017 *(pos++) = '\n'; // conventional with EVENT_TYPE_LIST apparently.
1018 android_bWriteLog(LOGTAG_BINDER_OPERATION, buf, pos - buf);
1019}
1020
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001021// We only measure binder call durations to potentially log them if
1022// we're on the main thread. Unfortunately sim-eng doesn't seem to
1023// have gettid, so we just ignore this and don't log if we can't
1024// get the thread id.
1025static bool should_time_binder_calls() {
Brad Fitzpatrick5348c012010-03-25 12:43:56 -07001026#ifdef HAVE_GETTID
1027 return (getpid() == androidGetTid());
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001028#else
1029#warning no gettid(), so not logging Binder calls...
1030 return false;
1031#endif
1032}
1033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
1035 jint code, jobject dataObj,
1036 jobject replyObj, jint flags)
1037{
1038 if (dataObj == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001039 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 return JNI_FALSE;
1041 }
1042
1043 Parcel* data = parcelForJavaObject(env, dataObj);
1044 if (data == NULL) {
1045 return JNI_FALSE;
1046 }
1047 Parcel* reply = parcelForJavaObject(env, replyObj);
1048 if (reply == NULL && replyObj != NULL) {
1049 return JNI_FALSE;
1050 }
1051
1052 IBinder* target = (IBinder*)
1053 env->GetIntField(obj, gBinderProxyOffsets.mObject);
1054 if (target == NULL) {
1055 jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
1056 return JNI_FALSE;
1057 }
1058
1059 LOGV("Java code calling transact on %p in Java object %p with code %d\n",
1060 target, obj, code);
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001061
1062 // Only log the binder call duration for things on the Java-level main thread.
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001063 // But if we don't
1064 const bool time_binder_calls = should_time_binder_calls();
1065
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001066 int64_t start_millis;
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001067 if (time_binder_calls) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001068 start_millis = uptimeMillis();
1069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 //printf("Transact from Java code to %p sending: ", target); data->print();
1071 status_t err = target->transact(code, *data, reply, flags);
1072 //if (reply) printf("Transact from Java code to %p received: ", target); reply->print();
Brad Fitzpatrickad8fd282010-03-25 02:01:32 -07001073 if (time_binder_calls) {
Brad Fitzpatrick2c5da312010-03-24 16:14:09 -07001074 conditionally_log_binder_call(start_millis, target, code);
1075 }
1076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 if (err == NO_ERROR) {
1078 return JNI_TRUE;
1079 } else if (err == UNKNOWN_TRANSACTION) {
1080 return JNI_FALSE;
1081 }
1082
1083 signalExceptionForError(env, obj, err);
1084 return JNI_FALSE;
1085}
1086
1087static void android_os_BinderProxy_linkToDeath(JNIEnv* env, jobject obj,
1088 jobject recipient, jint flags)
1089{
1090 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001091 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 return;
1093 }
1094
1095 IBinder* target = (IBinder*)
1096 env->GetIntField(obj, gBinderProxyOffsets.mObject);
1097 if (target == NULL) {
1098 LOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
1099 assert(false);
1100 }
1101
Christopher Tate79dd31f2011-03-04 17:45:00 -08001102 LOGDEATH("linkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103
1104 if (!target->localBinder()) {
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001105 DeathRecipientList* list = (DeathRecipientList*)
1106 env->GetIntField(obj, gBinderProxyOffsets.mOrgue);
1107 sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient, list);
Christopher Tate0b414482011-02-17 13:00:38 -08001108 status_t err = target->linkToDeath(jdr, NULL, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 if (err != NO_ERROR) {
1110 // Failure adding the death recipient, so clear its reference
1111 // now.
1112 jdr->clearReference();
1113 signalExceptionForError(env, obj, err);
1114 }
1115 }
1116}
1117
1118static jboolean android_os_BinderProxy_unlinkToDeath(JNIEnv* env, jobject obj,
1119 jobject recipient, jint flags)
1120{
1121 jboolean res = JNI_FALSE;
1122 if (recipient == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001123 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 return res;
1125 }
1126
1127 IBinder* target = (IBinder*)
1128 env->GetIntField(obj, gBinderProxyOffsets.mObject);
1129 if (target == NULL) {
1130 LOGW("Binder has been finalized when calling linkToDeath() with recip=%p)\n", recipient);
1131 return JNI_FALSE;
1132 }
1133
Christopher Tate79dd31f2011-03-04 17:45:00 -08001134 LOGDEATH("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135
1136 if (!target->localBinder()) {
Christopher Tate0b414482011-02-17 13:00:38 -08001137 status_t err = NAME_NOT_FOUND;
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001138
1139 // If we find the matching recipient, proceed to unlink using that
1140 DeathRecipientList* list = (DeathRecipientList*)
1141 env->GetIntField(obj, gBinderProxyOffsets.mOrgue);
1142 sp<JavaDeathRecipient> origJDR = list->find(recipient);
Christopher Tate79dd31f2011-03-04 17:45:00 -08001143 LOGDEATH(" unlink found list %p and JDR %p", list, origJDR.get());
Christopher Tate0b414482011-02-17 13:00:38 -08001144 if (origJDR != NULL) {
1145 wp<IBinder::DeathRecipient> dr;
1146 err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
1147 if (err == NO_ERROR && dr != NULL) {
1148 sp<IBinder::DeathRecipient> sdr = dr.promote();
1149 JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
1150 if (jdr != NULL) {
1151 jdr->clearReference();
1152 }
1153 }
1154 }
1155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 if (err == NO_ERROR || err == DEAD_OBJECT) {
1157 res = JNI_TRUE;
1158 } else {
1159 jniThrowException(env, "java/util/NoSuchElementException",
1160 "Death link does not exist");
1161 }
1162 }
1163
1164 return res;
1165}
1166
1167static void android_os_BinderProxy_destroy(JNIEnv* env, jobject obj)
1168{
1169 IBinder* b = (IBinder*)
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001170 env->GetIntField(obj, gBinderProxyOffsets.mObject);
1171 DeathRecipientList* drl = (DeathRecipientList*)
1172 env->GetIntField(obj, gBinderProxyOffsets.mOrgue);
Christopher Tate0b414482011-02-17 13:00:38 -08001173
Christopher Tate79dd31f2011-03-04 17:45:00 -08001174 LOGDEATH("Destroying BinderProxy %p: binder=%p drl=%p\n", obj, b, drl);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001175 env->SetIntField(obj, gBinderProxyOffsets.mObject, 0);
1176 env->SetIntField(obj, gBinderProxyOffsets.mOrgue, 0);
1177 drl->decStrong((void*)javaObjectForIBinder);
1178 b->decStrong(obj);
1179
1180 IPCThreadState::self()->flushCommands();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181}
1182
1183// ----------------------------------------------------------------------------
1184
1185static const JNINativeMethod gBinderProxyMethods[] = {
1186 /* name, signature, funcPtr */
1187 {"pingBinder", "()Z", (void*)android_os_BinderProxy_pingBinder},
1188 {"isBinderAlive", "()Z", (void*)android_os_BinderProxy_isBinderAlive},
1189 {"getInterfaceDescriptor", "()Ljava/lang/String;", (void*)android_os_BinderProxy_getInterfaceDescriptor},
1190 {"transact", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},
1191 {"linkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)V", (void*)android_os_BinderProxy_linkToDeath},
1192 {"unlinkToDeath", "(Landroid/os/IBinder$DeathRecipient;I)Z", (void*)android_os_BinderProxy_unlinkToDeath},
1193 {"destroy", "()V", (void*)android_os_BinderProxy_destroy},
1194};
1195
1196const char* const kBinderProxyPathName = "android/os/BinderProxy";
1197
1198static int int_register_android_os_BinderProxy(JNIEnv* env)
1199{
1200 jclass clazz;
1201
1202 clazz = env->FindClass("java/lang/ref/WeakReference");
1203 LOG_FATAL_IF(clazz == NULL, "Unable to find class java.lang.ref.WeakReference");
1204 gWeakReferenceOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1205 gWeakReferenceOffsets.mGet
1206 = env->GetMethodID(clazz, "get", "()Ljava/lang/Object;");
1207 assert(gWeakReferenceOffsets.mGet);
1208
1209 clazz = env->FindClass("java/lang/Error");
1210 LOG_FATAL_IF(clazz == NULL, "Unable to find class java.lang.Error");
1211 gErrorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
Elliott Hughes69a017b2011-04-08 14:10:28 -07001212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 clazz = env->FindClass(kBinderProxyPathName);
1214 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.BinderProxy");
1215
1216 gBinderProxyOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1217 gBinderProxyOffsets.mConstructor
1218 = env->GetMethodID(clazz, "<init>", "()V");
1219 assert(gBinderProxyOffsets.mConstructor);
1220 gBinderProxyOffsets.mSendDeathNotice
1221 = env->GetStaticMethodID(clazz, "sendDeathNotice", "(Landroid/os/IBinder$DeathRecipient;)V");
1222 assert(gBinderProxyOffsets.mSendDeathNotice);
1223
1224 gBinderProxyOffsets.mObject
1225 = env->GetFieldID(clazz, "mObject", "I");
1226 assert(gBinderProxyOffsets.mObject);
1227 gBinderProxyOffsets.mSelf
1228 = env->GetFieldID(clazz, "mSelf", "Ljava/lang/ref/WeakReference;");
1229 assert(gBinderProxyOffsets.mSelf);
Christopher Tatebd8b6f22011-03-01 11:55:27 -08001230 gBinderProxyOffsets.mOrgue
1231 = env->GetFieldID(clazz, "mOrgue", "I");
1232 assert(gBinderProxyOffsets.mOrgue);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233
Christopher Tate0d4a7922011-08-30 12:09:43 -07001234 clazz = env->FindClass("java/lang/Class");
1235 LOG_FATAL_IF(clazz == NULL, "Unable to find java.lang.Class");
1236 gClassOffsets.mGetName = env->GetMethodID(clazz, "getName", "()Ljava/lang/String;");
1237 assert(gClassOffsets.mGetName);
1238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 return AndroidRuntime::registerNativeMethods(
1240 env, kBinderProxyPathName,
1241 gBinderProxyMethods, NELEM(gBinderProxyMethods));
1242}
1243
1244// ****************************************************************************
1245// ****************************************************************************
1246// ****************************************************************************
1247
1248static jint android_os_Parcel_dataSize(JNIEnv* env, jobject clazz)
1249{
1250 Parcel* parcel = parcelForJavaObject(env, clazz);
1251 return parcel ? parcel->dataSize() : 0;
1252}
1253
1254static jint android_os_Parcel_dataAvail(JNIEnv* env, jobject clazz)
1255{
1256 Parcel* parcel = parcelForJavaObject(env, clazz);
1257 return parcel ? parcel->dataAvail() : 0;
1258}
1259
1260static jint android_os_Parcel_dataPosition(JNIEnv* env, jobject clazz)
1261{
1262 Parcel* parcel = parcelForJavaObject(env, clazz);
1263 return parcel ? parcel->dataPosition() : 0;
1264}
1265
1266static jint android_os_Parcel_dataCapacity(JNIEnv* env, jobject clazz)
1267{
1268 Parcel* parcel = parcelForJavaObject(env, clazz);
1269 return parcel ? parcel->dataCapacity() : 0;
1270}
1271
1272static void android_os_Parcel_setDataSize(JNIEnv* env, jobject clazz, jint size)
1273{
1274 Parcel* parcel = parcelForJavaObject(env, clazz);
1275 if (parcel != NULL) {
1276 const status_t err = parcel->setDataSize(size);
1277 if (err != NO_ERROR) {
1278 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1279 }
1280 }
1281}
1282
1283static void android_os_Parcel_setDataPosition(JNIEnv* env, jobject clazz, jint pos)
1284{
1285 Parcel* parcel = parcelForJavaObject(env, clazz);
1286 if (parcel != NULL) {
1287 parcel->setDataPosition(pos);
1288 }
1289}
1290
1291static void android_os_Parcel_setDataCapacity(JNIEnv* env, jobject clazz, jint size)
1292{
1293 Parcel* parcel = parcelForJavaObject(env, clazz);
1294 if (parcel != NULL) {
1295 const status_t err = parcel->setDataCapacity(size);
1296 if (err != NO_ERROR) {
1297 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1298 }
1299 }
1300}
1301
1302static void android_os_Parcel_writeNative(JNIEnv* env, jobject clazz,
1303 jobject data, jint offset,
1304 jint length)
1305{
1306 Parcel* parcel = parcelForJavaObject(env, clazz);
1307 if (parcel == NULL) {
1308 return;
1309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310
1311 const status_t err = parcel->writeInt32(length);
1312 if (err != NO_ERROR) {
1313 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1314 }
1315
Elliott Hughesa28b83e2011-02-28 14:26:13 -08001316 void* dest = parcel->writeInplace(length);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 if (dest == NULL) {
1318 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1319 return;
1320 }
1321
1322 jbyte* ar = (jbyte*)env->GetPrimitiveArrayCritical((jarray)data, 0);
1323 if (ar) {
Elliott Hughesa28b83e2011-02-28 14:26:13 -08001324 memcpy(dest, ar + offset, length);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 env->ReleasePrimitiveArrayCritical((jarray)data, ar, 0);
1326 }
1327}
1328
1329
1330static void android_os_Parcel_writeInt(JNIEnv* env, jobject clazz, jint val)
1331{
1332 Parcel* parcel = parcelForJavaObject(env, clazz);
1333 if (parcel != NULL) {
1334 const status_t err = parcel->writeInt32(val);
1335 if (err != NO_ERROR) {
1336 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1337 }
1338 }
1339}
1340
1341static void android_os_Parcel_writeLong(JNIEnv* env, jobject clazz, jlong val)
1342{
1343 Parcel* parcel = parcelForJavaObject(env, clazz);
1344 if (parcel != NULL) {
1345 const status_t err = parcel->writeInt64(val);
1346 if (err != NO_ERROR) {
1347 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1348 }
1349 }
1350}
1351
1352static void android_os_Parcel_writeFloat(JNIEnv* env, jobject clazz, jfloat val)
1353{
1354 Parcel* parcel = parcelForJavaObject(env, clazz);
1355 if (parcel != NULL) {
1356 const status_t err = parcel->writeFloat(val);
1357 if (err != NO_ERROR) {
1358 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1359 }
1360 }
1361}
1362
1363static void android_os_Parcel_writeDouble(JNIEnv* env, jobject clazz, jdouble val)
1364{
1365 Parcel* parcel = parcelForJavaObject(env, clazz);
1366 if (parcel != NULL) {
1367 const status_t err = parcel->writeDouble(val);
1368 if (err != NO_ERROR) {
1369 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1370 }
1371 }
1372}
1373
1374static void android_os_Parcel_writeString(JNIEnv* env, jobject clazz, jstring val)
1375{
1376 Parcel* parcel = parcelForJavaObject(env, clazz);
1377 if (parcel != NULL) {
1378 status_t err = NO_MEMORY;
1379 if (val) {
1380 const jchar* str = env->GetStringCritical(val, 0);
1381 if (str) {
1382 err = parcel->writeString16(str, env->GetStringLength(val));
1383 env->ReleaseStringCritical(val, str);
1384 }
1385 } else {
1386 err = parcel->writeString16(NULL, 0);
1387 }
1388 if (err != NO_ERROR) {
1389 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1390 }
1391 }
1392}
1393
1394static void android_os_Parcel_writeStrongBinder(JNIEnv* env, jobject clazz, jobject object)
1395{
1396 Parcel* parcel = parcelForJavaObject(env, clazz);
1397 if (parcel != NULL) {
1398 const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object));
1399 if (err != NO_ERROR) {
1400 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1401 }
1402 }
1403}
1404
1405static void android_os_Parcel_writeFileDescriptor(JNIEnv* env, jobject clazz, jobject object)
1406{
1407 Parcel* parcel = parcelForJavaObject(env, clazz);
1408 if (parcel != NULL) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001409 const status_t err =
1410 parcel->writeDupFileDescriptor(jniGetFDFromFileDescriptor(env, object));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 if (err != NO_ERROR) {
1412 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1413 }
1414 }
1415}
1416
1417static jbyteArray android_os_Parcel_createByteArray(JNIEnv* env, jobject clazz)
1418{
1419 jbyteArray ret = NULL;
1420
1421 Parcel* parcel = parcelForJavaObject(env, clazz);
1422 if (parcel != NULL) {
1423 int32_t len = parcel->readInt32();
1424
1425 // sanity check the stored length against the true data size
1426 if (len >= 0 && len <= (int32_t)parcel->dataAvail()) {
1427 ret = env->NewByteArray(len);
1428
1429 if (ret != NULL) {
1430 jbyte* a2 = (jbyte*)env->GetPrimitiveArrayCritical(ret, 0);
1431 if (a2) {
1432 const void* data = parcel->readInplace(len);
1433 memcpy(a2, data, len);
1434 env->ReleasePrimitiveArrayCritical(ret, a2, 0);
1435 }
1436 }
1437 }
1438 }
1439
1440 return ret;
1441}
1442
1443static jint android_os_Parcel_readInt(JNIEnv* env, jobject clazz)
1444{
1445 Parcel* parcel = parcelForJavaObject(env, clazz);
1446 if (parcel != NULL) {
1447 return parcel->readInt32();
1448 }
1449 return 0;
1450}
1451
1452static jlong android_os_Parcel_readLong(JNIEnv* env, jobject clazz)
1453{
1454 Parcel* parcel = parcelForJavaObject(env, clazz);
1455 if (parcel != NULL) {
1456 return parcel->readInt64();
1457 }
1458 return 0;
1459}
1460
1461static jfloat android_os_Parcel_readFloat(JNIEnv* env, jobject clazz)
1462{
1463 Parcel* parcel = parcelForJavaObject(env, clazz);
1464 if (parcel != NULL) {
1465 return parcel->readFloat();
1466 }
1467 return 0;
1468}
1469
1470static jdouble android_os_Parcel_readDouble(JNIEnv* env, jobject clazz)
1471{
1472 Parcel* parcel = parcelForJavaObject(env, clazz);
1473 if (parcel != NULL) {
1474 return parcel->readDouble();
1475 }
1476 return 0;
1477}
1478
1479static jstring android_os_Parcel_readString(JNIEnv* env, jobject clazz)
1480{
1481 Parcel* parcel = parcelForJavaObject(env, clazz);
1482 if (parcel != NULL) {
1483 size_t len;
1484 const char16_t* str = parcel->readString16Inplace(&len);
1485 if (str) {
1486 return env->NewString(str, len);
1487 }
1488 return NULL;
1489 }
1490 return NULL;
1491}
1492
1493static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jobject clazz)
1494{
1495 Parcel* parcel = parcelForJavaObject(env, clazz);
1496 if (parcel != NULL) {
1497 return javaObjectForIBinder(env, parcel->readStrongBinder());
1498 }
1499 return NULL;
1500}
1501
1502static jobject android_os_Parcel_readFileDescriptor(JNIEnv* env, jobject clazz)
1503{
1504 Parcel* parcel = parcelForJavaObject(env, clazz);
1505 if (parcel != NULL) {
1506 int fd = parcel->readFileDescriptor();
1507 if (fd < 0) return NULL;
1508 fd = dup(fd);
1509 if (fd < 0) return NULL;
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001510 return jniCreateFileDescriptor(env, fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 return NULL;
1513}
1514
1515static jobject android_os_Parcel_openFileDescriptor(JNIEnv* env, jobject clazz,
1516 jstring name, jint mode)
1517{
1518 if (name == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001519 jniThrowNullPointerException(env, NULL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 return NULL;
1521 }
1522 const jchar* str = env->GetStringCritical(name, 0);
1523 if (str == NULL) {
1524 // Whatever, whatever.
1525 jniThrowException(env, "java/lang/IllegalStateException", NULL);
1526 return NULL;
1527 }
1528 String8 name8(str, env->GetStringLength(name));
1529 env->ReleaseStringCritical(name, str);
1530 int flags=0;
1531 switch (mode&0x30000000) {
1532 case 0:
1533 case 0x10000000:
1534 flags = O_RDONLY;
1535 break;
1536 case 0x20000000:
1537 flags = O_WRONLY;
1538 break;
1539 case 0x30000000:
1540 flags = O_RDWR;
1541 break;
1542 }
1543
1544 if (mode&0x08000000) flags |= O_CREAT;
1545 if (mode&0x04000000) flags |= O_TRUNC;
1546 if (mode&0x02000000) flags |= O_APPEND;
1547
1548 int realMode = S_IRWXU|S_IRWXG;
1549 if (mode&0x00000001) realMode |= S_IROTH;
1550 if (mode&0x00000002) realMode |= S_IWOTH;
1551
1552 int fd = open(name8.string(), flags, realMode);
1553 if (fd < 0) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001554 jniThrowException(env, "java/io/FileNotFoundException", strerror(errno));
1555 return NULL;
1556 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001557 jobject object = jniCreateFileDescriptor(env, fd);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001558 if (object == NULL) {
1559 close(fd);
1560 }
1561 return object;
1562}
1563
1564static jobject android_os_Parcel_dupFileDescriptor(JNIEnv* env, jobject clazz, jobject orig)
1565{
1566 if (orig == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001567 jniThrowNullPointerException(env, NULL);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001568 return NULL;
1569 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001570 int origfd = jniGetFDFromFileDescriptor(env, orig);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001571 if (origfd < 0) {
1572 jniThrowException(env, "java/lang/IllegalArgumentException", "bad FileDescriptor");
1573 return NULL;
1574 }
1575
1576 int fd = dup(origfd);
1577 if (fd < 0) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001578 jniThrowIOException(env, errno);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 return NULL;
1580 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001581 jobject object = jniCreateFileDescriptor(env, fd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 if (object == NULL) {
1583 close(fd);
1584 }
1585 return object;
1586}
1587
1588static void android_os_Parcel_closeFileDescriptor(JNIEnv* env, jobject clazz, jobject object)
1589{
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001590 if (object == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001591 jniThrowNullPointerException(env, NULL);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001592 return;
1593 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001594 int fd = jniGetFDFromFileDescriptor(env, object);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if (fd >= 0) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001596 jniSetFileDescriptorOfFD(env, object, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 //LOGI("Closing ParcelFileDescriptor %d\n", fd);
1598 close(fd);
1599 }
1600}
1601
Dianne Hackbornc9119f52011-02-28 18:03:26 -08001602static void android_os_Parcel_clearFileDescriptor(JNIEnv* env, jobject clazz, jobject object)
1603{
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001604 if (object == NULL) {
Elliott Hughes69a017b2011-04-08 14:10:28 -07001605 jniThrowNullPointerException(env, NULL);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001606 return;
1607 }
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001608 int fd = jniGetFDFromFileDescriptor(env, object);
Dianne Hackbornc9119f52011-02-28 18:03:26 -08001609 if (fd >= 0) {
Elliott Hughesa3804cf2011-04-11 16:50:19 -07001610 jniSetFileDescriptorOfFD(env, object, -1);
Dianne Hackbornc9119f52011-02-28 18:03:26 -08001611 }
1612}
1613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614static void android_os_Parcel_freeBuffer(JNIEnv* env, jobject clazz)
1615{
1616 int32_t own = env->GetIntField(clazz, gParcelOffsets.mOwnObject);
1617 if (own) {
1618 Parcel* parcel = parcelForJavaObject(env, clazz);
1619 if (parcel != NULL) {
1620 //LOGI("Parcel.freeBuffer() called for C++ Parcel %p\n", parcel);
1621 parcel->freeData();
1622 }
1623 }
1624}
1625
1626static void android_os_Parcel_init(JNIEnv* env, jobject clazz, jint parcelInt)
1627{
1628 Parcel* parcel = (Parcel*)parcelInt;
1629 int own = 0;
1630 if (!parcel) {
1631 //LOGI("Initializing obj %p: creating new Parcel\n", clazz);
1632 own = 1;
1633 parcel = new Parcel;
1634 } else {
1635 //LOGI("Initializing obj %p: given existing Parcel %p\n", clazz, parcel);
1636 }
1637 if (parcel == NULL) {
1638 jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
1639 return;
1640 }
1641 //LOGI("Initializing obj %p from C++ Parcel %p, own=%d\n", clazz, parcel, own);
1642 env->SetIntField(clazz, gParcelOffsets.mOwnObject, own);
1643 env->SetIntField(clazz, gParcelOffsets.mObject, (int)parcel);
1644}
1645
1646static void android_os_Parcel_destroy(JNIEnv* env, jobject clazz)
1647{
1648 int32_t own = env->GetIntField(clazz, gParcelOffsets.mOwnObject);
1649 if (own) {
1650 Parcel* parcel = parcelForJavaObject(env, clazz);
1651 env->SetIntField(clazz, gParcelOffsets.mObject, 0);
1652 //LOGI("Destroying obj %p: deleting C++ Parcel %p\n", clazz, parcel);
1653 delete parcel;
1654 } else {
1655 env->SetIntField(clazz, gParcelOffsets.mObject, 0);
1656 //LOGI("Destroying obj %p: leaving C++ Parcel %p\n", clazz);
1657 }
1658}
1659
1660static jbyteArray android_os_Parcel_marshall(JNIEnv* env, jobject clazz)
1661{
1662 Parcel* parcel = parcelForJavaObject(env, clazz);
1663 if (parcel == NULL) {
1664 return NULL;
1665 }
1666
1667 // do not marshall if there are binder objects in the parcel
1668 if (parcel->objectsCount())
1669 {
1670 jniThrowException(env, "java/lang/RuntimeException", "Tried to marshall a Parcel that contained Binder objects.");
1671 return NULL;
1672 }
1673
1674 jbyteArray ret = env->NewByteArray(parcel->dataSize());
1675
1676 if (ret != NULL)
1677 {
1678 jbyte* array = (jbyte*)env->GetPrimitiveArrayCritical(ret, 0);
1679 if (array != NULL)
1680 {
1681 memcpy(array, parcel->data(), parcel->dataSize());
1682 env->ReleasePrimitiveArrayCritical(ret, array, 0);
1683 }
1684 }
1685
1686 return ret;
1687}
1688
1689static void android_os_Parcel_unmarshall(JNIEnv* env, jobject clazz, jbyteArray data, jint offset, jint length)
1690{
1691 Parcel* parcel = parcelForJavaObject(env, clazz);
1692 if (parcel == NULL || length < 0) {
1693 return;
1694 }
1695
1696 jbyte* array = (jbyte*)env->GetPrimitiveArrayCritical(data, 0);
1697 if (array)
1698 {
1699 parcel->setDataSize(length);
1700 parcel->setDataPosition(0);
1701
1702 void* raw = parcel->writeInplace(length);
1703 memcpy(raw, (array + offset), length);
1704
1705 env->ReleasePrimitiveArrayCritical(data, array, 0);
1706 }
1707}
1708
1709static void android_os_Parcel_appendFrom(JNIEnv* env, jobject clazz, jobject parcel, jint offset, jint length)
1710{
1711 Parcel* thisParcel = parcelForJavaObject(env, clazz);
1712 if (thisParcel == NULL) {
1713 return;
1714 }
1715 Parcel* otherParcel = parcelForJavaObject(env, parcel);
1716 if (otherParcel == NULL) {
1717 return;
1718 }
1719
1720 (void) thisParcel->appendFrom(otherParcel, offset, length);
1721}
1722
1723static jboolean android_os_Parcel_hasFileDescriptors(JNIEnv* env, jobject clazz)
1724{
1725 jboolean ret = JNI_FALSE;
1726 Parcel* parcel = parcelForJavaObject(env, clazz);
1727 if (parcel != NULL) {
1728 if (parcel->hasFileDescriptors()) {
1729 ret = JNI_TRUE;
1730 }
1731 }
1732 return ret;
1733}
1734
1735static void android_os_Parcel_writeInterfaceToken(JNIEnv* env, jobject clazz, jstring name)
1736{
1737 Parcel* parcel = parcelForJavaObject(env, clazz);
1738 if (parcel != NULL) {
1739 // In the current implementation, the token is just the serialized interface name that
1740 // the caller expects to be invoking
1741 const jchar* str = env->GetStringCritical(name, 0);
1742 if (str != NULL) {
1743 parcel->writeInterfaceToken(String16(str, env->GetStringLength(name)));
1744 env->ReleaseStringCritical(name, str);
1745 }
1746 }
1747}
1748
1749static void android_os_Parcel_enforceInterface(JNIEnv* env, jobject clazz, jstring name)
1750{
1751 jboolean ret = JNI_FALSE;
1752
1753 Parcel* parcel = parcelForJavaObject(env, clazz);
1754 if (parcel != NULL) {
1755 const jchar* str = env->GetStringCritical(name, 0);
1756 if (str) {
Brad Fitzpatrick7bcad8a32010-07-27 09:49:11 -07001757 IPCThreadState* threadState = IPCThreadState::self();
1758 const int32_t oldPolicy = threadState->getStrictModePolicy();
1759 const bool isValid = parcel->enforceInterface(
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001760 String16(str, env->GetStringLength(name)),
Brad Fitzpatrick7bcad8a32010-07-27 09:49:11 -07001761 threadState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 env->ReleaseStringCritical(name, str);
1763 if (isValid) {
Brad Fitzpatrick7bcad8a32010-07-27 09:49:11 -07001764 const int32_t newPolicy = threadState->getStrictModePolicy();
1765 if (oldPolicy != newPolicy) {
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001766 // Need to keep the Java-level thread-local strict
1767 // mode policy in sync for the libcore
1768 // enforcements, which involves an upcall back
1769 // into Java. (We can't modify the
1770 // Parcel.enforceInterface signature, as it's
1771 // pseudo-public, and used via AIDL
1772 // auto-generation...)
Brad Fitzpatrick7bcad8a32010-07-27 09:49:11 -07001773 set_dalvik_blockguard_policy(env, newPolicy);
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 return; // everything was correct -> return silently
1776 }
1777 }
1778 }
1779
1780 // all error conditions wind up here
1781 jniThrowException(env, "java/lang/SecurityException",
1782 "Binder invocation to an incorrect interface");
1783}
1784
1785// ----------------------------------------------------------------------------
1786
1787static const JNINativeMethod gParcelMethods[] = {
1788 {"dataSize", "()I", (void*)android_os_Parcel_dataSize},
1789 {"dataAvail", "()I", (void*)android_os_Parcel_dataAvail},
1790 {"dataPosition", "()I", (void*)android_os_Parcel_dataPosition},
1791 {"dataCapacity", "()I", (void*)android_os_Parcel_dataCapacity},
1792 {"setDataSize", "(I)V", (void*)android_os_Parcel_setDataSize},
1793 {"setDataPosition", "(I)V", (void*)android_os_Parcel_setDataPosition},
1794 {"setDataCapacity", "(I)V", (void*)android_os_Parcel_setDataCapacity},
1795 {"writeNative", "([BII)V", (void*)android_os_Parcel_writeNative},
1796 {"writeInt", "(I)V", (void*)android_os_Parcel_writeInt},
1797 {"writeLong", "(J)V", (void*)android_os_Parcel_writeLong},
1798 {"writeFloat", "(F)V", (void*)android_os_Parcel_writeFloat},
1799 {"writeDouble", "(D)V", (void*)android_os_Parcel_writeDouble},
1800 {"writeString", "(Ljava/lang/String;)V", (void*)android_os_Parcel_writeString},
1801 {"writeStrongBinder", "(Landroid/os/IBinder;)V", (void*)android_os_Parcel_writeStrongBinder},
1802 {"writeFileDescriptor", "(Ljava/io/FileDescriptor;)V", (void*)android_os_Parcel_writeFileDescriptor},
1803 {"createByteArray", "()[B", (void*)android_os_Parcel_createByteArray},
1804 {"readInt", "()I", (void*)android_os_Parcel_readInt},
1805 {"readLong", "()J", (void*)android_os_Parcel_readLong},
1806 {"readFloat", "()F", (void*)android_os_Parcel_readFloat},
1807 {"readDouble", "()D", (void*)android_os_Parcel_readDouble},
1808 {"readString", "()Ljava/lang/String;", (void*)android_os_Parcel_readString},
1809 {"readStrongBinder", "()Landroid/os/IBinder;", (void*)android_os_Parcel_readStrongBinder},
1810 {"internalReadFileDescriptor", "()Ljava/io/FileDescriptor;", (void*)android_os_Parcel_readFileDescriptor},
1811 {"openFileDescriptor", "(Ljava/lang/String;I)Ljava/io/FileDescriptor;", (void*)android_os_Parcel_openFileDescriptor},
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001812 {"dupFileDescriptor", "(Ljava/io/FileDescriptor;)Ljava/io/FileDescriptor;", (void*)android_os_Parcel_dupFileDescriptor},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 {"closeFileDescriptor", "(Ljava/io/FileDescriptor;)V", (void*)android_os_Parcel_closeFileDescriptor},
Dianne Hackbornc9119f52011-02-28 18:03:26 -08001814 {"clearFileDescriptor", "(Ljava/io/FileDescriptor;)V", (void*)android_os_Parcel_clearFileDescriptor},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 {"freeBuffer", "()V", (void*)android_os_Parcel_freeBuffer},
1816 {"init", "(I)V", (void*)android_os_Parcel_init},
1817 {"destroy", "()V", (void*)android_os_Parcel_destroy},
1818 {"marshall", "()[B", (void*)android_os_Parcel_marshall},
1819 {"unmarshall", "([BII)V", (void*)android_os_Parcel_unmarshall},
1820 {"appendFrom", "(Landroid/os/Parcel;II)V", (void*)android_os_Parcel_appendFrom},
1821 {"hasFileDescriptors", "()Z", (void*)android_os_Parcel_hasFileDescriptors},
1822 {"writeInterfaceToken", "(Ljava/lang/String;)V", (void*)android_os_Parcel_writeInterfaceToken},
1823 {"enforceInterface", "(Ljava/lang/String;)V", (void*)android_os_Parcel_enforceInterface},
1824};
1825
1826const char* const kParcelPathName = "android/os/Parcel";
1827
1828static int int_register_android_os_Parcel(JNIEnv* env)
1829{
1830 jclass clazz;
1831
1832 clazz = env->FindClass("android/util/Log");
1833 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.util.Log");
1834 gLogOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1835 gLogOffsets.mLogE = env->GetStaticMethodID(
1836 clazz, "e", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
1837 assert(gLogOffsets.mLogE);
1838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 clazz = env->FindClass("android/os/ParcelFileDescriptor");
1840 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor");
1841 gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1842 gParcelFileDescriptorOffsets.mConstructor
1843 = env->GetMethodID(clazz, "<init>", "(Ljava/io/FileDescriptor;)V");
1844
1845 clazz = env->FindClass(kParcelPathName);
1846 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.Parcel");
1847
1848 gParcelOffsets.mObject
1849 = env->GetFieldID(clazz, "mObject", "I");
1850 gParcelOffsets.mOwnObject
1851 = env->GetFieldID(clazz, "mOwnObject", "I");
1852
Brad Fitzpatrick727de402010-07-07 16:06:39 -07001853 clazz = env->FindClass("android/os/StrictMode");
1854 LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.StrictMode");
1855 gStrictModeCallbackOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
1856 gStrictModeCallbackOffsets.mCallback = env->GetStaticMethodID(
1857 clazz, "onBinderStrictModePolicyChange", "(I)V");
1858 LOG_FATAL_IF(gStrictModeCallbackOffsets.mCallback == NULL,
1859 "Unable to find strict mode callback.");
1860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 return AndroidRuntime::registerNativeMethods(
1862 env, kParcelPathName,
1863 gParcelMethods, NELEM(gParcelMethods));
1864}
1865
1866int register_android_os_Binder(JNIEnv* env)
1867{
1868 if (int_register_android_os_Binder(env) < 0)
1869 return -1;
1870 if (int_register_android_os_BinderInternal(env) < 0)
1871 return -1;
1872 if (int_register_android_os_BinderProxy(env) < 0)
1873 return -1;
1874 if (int_register_android_os_Parcel(env) < 0)
1875 return -1;
1876 return 0;
1877}