2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "android_os_HwBinder"
19 #include <android-base/logging.h>
21 #include "android_os_HwBinder.h"
23 #include "android_os_HwParcel.h"
24 #include "android_os_HwRemoteBinder.h"
28 #include <nativehelper/JNIHelp.h>
29 #include <android/hidl/manager/1.0/IServiceManager.h>
30 #include <android/hidl/base/1.0/IBase.h>
31 #include <android/hidl/base/1.0/BpHwBase.h>
32 #include <android_runtime/AndroidRuntime.h>
33 #include <hidl/ServiceManagement.h>
34 #include <hidl/Status.h>
35 #include <hidl/HidlTransportSupport.h>
36 #include <hwbinder/ProcessState.h>
37 #include <nativehelper/ScopedLocalRef.h>
38 #include <vintf/parse_string.h>
39 #include <utils/misc.h>
41 #include "core_jni_helpers.h"
43 using android::AndroidRuntime;
44 using android::hardware::hidl_vec;
45 using android::hardware::hidl_string;
46 using android::hardware::IPCThreadState;
47 using android::hardware::ProcessState;
49 using Return = android::hardware::Return<T>;
51 #define PACKAGE_PATH "android/os"
52 #define CLASS_NAME "HwBinder"
53 #define CLASS_PATH PACKAGE_PATH "/" CLASS_NAME
57 static jclass gErrorClass;
59 static struct fields_t {
61 jmethodID onTransactID;
64 struct JHwBinderHolder : public RefBase {
67 sp<JHwBinder> get(JNIEnv *env, jobject obj) {
68 Mutex::Autolock autoLock(mLock);
70 sp<JHwBinder> binder = mBinder.promote();
73 binder = new JHwBinder(env, obj);
82 wp<JHwBinder> mBinder;
84 DISALLOW_COPY_AND_ASSIGN(JHwBinderHolder);
88 void JHwBinder::InitClass(JNIEnv *env) {
89 ScopedLocalRef<jclass> clazz(
90 env, FindClassOrDie(env, CLASS_PATH));
93 GetFieldIDOrDie(env, clazz.get(), "mNativeContext", "J");
95 gFields.onTransactID =
100 "(IL" PACKAGE_PATH "/HwParcel;L" PACKAGE_PATH "/HwParcel;I)V");
104 sp<JHwBinderHolder> JHwBinder::SetNativeContext(
105 JNIEnv *env, jobject thiz, const sp<JHwBinderHolder> &context) {
106 sp<JHwBinderHolder> old =
107 (JHwBinderHolder *)env->GetLongField(thiz, gFields.contextID);
109 if (context != NULL) {
110 context->incStrong(NULL /* id */);
114 old->decStrong(NULL /* id */);
117 env->SetLongField(thiz, gFields.contextID, (long)context.get());
123 sp<JHwBinder> JHwBinder::GetNativeBinder(
124 JNIEnv *env, jobject thiz) {
125 JHwBinderHolder *holder =
126 reinterpret_cast<JHwBinderHolder *>(
127 env->GetLongField(thiz, gFields.contextID));
129 return holder->get(env, thiz);
132 JHwBinder::JHwBinder(JNIEnv *env, jobject thiz) {
133 jclass clazz = env->GetObjectClass(thiz);
134 CHECK(clazz != NULL);
136 mObject = env->NewGlobalRef(thiz);
139 JHwBinder::~JHwBinder() {
140 JNIEnv *env = AndroidRuntime::getJNIEnv();
142 env->DeleteGlobalRef(mObject);
146 status_t JHwBinder::onTransact(
148 const hardware::Parcel &data,
149 hardware::Parcel *reply,
151 TransactCallback callback) {
152 JNIEnv *env = AndroidRuntime::getJNIEnv();
153 bool isOneway = (flags & TF_ONE_WAY) != 0;
154 ScopedLocalRef<jobject> replyObj(env, nullptr);
155 sp<JHwParcel> replyContext = nullptr;
157 ScopedLocalRef<jobject> requestObj(env, JHwParcel::NewObject(env));
158 JHwParcel::GetNativeContext(env, requestObj.get())->setParcel(
159 const_cast<hardware::Parcel *>(&data), false /* assumeOwnership */);
163 replyObj.reset(JHwParcel::NewObject(env));
165 replyContext = JHwParcel::GetNativeContext(env, replyObj.get());
167 replyContext->setParcel(reply, false /* assumeOwnership */);
168 replyContext->setTransactCallback(callback);
173 gFields.onTransactID,
179 if (env->ExceptionCheck()) {
180 jthrowable excep = env->ExceptionOccurred();
181 env->ExceptionDescribe();
182 env->ExceptionClear();
184 // It is illegal to call IsInstanceOf if there is a pending exception.
185 // Attempting to do so results in a JniAbort which crashes the entire process.
186 if (env->IsInstanceOf(excep, gErrorClass)) {
188 LOG(ERROR) << "Forcefully exiting";
191 LOG(ERROR) << "Uncaught exception!";
194 env->DeleteLocalRef(excep);
200 if (!replyContext->wasSent()) {
201 // The implementation never finished the transaction.
202 err = UNKNOWN_ERROR; // XXX special error code instead?
204 reply->setDataPosition(0 /* pos */);
207 // Release all temporary storage now that scatter-gather data
208 // has been consolidated, either by calling the TransactCallback,
209 // if wasSent() == true or clearing the reply parcel (setDataOffset above).
210 replyContext->getStorage()->release(env);
212 // We cannot permanently pass ownership of "data" and "reply" over to their
213 // Java object wrappers (we don't own them ourselves).
214 replyContext->setParcel(
215 NULL /* parcel */, false /* assumeOwnership */);
219 JHwParcel::GetNativeContext(env, requestObj.get())->setParcel(
220 NULL /* parcel */, false /* assumeOwnership */);
225 } // namespace android
227 ////////////////////////////////////////////////////////////////////////////////
229 using namespace android;
231 static void releaseNativeContext(void *nativeContext) {
232 sp<JHwBinderHolder> context = static_cast<JHwBinderHolder *>(nativeContext);
234 if (context != NULL) {
235 context->decStrong(NULL /* id */);
239 static jlong JHwBinder_native_init(JNIEnv *env) {
240 JHwBinder::InitClass(env);
242 return reinterpret_cast<jlong>(&releaseNativeContext);
245 static void JHwBinder_native_setup(JNIEnv *env, jobject thiz) {
246 sp<JHwBinderHolder> context = new JHwBinderHolder;
247 JHwBinder::SetNativeContext(env, thiz, context);
250 static void JHwBinder_native_transact(
254 jobject /* requestObj */,
255 jobject /* replyObj */,
257 CHECK(!"Should not be here");
260 static void JHwBinder_native_registerService(
263 jstring serviceNameObj) {
264 if (serviceNameObj == NULL) {
265 jniThrowException(env, "java/lang/NullPointerException", NULL);
269 const char *serviceName = env->GetStringUTFChars(serviceNameObj, NULL);
270 if (serviceName == NULL) {
271 return; // XXX exception already pending?
274 sp<hardware::IBinder> binder = JHwBinder::GetNativeBinder(env, thiz);
276 /* TODO(b/33440494) this is not right */
277 sp<hidl::base::V1_0::IBase> base = new hidl::base::V1_0::BpHwBase(binder);
279 auto manager = hardware::defaultServiceManager();
281 if (manager == nullptr) {
282 LOG(ERROR) << "Could not get hwservicemanager.";
283 signalExceptionForError(env, UNKNOWN_ERROR, true /* canThrowRemoteException */);
287 Return<bool> ret = manager->add(serviceName, base);
289 env->ReleaseStringUTFChars(serviceNameObj, serviceName);
292 bool ok = ret.isOk() && ret;
295 LOG(INFO) << "Starting thread pool.";
296 ::android::hardware::ProcessState::self()->startThreadPool();
299 signalExceptionForError(env, (ok ? OK : UNKNOWN_ERROR), true /* canThrowRemoteException */);
302 static jobject JHwBinder_native_getService(
304 jclass /* clazzObj */,
305 jstring ifaceNameObj,
306 jstring serviceNameObj) {
308 using ::android::hidl::base::V1_0::IBase;
309 using ::android::hardware::details::getRawServiceInternal;
311 if (ifaceNameObj == NULL) {
312 jniThrowException(env, "java/lang/NullPointerException", NULL);
315 if (serviceNameObj == NULL) {
316 jniThrowException(env, "java/lang/NullPointerException", NULL);
320 const char *ifaceNameCStr = env->GetStringUTFChars(ifaceNameObj, NULL);
321 if (ifaceNameCStr == NULL) {
322 return NULL; // XXX exception already pending?
324 std::string ifaceName(ifaceNameCStr);
325 env->ReleaseStringUTFChars(ifaceNameObj, ifaceNameCStr);
327 const char *serviceNameCStr = env->GetStringUTFChars(serviceNameObj, NULL);
328 if (serviceNameCStr == NULL) {
329 return NULL; // XXX exception already pending?
331 std::string serviceName(serviceNameCStr);
332 env->ReleaseStringUTFChars(serviceNameObj, serviceNameCStr);
334 // TODO(b/67981006): true /* retry */
335 sp<IBase> ret = getRawServiceInternal(ifaceName, serviceName, false /* retry */, false /* getStub */);
336 sp<hardware::IBinder> service = hardware::toBinder<hidl::base::V1_0::IBase>(ret);
338 if (service == NULL) {
339 signalExceptionForError(env, NAME_NOT_FOUND);
343 LOG(INFO) << "Starting thread pool.";
344 ::android::hardware::ProcessState::self()->startThreadPool();
346 return JHwRemoteBinder::NewObject(env, service);
349 void JHwBinder_native_configureRpcThreadpool(JNIEnv *, jclass,
350 jlong maxThreads, jboolean callerWillJoin) {
351 CHECK(maxThreads > 0);
352 ProcessState::self()->setThreadPoolConfiguration(maxThreads, callerWillJoin /*callerJoinsPool*/);
355 void JHwBinder_native_joinRpcThreadpool() {
356 IPCThreadState::self()->joinThreadPool();
359 static void JHwBinder_report_sysprop_change(JNIEnv * /*env*/, jclass /*clazz*/)
361 report_sysprop_change();
364 static JNINativeMethod gMethods[] = {
365 { "native_init", "()J", (void *)JHwBinder_native_init },
366 { "native_setup", "()V", (void *)JHwBinder_native_setup },
369 "(IL" PACKAGE_PATH "/HwParcel;L" PACKAGE_PATH "/HwParcel;I)V",
370 (void *)JHwBinder_native_transact },
372 { "registerService", "(Ljava/lang/String;)V",
373 (void *)JHwBinder_native_registerService },
375 { "getService", "(Ljava/lang/String;Ljava/lang/String;)L" PACKAGE_PATH "/IHwBinder;",
376 (void *)JHwBinder_native_getService },
378 { "configureRpcThreadpool", "(JZ)V",
379 (void *)JHwBinder_native_configureRpcThreadpool },
381 { "joinRpcThreadpool", "()V",
382 (void *)JHwBinder_native_joinRpcThreadpool },
384 { "native_report_sysprop_change", "()V",
385 (void *)JHwBinder_report_sysprop_change },
390 int register_android_os_HwBinder(JNIEnv *env) {
391 jclass errorClass = FindClassOrDie(env, "java/lang/Error");
392 gErrorClass = MakeGlobalRefOrDie(env, errorClass);
394 return RegisterMethodsOrDie(env, CLASS_PATH, gMethods, NELEM(gMethods));
397 } // namespace android