blob: b5fba9994f1a80fe379a45e1c975d746e8fca475 [file] [log] [blame]
Elliott Hughes87f62a82011-04-22 19:22:54 -07001/*
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 "JNIHelp"
18
Brian Carlstromdd8af232012-05-13 23:56:07 -070019#define LIBCORE_CPP_JNI_HELPERS
20
21#include "JniConstants.h"
Elliott Hughes87f62a82011-04-22 19:22:54 -070022#include "JNIHelp.h"
Elliott Hughesa6f951c2011-06-08 15:54:05 -070023#include "cutils/log.h"
Elliott Hughes87f62a82011-04-22 19:22:54 -070024
25#include <stdlib.h>
26#include <string.h>
27#include <assert.h>
28
Brian Carlstromdd8af232012-05-13 23:56:07 -070029#include <string>
30
Elliott Hughes87f62a82011-04-22 19:22:54 -070031/**
32 * Equivalent to ScopedLocalRef, but for C_JNIEnv instead. (And slightly more powerful.)
33 */
34template<typename T>
35class scoped_local_ref {
36public:
37 scoped_local_ref(C_JNIEnv* env, T localRef = NULL)
38 : mEnv(env), mLocalRef(localRef)
39 {
40 }
41
42 ~scoped_local_ref() {
43 reset();
44 }
45
46 void reset(T localRef = NULL) {
47 if (mLocalRef != NULL) {
48 (*mEnv)->DeleteLocalRef(reinterpret_cast<JNIEnv*>(mEnv), mLocalRef);
49 mLocalRef = localRef;
50 }
51 }
52
53 T get() const {
54 return mLocalRef;
55 }
56
57private:
58 C_JNIEnv* mEnv;
59 T mLocalRef;
60
61 // Disallow copy and assignment.
62 scoped_local_ref(const scoped_local_ref&);
63 void operator=(const scoped_local_ref&);
64};
65
66static jclass findClass(C_JNIEnv* env, const char* className) {
67 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
68 return (*env)->FindClass(e, className);
69}
70
71extern "C" int jniRegisterNativeMethods(C_JNIEnv* env, const char* className,
72 const JNINativeMethod* gMethods, int numMethods)
73{
74 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
75
Brian Carlstromdd8af232012-05-13 23:56:07 -070076 ALOGV("Registering %s's %d native methods...", className, numMethods);
Elliott Hughes87f62a82011-04-22 19:22:54 -070077
78 scoped_local_ref<jclass> c(env, findClass(env, className));
79 if (c.get() == NULL) {
Elliott Hughesa3b57002013-01-22 09:35:09 -080080 char* msg;
Brian Carlstromdd8af232012-05-13 23:56:07 -070081 asprintf(&msg, "Native registration unable to find class '%s', aborting...", className);
Elliott Hughesa3b57002013-01-22 09:35:09 -080082 e->FatalError(msg);
Elliott Hughes87f62a82011-04-22 19:22:54 -070083 }
84
85 if ((*env)->RegisterNatives(e, c.get(), gMethods, numMethods) < 0) {
Elliott Hughesa3b57002013-01-22 09:35:09 -080086 char* msg;
Brian Carlstromdd8af232012-05-13 23:56:07 -070087 asprintf(&msg, "RegisterNatives failed for '%s', aborting...", className);
Elliott Hughesa3b57002013-01-22 09:35:09 -080088 e->FatalError(msg);
Elliott Hughes87f62a82011-04-22 19:22:54 -070089 }
90
91 return 0;
92}
93
94/*
95 * Returns a human-readable summary of an exception object. The buffer will
96 * be populated with the "binary" class name and, if present, the
97 * exception message.
98 */
Brian Carlstromdd8af232012-05-13 23:56:07 -070099static bool getExceptionSummary(C_JNIEnv* env, jthrowable exception, std::string& result) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700100 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
101
102 /* get the name of the exception's class */
103 scoped_local_ref<jclass> exceptionClass(env, (*env)->GetObjectClass(e, exception)); // can't fail
104 scoped_local_ref<jclass> classClass(env,
105 (*env)->GetObjectClass(e, exceptionClass.get())); // java.lang.Class, can't fail
106 jmethodID classGetNameMethod =
107 (*env)->GetMethodID(e, classClass.get(), "getName", "()Ljava/lang/String;");
108 scoped_local_ref<jstring> classNameStr(env,
109 (jstring) (*env)->CallObjectMethod(e, exceptionClass.get(), classGetNameMethod));
110 if (classNameStr.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700111 (*env)->ExceptionClear(e);
112 result = "<error getting class name>";
113 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700114 }
Elliott Hughes87f62a82011-04-22 19:22:54 -0700115 const char* classNameChars = (*env)->GetStringUTFChars(e, classNameStr.get(), NULL);
116 if (classNameChars == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700117 (*env)->ExceptionClear(e);
118 result = "<error getting class name UTF-8>";
119 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700120 }
Brian Carlstromdd8af232012-05-13 23:56:07 -0700121 result += classNameChars;
122 (*env)->ReleaseStringUTFChars(e, classNameStr.get(), classNameChars);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700123
124 /* if the exception has a detail message, get that */
125 jmethodID getMessage =
126 (*env)->GetMethodID(e, exceptionClass.get(), "getMessage", "()Ljava/lang/String;");
127 scoped_local_ref<jstring> messageStr(env,
128 (jstring) (*env)->CallObjectMethod(e, exception, getMessage));
129 if (messageStr.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700130 return true;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700131 }
132
Brian Carlstromdd8af232012-05-13 23:56:07 -0700133 result += ": ";
134
Elliott Hughes87f62a82011-04-22 19:22:54 -0700135 const char* messageChars = (*env)->GetStringUTFChars(e, messageStr.get(), NULL);
136 if (messageChars != NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700137 result += messageChars;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700138 (*env)->ReleaseStringUTFChars(e, messageStr.get(), messageChars);
139 } else {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700140 result += "<error getting message>";
Elliott Hughes87f62a82011-04-22 19:22:54 -0700141 (*env)->ExceptionClear(e); // clear OOM
Elliott Hughes87f62a82011-04-22 19:22:54 -0700142 }
143
Brian Carlstromdd8af232012-05-13 23:56:07 -0700144 return true;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700145}
146
147/*
148 * Returns an exception (with stack trace) as a string.
149 */
Brian Carlstromdd8af232012-05-13 23:56:07 -0700150static bool getStackTrace(C_JNIEnv* env, jthrowable exception, std::string& result) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700151 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
152
153 scoped_local_ref<jclass> stringWriterClass(env, findClass(env, "java/io/StringWriter"));
154 if (stringWriterClass.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700155 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700156 }
157
158 jmethodID stringWriterCtor = (*env)->GetMethodID(e, stringWriterClass.get(), "<init>", "()V");
159 jmethodID stringWriterToStringMethod =
160 (*env)->GetMethodID(e, stringWriterClass.get(), "toString", "()Ljava/lang/String;");
161
162 scoped_local_ref<jclass> printWriterClass(env, findClass(env, "java/io/PrintWriter"));
163 if (printWriterClass.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700164 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700165 }
166
167 jmethodID printWriterCtor =
168 (*env)->GetMethodID(e, printWriterClass.get(), "<init>", "(Ljava/io/Writer;)V");
169
170 scoped_local_ref<jobject> stringWriter(env,
171 (*env)->NewObject(e, stringWriterClass.get(), stringWriterCtor));
172 if (stringWriter.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700173 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700174 }
175
176 jobject printWriter =
177 (*env)->NewObject(e, printWriterClass.get(), printWriterCtor, stringWriter.get());
178 if (printWriter == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700179 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700180 }
181
182 scoped_local_ref<jclass> exceptionClass(env, (*env)->GetObjectClass(e, exception)); // can't fail
183 jmethodID printStackTraceMethod =
184 (*env)->GetMethodID(e, exceptionClass.get(), "printStackTrace", "(Ljava/io/PrintWriter;)V");
185 (*env)->CallVoidMethod(e, exception, printStackTraceMethod, printWriter);
186
187 if ((*env)->ExceptionCheck(e)) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700188 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700189 }
190
191 scoped_local_ref<jstring> messageStr(env,
192 (jstring) (*env)->CallObjectMethod(e, stringWriter.get(), stringWriterToStringMethod));
193 if (messageStr.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700194 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700195 }
196
197 const char* utfChars = (*env)->GetStringUTFChars(e, messageStr.get(), NULL);
198 if (utfChars == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700199 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700200 }
201
Brian Carlstromdd8af232012-05-13 23:56:07 -0700202 result = utfChars;
203
Elliott Hughes87f62a82011-04-22 19:22:54 -0700204 (*env)->ReleaseStringUTFChars(e, messageStr.get(), utfChars);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700205 return true;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700206}
207
208extern "C" int jniThrowException(C_JNIEnv* env, const char* className, const char* msg) {
209 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
210
211 if ((*env)->ExceptionCheck(e)) {
212 /* TODO: consider creating the new exception with this as "cause" */
213 scoped_local_ref<jthrowable> exception(env, (*env)->ExceptionOccurred(e));
214 (*env)->ExceptionClear(e);
215
216 if (exception.get() != NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700217 std::string text;
218 getExceptionSummary(env, exception.get(), text);
219 ALOGW("Discarding pending exception (%s) to throw %s", text.c_str(), className);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700220 }
221 }
222
223 scoped_local_ref<jclass> exceptionClass(env, findClass(env, className));
224 if (exceptionClass.get() == NULL) {
Steve Block79a0d9c2012-01-06 19:16:58 +0000225 ALOGE("Unable to find exception class %s", className);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700226 /* ClassNotFoundException now pending */
227 return -1;
228 }
229
230 if ((*env)->ThrowNew(e, exceptionClass.get(), msg) != JNI_OK) {
Steve Block79a0d9c2012-01-06 19:16:58 +0000231 ALOGE("Failed throwing '%s' '%s'", className, msg);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700232 /* an exception, most likely OOM, will now be pending */
233 return -1;
234 }
235
236 return 0;
237}
238
239int jniThrowExceptionFmt(C_JNIEnv* env, const char* className, const char* fmt, va_list args) {
240 char msgBuf[512];
241 vsnprintf(msgBuf, sizeof(msgBuf), fmt, args);
242 return jniThrowException(env, className, msgBuf);
243}
244
245int jniThrowNullPointerException(C_JNIEnv* env, const char* msg) {
246 return jniThrowException(env, "java/lang/NullPointerException", msg);
247}
248
249int jniThrowRuntimeException(C_JNIEnv* env, const char* msg) {
250 return jniThrowException(env, "java/lang/RuntimeException", msg);
251}
252
253int jniThrowIOException(C_JNIEnv* env, int errnum) {
254 char buffer[80];
255 const char* message = jniStrError(errnum, buffer, sizeof(buffer));
256 return jniThrowException(env, "java/io/IOException", message);
257}
258
259void jniLogException(C_JNIEnv* env, int priority, const char* tag, jthrowable exception) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700260 std::string trace(jniGetStackTrace(env, exception));
261 __android_log_write(priority, tag, trace.c_str());
262}
263
264extern "C" std::string jniGetStackTrace(C_JNIEnv* env, jthrowable exception) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700265 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
266
Jeff Browne2b11e72012-04-10 20:34:39 -0700267 scoped_local_ref<jthrowable> currentException(env, (*env)->ExceptionOccurred(e));
Elliott Hughes87f62a82011-04-22 19:22:54 -0700268 if (exception == NULL) {
Jeff Browne2b11e72012-04-10 20:34:39 -0700269 exception = currentException.get();
Elliott Hughes87f62a82011-04-22 19:22:54 -0700270 if (exception == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700271 return "<no pending exception>";
Elliott Hughes87f62a82011-04-22 19:22:54 -0700272 }
Jeff Browne2b11e72012-04-10 20:34:39 -0700273 }
Elliott Hughes87f62a82011-04-22 19:22:54 -0700274
Jeff Browne2b11e72012-04-10 20:34:39 -0700275 if (currentException.get() != NULL) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700276 (*env)->ExceptionClear(e);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700277 }
278
Brian Carlstromdd8af232012-05-13 23:56:07 -0700279 std::string trace;
280 if (!getStackTrace(env, exception, trace)) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700281 (*env)->ExceptionClear(e);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700282 getExceptionSummary(env, exception, trace);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700283 }
284
Elliott Hughes87f62a82011-04-22 19:22:54 -0700285 if (currentException.get() != NULL) {
Jeff Browne2b11e72012-04-10 20:34:39 -0700286 (*env)->Throw(e, currentException.get()); // rethrow
Elliott Hughes87f62a82011-04-22 19:22:54 -0700287 }
Brian Carlstromdd8af232012-05-13 23:56:07 -0700288
289 return trace;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700290}
291
292const char* jniStrError(int errnum, char* buf, size_t buflen) {
293 // Note: glibc has a nonstandard strerror_r that returns char* rather than POSIX's int.
294 // char *strerror_r(int errnum, char *buf, size_t n);
295 char* ret = (char*) strerror_r(errnum, buf, buflen);
296 if (((int)ret) == 0) {
297 // POSIX strerror_r, success
298 return buf;
299 } else if (((int)ret) == -1) {
300 // POSIX strerror_r, failure
301 // (Strictly, POSIX only guarantees a value other than 0. The safest
302 // way to implement this function is to use C++ and overload on the
303 // type of strerror_r to accurately distinguish GNU from POSIX. But
304 // realistic implementations will always return -1.)
305 snprintf(buf, buflen, "errno %d", errnum);
306 return buf;
307 } else {
308 // glibc strerror_r returning a string
309 return ret;
310 }
311}
312
Elliott Hughes87f62a82011-04-22 19:22:54 -0700313jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd) {
314 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700315 static jmethodID ctor = e->GetMethodID(JniConstants::fileDescriptorClass, "<init>", "()V");
316 jobject fileDescriptor = (*env)->NewObject(e, JniConstants::fileDescriptorClass, ctor);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700317 jniSetFileDescriptorOfFD(env, fileDescriptor, fd);
318 return fileDescriptor;
319}
320
321int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor) {
322 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700323 static jfieldID fid = e->GetFieldID(JniConstants::fileDescriptorClass, "descriptor", "I");
324 return (*env)->GetIntField(e, fileDescriptor, fid);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700325}
326
327void jniSetFileDescriptorOfFD(C_JNIEnv* env, jobject fileDescriptor, int value) {
328 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700329 static jfieldID fid = e->GetFieldID(JniConstants::fileDescriptorClass, "descriptor", "I");
330 (*env)->SetIntField(e, fileDescriptor, fid, value);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700331}
332
333/*
334 * DO NOT USE THIS FUNCTION
335 *
336 * Get a pointer to the elements of a non-movable array.
337 *
338 * The semantics are similar to GetDirectBufferAddress. Specifically, the VM
339 * guarantees that the array will not move, and the caller must ensure that
340 * it does not continue to use the pointer after the object is collected.
341 *
342 * We currently use an illegal sequence that trips up CheckJNI when
343 * the "forcecopy" mode is enabled. We pass in a magic value to work
344 * around the problem.
345 *
346 * Returns NULL if the array is movable.
347 */
348#define kNoCopyMagic 0xd5aab57f /* also in CheckJni.c */
349extern "C" jbyte* jniGetNonMovableArrayElements(C_JNIEnv* env, jarray arrayObj) {
350 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
351
352 jbyteArray byteArray = reinterpret_cast<jbyteArray>(arrayObj);
353
354 /*
355 * Normally the "isCopy" parameter is for a return value only, so the
356 * non-CheckJNI VM will ignore whatever we pass in.
357 */
358 uint32_t noCopy = kNoCopyMagic;
359 jbyte* result = (*env)->GetByteArrayElements(e, byteArray, reinterpret_cast<jboolean*>(&noCopy));
360
361 /*
362 * The non-CheckJNI implementation only cares about the array object,
363 * so we can replace the element pointer with the magic value.
364 */
365 (*env)->ReleaseByteArrayElements(e, byteArray, reinterpret_cast<jbyte*>(kNoCopyMagic), 0);
366 return result;
367}