OSDN Git Service

android.os.HwBinder: fix native static method signature
[android-x86/frameworks-base.git] / core / jni / android_os_HwBinder.cpp
1 /*
2  * Copyright (C) 2016 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_NDEBUG 0
18 #define LOG_TAG "android_os_HwBinder"
19 #include <android-base/logging.h>
20
21 #include "android_os_HwBinder.h"
22
23 #include "android_os_HwParcel.h"
24 #include "android_os_HwRemoteBinder.h"
25
26 #include <cstring>
27
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>
40
41 #include "core_jni_helpers.h"
42
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;
48 template<typename T>
49 using Return = android::hardware::Return<T>;
50
51 #define PACKAGE_PATH    "android/os"
52 #define CLASS_NAME      "HwBinder"
53 #define CLASS_PATH      PACKAGE_PATH "/" CLASS_NAME
54
55 namespace android {
56
57 static jclass gErrorClass;
58
59 static struct fields_t {
60     jfieldID contextID;
61     jmethodID onTransactID;
62 } gFields;
63
64 struct JHwBinderHolder : public RefBase {
65     JHwBinderHolder() {}
66
67     sp<JHwBinder> get(JNIEnv *env, jobject obj) {
68         Mutex::Autolock autoLock(mLock);
69
70         sp<JHwBinder> binder = mBinder.promote();
71
72         if (binder == NULL) {
73             binder = new JHwBinder(env, obj);
74             mBinder = binder;
75         }
76
77         return binder;
78     }
79
80 private:
81     Mutex mLock;
82     wp<JHwBinder> mBinder;
83
84     DISALLOW_COPY_AND_ASSIGN(JHwBinderHolder);
85 };
86
87 // static
88 void JHwBinder::InitClass(JNIEnv *env) {
89     ScopedLocalRef<jclass> clazz(
90             env, FindClassOrDie(env, CLASS_PATH));
91
92     gFields.contextID =
93         GetFieldIDOrDie(env, clazz.get(), "mNativeContext", "J");
94
95     gFields.onTransactID =
96         GetMethodIDOrDie(
97                 env,
98                 clazz.get(),
99                 "onTransact",
100                 "(IL" PACKAGE_PATH "/HwParcel;L" PACKAGE_PATH "/HwParcel;I)V");
101 }
102
103 // static
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);
108
109     if (context != NULL) {
110         context->incStrong(NULL /* id */);
111     }
112
113     if (old != NULL) {
114         old->decStrong(NULL /* id */);
115     }
116
117     env->SetLongField(thiz, gFields.contextID, (long)context.get());
118
119     return old;
120 }
121
122 // static
123 sp<JHwBinder> JHwBinder::GetNativeBinder(
124         JNIEnv *env, jobject thiz) {
125     JHwBinderHolder *holder =
126         reinterpret_cast<JHwBinderHolder *>(
127                 env->GetLongField(thiz, gFields.contextID));
128
129     return holder->get(env, thiz);
130 }
131
132 JHwBinder::JHwBinder(JNIEnv *env, jobject thiz) {
133     jclass clazz = env->GetObjectClass(thiz);
134     CHECK(clazz != NULL);
135
136     mObject = env->NewGlobalRef(thiz);
137 }
138
139 JHwBinder::~JHwBinder() {
140     JNIEnv *env = AndroidRuntime::getJNIEnv();
141
142     env->DeleteGlobalRef(mObject);
143     mObject = NULL;
144 }
145
146 status_t JHwBinder::onTransact(
147         uint32_t code,
148         const hardware::Parcel &data,
149         hardware::Parcel *reply,
150         uint32_t flags,
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;
156
157     ScopedLocalRef<jobject> requestObj(env, JHwParcel::NewObject(env));
158     JHwParcel::GetNativeContext(env, requestObj.get())->setParcel(
159             const_cast<hardware::Parcel *>(&data), false /* assumeOwnership */);
160
161
162     if (!isOneway) {
163         replyObj.reset(JHwParcel::NewObject(env));
164
165         replyContext = JHwParcel::GetNativeContext(env, replyObj.get());
166
167         replyContext->setParcel(reply, false /* assumeOwnership */);
168         replyContext->setTransactCallback(callback);
169     }
170
171     env->CallVoidMethod(
172             mObject,
173             gFields.onTransactID,
174             code,
175             requestObj.get(),
176             replyObj.get(),
177             flags);
178
179     if (env->ExceptionCheck()) {
180         jthrowable excep = env->ExceptionOccurred();
181         env->ExceptionDescribe();
182         env->ExceptionClear();
183
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)) {
187             /* It's an error */
188             LOG(ERROR) << "Forcefully exiting";
189             exit(1);
190         } else {
191             LOG(ERROR) << "Uncaught exception!";
192         }
193
194         env->DeleteLocalRef(excep);
195     }
196
197     status_t err = OK;
198
199     if (!isOneway) {
200         if (!replyContext->wasSent()) {
201             // The implementation never finished the transaction.
202             err = UNKNOWN_ERROR;  // XXX special error code instead?
203
204             reply->setDataPosition(0 /* pos */);
205         }
206
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);
211
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 */);
216
217     }
218
219     JHwParcel::GetNativeContext(env, requestObj.get())->setParcel(
220             NULL /* parcel */, false /* assumeOwnership */);
221
222     return err;
223 }
224
225 }  // namespace android
226
227 ////////////////////////////////////////////////////////////////////////////////
228
229 using namespace android;
230
231 static void releaseNativeContext(void *nativeContext) {
232     sp<JHwBinderHolder> context = static_cast<JHwBinderHolder *>(nativeContext);
233
234     if (context != NULL) {
235         context->decStrong(NULL /* id */);
236     }
237 }
238
239 static jlong JHwBinder_native_init(JNIEnv *env) {
240     JHwBinder::InitClass(env);
241
242     return reinterpret_cast<jlong>(&releaseNativeContext);
243 }
244
245 static void JHwBinder_native_setup(JNIEnv *env, jobject thiz) {
246     sp<JHwBinderHolder> context = new JHwBinderHolder;
247     JHwBinder::SetNativeContext(env, thiz, context);
248 }
249
250 static void JHwBinder_native_transact(
251         JNIEnv * /* env */,
252         jobject /* thiz */,
253         jint /* code */,
254         jobject /* requestObj */,
255         jobject /* replyObj */,
256         jint /* flags */) {
257     CHECK(!"Should not be here");
258 }
259
260 static void JHwBinder_native_registerService(
261         JNIEnv *env,
262         jobject thiz,
263         jstring serviceNameObj) {
264     if (serviceNameObj == NULL) {
265         jniThrowException(env, "java/lang/NullPointerException", NULL);
266         return;
267     }
268
269     const char *serviceName = env->GetStringUTFChars(serviceNameObj, NULL);
270     if (serviceName == NULL) {
271         return;  // XXX exception already pending?
272     }
273
274     sp<hardware::IBinder> binder = JHwBinder::GetNativeBinder(env, thiz);
275
276     /* TODO(b/33440494) this is not right */
277     sp<hidl::base::V1_0::IBase> base = new hidl::base::V1_0::BpHwBase(binder);
278
279     auto manager = hardware::defaultServiceManager();
280
281     if (manager == nullptr) {
282         LOG(ERROR) << "Could not get hwservicemanager.";
283         signalExceptionForError(env, UNKNOWN_ERROR, true /* canThrowRemoteException */);
284         return;
285     }
286
287     Return<bool> ret = manager->add(serviceName, base);
288
289     env->ReleaseStringUTFChars(serviceNameObj, serviceName);
290     serviceName = NULL;
291
292     bool ok = ret.isOk() && ret;
293
294     if (ok) {
295         LOG(INFO) << "Starting thread pool.";
296         ::android::hardware::ProcessState::self()->startThreadPool();
297     }
298
299     signalExceptionForError(env, (ok ? OK : UNKNOWN_ERROR), true /* canThrowRemoteException */);
300 }
301
302 static jobject JHwBinder_native_getService(
303         JNIEnv *env,
304         jclass /* clazzObj */,
305         jstring ifaceNameObj,
306         jstring serviceNameObj) {
307
308     using ::android::hidl::base::V1_0::IBase;
309     using ::android::hardware::details::getRawServiceInternal;
310
311     if (ifaceNameObj == NULL) {
312         jniThrowException(env, "java/lang/NullPointerException", NULL);
313         return NULL;
314     }
315     if (serviceNameObj == NULL) {
316         jniThrowException(env, "java/lang/NullPointerException", NULL);
317         return NULL;
318     }
319
320     const char *ifaceNameCStr = env->GetStringUTFChars(ifaceNameObj, NULL);
321     if (ifaceNameCStr == NULL) {
322         return NULL; // XXX exception already pending?
323     }
324     std::string ifaceName(ifaceNameCStr);
325     env->ReleaseStringUTFChars(ifaceNameObj, ifaceNameCStr);
326
327     const char *serviceNameCStr = env->GetStringUTFChars(serviceNameObj, NULL);
328     if (serviceNameCStr == NULL) {
329         return NULL; // XXX exception already pending?
330     }
331     std::string serviceName(serviceNameCStr);
332     env->ReleaseStringUTFChars(serviceNameObj, serviceNameCStr);
333
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);
337
338     if (service == NULL) {
339         signalExceptionForError(env, NAME_NOT_FOUND);
340         return NULL;
341     }
342
343     LOG(INFO) << "Starting thread pool.";
344     ::android::hardware::ProcessState::self()->startThreadPool();
345
346     return JHwRemoteBinder::NewObject(env, service);
347 }
348
349 void JHwBinder_native_configureRpcThreadpool(JNIEnv *, jclass,
350         jlong maxThreads, jboolean callerWillJoin) {
351     CHECK(maxThreads > 0);
352     ProcessState::self()->setThreadPoolConfiguration(maxThreads, callerWillJoin /*callerJoinsPool*/);
353 }
354
355 void JHwBinder_native_joinRpcThreadpool() {
356     IPCThreadState::self()->joinThreadPool();
357 }
358
359 static void JHwBinder_report_sysprop_change(JNIEnv * /*env*/, jclass /*clazz*/)
360 {
361     report_sysprop_change();
362 }
363
364 static JNINativeMethod gMethods[] = {
365     { "native_init", "()J", (void *)JHwBinder_native_init },
366     { "native_setup", "()V", (void *)JHwBinder_native_setup },
367
368     { "transact",
369         "(IL" PACKAGE_PATH "/HwParcel;L" PACKAGE_PATH "/HwParcel;I)V",
370         (void *)JHwBinder_native_transact },
371
372     { "registerService", "(Ljava/lang/String;)V",
373         (void *)JHwBinder_native_registerService },
374
375     { "getService", "(Ljava/lang/String;Ljava/lang/String;)L" PACKAGE_PATH "/IHwBinder;",
376         (void *)JHwBinder_native_getService },
377
378     { "configureRpcThreadpool", "(JZ)V",
379         (void *)JHwBinder_native_configureRpcThreadpool },
380
381     { "joinRpcThreadpool", "()V",
382         (void *)JHwBinder_native_joinRpcThreadpool },
383
384     { "native_report_sysprop_change", "()V",
385         (void *)JHwBinder_report_sysprop_change },
386 };
387
388 namespace android {
389
390 int register_android_os_HwBinder(JNIEnv *env) {
391     jclass errorClass = FindClassOrDie(env, "java/lang/Error");
392     gErrorClass = MakeGlobalRefOrDie(env, errorClass);
393
394     return RegisterMethodsOrDie(env, CLASS_PATH, gMethods, NELEM(gMethods));
395 }
396
397 }  // namespace android