1 /*
2  * Copyright (C) 2010 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 "MessageQueue-JNI"
18 
19 #include <nativehelper/JNIHelp.h>
20 #include <android_runtime/AndroidRuntime.h>
21 
22 #include <utils/Looper.h>
23 #include <utils/Log.h>
24 #include "android_os_MessageQueue.h"
25 
26 #include "core_jni_helpers.h"
27 
28 namespace android {
29 
30 static struct {
31     jfieldID mPtr;   // native object attached to the DVM MessageQueue
32     jmethodID dispatchEvents;
33 } gMessageQueueClassInfo;
34 
35 // Must be kept in sync with the constants in Looper.FileDescriptorCallback
36 static const int CALLBACK_EVENT_INPUT = 1 << 0;
37 static const int CALLBACK_EVENT_OUTPUT = 1 << 1;
38 static const int CALLBACK_EVENT_ERROR = 1 << 2;
39 
40 
41 class NativeMessageQueue : public MessageQueue, public LooperCallback {
42 public:
43     NativeMessageQueue();
44     virtual ~NativeMessageQueue();
45 
46     virtual void raiseException(JNIEnv* env, const char* msg, jthrowable exceptionObj);
47 
48     void pollOnce(JNIEnv* env, jobject obj, int timeoutMillis);
49     void wake();
50     void setFileDescriptorEvents(int fd, int events);
51 
52     virtual int handleEvent(int fd, int events, void* data);
53 
54     /**
55      * A simple proxy that holds a weak reference to a looper callback.
56      */
57     class WeakLooperCallback : public LooperCallback {
58     protected:
59         virtual ~WeakLooperCallback();
60 
61     public:
62         WeakLooperCallback(const wp<LooperCallback>& callback);
63         virtual int handleEvent(int fd, int events, void* data);
64 
65     private:
66         wp<LooperCallback> mCallback;
67     };
68 
69 private:
70     JNIEnv* mPollEnv;
71     jobject mPollObj;
72     jthrowable mExceptionObj;
73 };
74 
75 
MessageQueue()76 MessageQueue::MessageQueue() {
77 }
78 
~MessageQueue()79 MessageQueue::~MessageQueue() {
80 }
81 
raiseAndClearException(JNIEnv * env,const char * msg)82 bool MessageQueue::raiseAndClearException(JNIEnv* env, const char* msg) {
83     if (env->ExceptionCheck()) {
84         jthrowable exceptionObj = env->ExceptionOccurred();
85         env->ExceptionClear();
86         raiseException(env, msg, exceptionObj);
87         env->DeleteLocalRef(exceptionObj);
88         return true;
89     }
90     return false;
91 }
92 
NativeMessageQueue()93 NativeMessageQueue::NativeMessageQueue() :
94         mPollEnv(NULL), mPollObj(NULL), mExceptionObj(NULL) {
95     mLooper = Looper::getForThread();
96     if (mLooper == NULL) {
97         mLooper = new Looper(false);
98         Looper::setForThread(mLooper);
99     }
100 }
101 
~NativeMessageQueue()102 NativeMessageQueue::~NativeMessageQueue() {
103 }
104 
raiseException(JNIEnv * env,const char * msg,jthrowable exceptionObj)105 void NativeMessageQueue::raiseException(JNIEnv* env, const char* msg, jthrowable exceptionObj) {
106     if (exceptionObj) {
107         if (mPollEnv == env) {
108             if (mExceptionObj) {
109                 env->DeleteLocalRef(mExceptionObj);
110             }
111             mExceptionObj = jthrowable(env->NewLocalRef(exceptionObj));
112             ALOGE("Exception in MessageQueue callback: %s", msg);
113             jniLogException(env, ANDROID_LOG_ERROR, LOG_TAG, exceptionObj);
114         } else {
115             ALOGE("Exception: %s", msg);
116             jniLogException(env, ANDROID_LOG_ERROR, LOG_TAG, exceptionObj);
117             LOG_ALWAYS_FATAL("raiseException() was called when not in a callback, exiting.");
118         }
119     }
120 }
121 
pollOnce(JNIEnv * env,jobject pollObj,int timeoutMillis)122 void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
123     mPollEnv = env;
124     mPollObj = pollObj;
125     mLooper->pollOnce(timeoutMillis);
126     mPollObj = NULL;
127     mPollEnv = NULL;
128 
129     if (mExceptionObj) {
130         env->Throw(mExceptionObj);
131         env->DeleteLocalRef(mExceptionObj);
132         mExceptionObj = NULL;
133     }
134 }
135 
wake()136 void NativeMessageQueue::wake() {
137     mLooper->wake();
138 }
139 
setFileDescriptorEvents(int fd,int events)140 void NativeMessageQueue::setFileDescriptorEvents(int fd, int events) {
141     if (events) {
142         int looperEvents = 0;
143         if (events & CALLBACK_EVENT_INPUT) {
144             looperEvents |= Looper::EVENT_INPUT;
145         }
146         if (events & CALLBACK_EVENT_OUTPUT) {
147             looperEvents |= Looper::EVENT_OUTPUT;
148         }
149         mLooper->addFd(fd, Looper::POLL_CALLBACK, looperEvents,
150                 sp<WeakLooperCallback>::make(this),
151                 reinterpret_cast<void*>(events));
152     } else {
153         mLooper->removeFd(fd);
154     }
155 }
156 
handleEvent(int fd,int looperEvents,void * data)157 int NativeMessageQueue::handleEvent(int fd, int looperEvents, void* data) {
158     int events = 0;
159     if (looperEvents & Looper::EVENT_INPUT) {
160         events |= CALLBACK_EVENT_INPUT;
161     }
162     if (looperEvents & Looper::EVENT_OUTPUT) {
163         events |= CALLBACK_EVENT_OUTPUT;
164     }
165     if (looperEvents & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP | Looper::EVENT_INVALID)) {
166         events |= CALLBACK_EVENT_ERROR;
167     }
168     int oldWatchedEvents = reinterpret_cast<intptr_t>(data);
169     int newWatchedEvents = mPollEnv->CallIntMethod(mPollObj,
170             gMessageQueueClassInfo.dispatchEvents, fd, events);
171     if (!newWatchedEvents) {
172         return 0; // unregister the fd
173     }
174     if (newWatchedEvents != oldWatchedEvents) {
175         setFileDescriptorEvents(fd, newWatchedEvents);
176     }
177     return 1;
178 }
179 
180 
181 // --- NativeMessageQueue::WeakLooperCallback ---
182 
WeakLooperCallback(const wp<LooperCallback> & callback)183 NativeMessageQueue::WeakLooperCallback::WeakLooperCallback(const wp<LooperCallback>& callback) :
184         mCallback(callback) {
185 }
186 
~WeakLooperCallback()187 NativeMessageQueue::WeakLooperCallback::~WeakLooperCallback() {
188 }
189 
handleEvent(int fd,int events,void * data)190 int NativeMessageQueue::WeakLooperCallback::handleEvent(int fd, int events, void* data) {
191     sp<LooperCallback> callback = mCallback.promote();
192     if (callback != nullptr) {
193         return callback->handleEvent(fd, events, data);
194     }
195     return 0;
196 }
197 
198 
199 // ----------------------------------------------------------------------------
200 
android_os_MessageQueue_getMessageQueue(JNIEnv * env,jobject messageQueueObj)201 sp<MessageQueue> android_os_MessageQueue_getMessageQueue(JNIEnv* env, jobject messageQueueObj) {
202     jlong ptr = env->GetLongField(messageQueueObj, gMessageQueueClassInfo.mPtr);
203     return reinterpret_cast<NativeMessageQueue*>(ptr);
204 }
205 
android_os_MessageQueue_nativeInit(JNIEnv * env,jclass clazz)206 static jlong android_os_MessageQueue_nativeInit(JNIEnv* env, jclass clazz) {
207     NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
208     if (!nativeMessageQueue) {
209         jniThrowRuntimeException(env, "Unable to allocate native queue");
210         return 0;
211     }
212 
213     nativeMessageQueue->incStrong(env);
214     return reinterpret_cast<jlong>(nativeMessageQueue);
215 }
216 
android_os_MessageQueue_nativeDestroy(JNIEnv * env,jclass clazz,jlong ptr)217 static void android_os_MessageQueue_nativeDestroy(JNIEnv* env, jclass clazz, jlong ptr) {
218     NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
219     nativeMessageQueue->decStrong(env);
220 }
221 
android_os_MessageQueue_nativePollOnce(JNIEnv * env,jobject obj,jlong ptr,jint timeoutMillis)222 static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
223         jlong ptr, jint timeoutMillis) {
224     NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
225     nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
226 }
227 
android_os_MessageQueue_nativeWake(JNIEnv * env,jclass clazz,jlong ptr)228 static void android_os_MessageQueue_nativeWake(JNIEnv* env, jclass clazz, jlong ptr) {
229     NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
230     nativeMessageQueue->wake();
231 }
232 
android_os_MessageQueue_nativeIsPolling(JNIEnv * env,jclass clazz,jlong ptr)233 static jboolean android_os_MessageQueue_nativeIsPolling(JNIEnv* env, jclass clazz, jlong ptr) {
234     NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
235     return nativeMessageQueue->getLooper()->isPolling();
236 }
237 
android_os_MessageQueue_nativeSetFileDescriptorEvents(JNIEnv * env,jclass clazz,jlong ptr,jint fd,jint events)238 static void android_os_MessageQueue_nativeSetFileDescriptorEvents(JNIEnv* env, jclass clazz,
239         jlong ptr, jint fd, jint events) {
240     NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
241     nativeMessageQueue->setFileDescriptorEvents(fd, events);
242 }
243 
244 // ----------------------------------------------------------------------------
245 
246 static const JNINativeMethod gMessageQueueMethods[] = {
247     /* name, signature, funcPtr */
248     { "nativeInit", "()J", (void*)android_os_MessageQueue_nativeInit },
249     { "nativeDestroy", "(J)V", (void*)android_os_MessageQueue_nativeDestroy },
250     { "nativePollOnce", "(JI)V", (void*)android_os_MessageQueue_nativePollOnce },
251     { "nativeWake", "(J)V", (void*)android_os_MessageQueue_nativeWake },
252     { "nativeIsPolling", "(J)Z", (void*)android_os_MessageQueue_nativeIsPolling },
253     { "nativeSetFileDescriptorEvents", "(JII)V",
254             (void*)android_os_MessageQueue_nativeSetFileDescriptorEvents },
255 };
256 
register_android_os_MessageQueue(JNIEnv * env)257 int register_android_os_MessageQueue(JNIEnv* env) {
258     int res = RegisterMethodsOrDie(env, "android/os/MessageQueue", gMessageQueueMethods,
259                                    NELEM(gMessageQueueMethods));
260 
261     jclass clazz = FindClassOrDie(env, "android/os/MessageQueue");
262     gMessageQueueClassInfo.mPtr = GetFieldIDOrDie(env, clazz, "mPtr", "J");
263     gMessageQueueClassInfo.dispatchEvents = GetMethodIDOrDie(env, clazz,
264             "dispatchEvents", "(II)I");
265 
266     return res;
267 }
268 
269 } // namespace android
270