blob: 49c4f94194ae271d4104405635ea55172349297e [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
Elliott Hughes2fc9d0a2014-08-18 19:50:01 -070017#if defined(__ANDROID__)
18/* libnativehelper is built by NDK 19 in one variant, which doesn't yet have the GNU strerror_r. */
19#undef _GNU_SOURCE
20#endif
21
Elliott Hughes87f62a82011-04-22 19:22:54 -070022#define LOG_TAG "JNIHelp"
23
Brian Carlstromdd8af232012-05-13 23:56:07 -070024#include "JniConstants.h"
Elliott Hughes87f62a82011-04-22 19:22:54 -070025#include "JNIHelp.h"
Ruben Brunka77f3a22013-09-09 02:21:31 -070026#include "ALog-priv.h"
Elliott Hughes87f62a82011-04-22 19:22:54 -070027
Ruben Brunka77f3a22013-09-09 02:21:31 -070028#include <stdio.h>
Elliott Hughes87f62a82011-04-22 19:22:54 -070029#include <stdlib.h>
30#include <string.h>
31#include <assert.h>
32
Brian Carlstromdd8af232012-05-13 23:56:07 -070033#include <string>
34
Elliott Hughes87f62a82011-04-22 19:22:54 -070035/**
36 * Equivalent to ScopedLocalRef, but for C_JNIEnv instead. (And slightly more powerful.)
37 */
38template<typename T>
39class scoped_local_ref {
40public:
41 scoped_local_ref(C_JNIEnv* env, T localRef = NULL)
42 : mEnv(env), mLocalRef(localRef)
43 {
44 }
45
46 ~scoped_local_ref() {
47 reset();
48 }
49
50 void reset(T localRef = NULL) {
51 if (mLocalRef != NULL) {
52 (*mEnv)->DeleteLocalRef(reinterpret_cast<JNIEnv*>(mEnv), mLocalRef);
53 mLocalRef = localRef;
54 }
55 }
56
57 T get() const {
58 return mLocalRef;
59 }
60
61private:
Ian Rogers8288dde2014-11-04 11:42:02 -080062 C_JNIEnv* const mEnv;
Elliott Hughes87f62a82011-04-22 19:22:54 -070063 T mLocalRef;
64
Ian Rogers8288dde2014-11-04 11:42:02 -080065 DISALLOW_COPY_AND_ASSIGN(scoped_local_ref);
Elliott Hughes87f62a82011-04-22 19:22:54 -070066};
67
68static jclass findClass(C_JNIEnv* env, const char* className) {
69 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
70 return (*env)->FindClass(e, className);
71}
72
73extern "C" int jniRegisterNativeMethods(C_JNIEnv* env, const char* className,
74 const JNINativeMethod* gMethods, int numMethods)
75{
76 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
77
Brian Carlstromdd8af232012-05-13 23:56:07 -070078 ALOGV("Registering %s's %d native methods...", className, numMethods);
Elliott Hughes87f62a82011-04-22 19:22:54 -070079
80 scoped_local_ref<jclass> c(env, findClass(env, className));
81 if (c.get() == NULL) {
Elliott Hughesa3b57002013-01-22 09:35:09 -080082 char* msg;
Brian Carlstromdeb6d5d2013-05-10 09:50:08 -070083 asprintf(&msg, "Native registration unable to find class '%s'; aborting...", className);
Elliott Hughesa3b57002013-01-22 09:35:09 -080084 e->FatalError(msg);
Elliott Hughes87f62a82011-04-22 19:22:54 -070085 }
86
87 if ((*env)->RegisterNatives(e, c.get(), gMethods, numMethods) < 0) {
Elliott Hughesa3b57002013-01-22 09:35:09 -080088 char* msg;
Brian Carlstromdeb6d5d2013-05-10 09:50:08 -070089 asprintf(&msg, "RegisterNatives failed for '%s'; aborting...", className);
Elliott Hughesa3b57002013-01-22 09:35:09 -080090 e->FatalError(msg);
Elliott Hughes87f62a82011-04-22 19:22:54 -070091 }
92
93 return 0;
94}
95
96/*
97 * Returns a human-readable summary of an exception object. The buffer will
98 * be populated with the "binary" class name and, if present, the
99 * exception message.
100 */
Brian Carlstromdd8af232012-05-13 23:56:07 -0700101static bool getExceptionSummary(C_JNIEnv* env, jthrowable exception, std::string& result) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700102 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
103
104 /* get the name of the exception's class */
105 scoped_local_ref<jclass> exceptionClass(env, (*env)->GetObjectClass(e, exception)); // can't fail
106 scoped_local_ref<jclass> classClass(env,
107 (*env)->GetObjectClass(e, exceptionClass.get())); // java.lang.Class, can't fail
108 jmethodID classGetNameMethod =
109 (*env)->GetMethodID(e, classClass.get(), "getName", "()Ljava/lang/String;");
110 scoped_local_ref<jstring> classNameStr(env,
111 (jstring) (*env)->CallObjectMethod(e, exceptionClass.get(), classGetNameMethod));
112 if (classNameStr.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700113 (*env)->ExceptionClear(e);
114 result = "<error getting class name>";
115 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700116 }
Elliott Hughes87f62a82011-04-22 19:22:54 -0700117 const char* classNameChars = (*env)->GetStringUTFChars(e, classNameStr.get(), NULL);
118 if (classNameChars == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700119 (*env)->ExceptionClear(e);
120 result = "<error getting class name UTF-8>";
121 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700122 }
Brian Carlstromdd8af232012-05-13 23:56:07 -0700123 result += classNameChars;
124 (*env)->ReleaseStringUTFChars(e, classNameStr.get(), classNameChars);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700125
126 /* if the exception has a detail message, get that */
127 jmethodID getMessage =
128 (*env)->GetMethodID(e, exceptionClass.get(), "getMessage", "()Ljava/lang/String;");
129 scoped_local_ref<jstring> messageStr(env,
130 (jstring) (*env)->CallObjectMethod(e, exception, getMessage));
131 if (messageStr.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700132 return true;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700133 }
134
Brian Carlstromdd8af232012-05-13 23:56:07 -0700135 result += ": ";
136
Elliott Hughes87f62a82011-04-22 19:22:54 -0700137 const char* messageChars = (*env)->GetStringUTFChars(e, messageStr.get(), NULL);
138 if (messageChars != NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700139 result += messageChars;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700140 (*env)->ReleaseStringUTFChars(e, messageStr.get(), messageChars);
141 } else {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700142 result += "<error getting message>";
Elliott Hughes87f62a82011-04-22 19:22:54 -0700143 (*env)->ExceptionClear(e); // clear OOM
Elliott Hughes87f62a82011-04-22 19:22:54 -0700144 }
145
Brian Carlstromdd8af232012-05-13 23:56:07 -0700146 return true;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700147}
148
149/*
150 * Returns an exception (with stack trace) as a string.
151 */
Brian Carlstromdd8af232012-05-13 23:56:07 -0700152static bool getStackTrace(C_JNIEnv* env, jthrowable exception, std::string& result) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700153 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
154
155 scoped_local_ref<jclass> stringWriterClass(env, findClass(env, "java/io/StringWriter"));
156 if (stringWriterClass.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700157 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700158 }
159
160 jmethodID stringWriterCtor = (*env)->GetMethodID(e, stringWriterClass.get(), "<init>", "()V");
161 jmethodID stringWriterToStringMethod =
162 (*env)->GetMethodID(e, stringWriterClass.get(), "toString", "()Ljava/lang/String;");
163
164 scoped_local_ref<jclass> printWriterClass(env, findClass(env, "java/io/PrintWriter"));
165 if (printWriterClass.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700166 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700167 }
168
169 jmethodID printWriterCtor =
170 (*env)->GetMethodID(e, printWriterClass.get(), "<init>", "(Ljava/io/Writer;)V");
171
172 scoped_local_ref<jobject> stringWriter(env,
173 (*env)->NewObject(e, stringWriterClass.get(), stringWriterCtor));
174 if (stringWriter.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700175 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700176 }
177
Huanqi Chend47c3252014-06-24 13:31:31 +0200178 scoped_local_ref<jobject> printWriter(env,
179 (*env)->NewObject(e, printWriterClass.get(), printWriterCtor, stringWriter.get()));
180 if (printWriter.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700181 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700182 }
183
184 scoped_local_ref<jclass> exceptionClass(env, (*env)->GetObjectClass(e, exception)); // can't fail
185 jmethodID printStackTraceMethod =
186 (*env)->GetMethodID(e, exceptionClass.get(), "printStackTrace", "(Ljava/io/PrintWriter;)V");
Huanqi Chend47c3252014-06-24 13:31:31 +0200187 (*env)->CallVoidMethod(e, exception, printStackTraceMethod, printWriter.get());
Elliott Hughes87f62a82011-04-22 19:22:54 -0700188
189 if ((*env)->ExceptionCheck(e)) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700190 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700191 }
192
193 scoped_local_ref<jstring> messageStr(env,
194 (jstring) (*env)->CallObjectMethod(e, stringWriter.get(), stringWriterToStringMethod));
195 if (messageStr.get() == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700196 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700197 }
198
199 const char* utfChars = (*env)->GetStringUTFChars(e, messageStr.get(), NULL);
200 if (utfChars == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700201 return false;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700202 }
203
Brian Carlstromdd8af232012-05-13 23:56:07 -0700204 result = utfChars;
205
Elliott Hughes87f62a82011-04-22 19:22:54 -0700206 (*env)->ReleaseStringUTFChars(e, messageStr.get(), utfChars);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700207 return true;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700208}
209
210extern "C" int jniThrowException(C_JNIEnv* env, const char* className, const char* msg) {
211 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
212
213 if ((*env)->ExceptionCheck(e)) {
214 /* TODO: consider creating the new exception with this as "cause" */
215 scoped_local_ref<jthrowable> exception(env, (*env)->ExceptionOccurred(e));
216 (*env)->ExceptionClear(e);
217
218 if (exception.get() != NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700219 std::string text;
220 getExceptionSummary(env, exception.get(), text);
221 ALOGW("Discarding pending exception (%s) to throw %s", text.c_str(), className);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700222 }
223 }
224
225 scoped_local_ref<jclass> exceptionClass(env, findClass(env, className));
226 if (exceptionClass.get() == NULL) {
Steve Block79a0d9c2012-01-06 19:16:58 +0000227 ALOGE("Unable to find exception class %s", className);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700228 /* ClassNotFoundException now pending */
229 return -1;
230 }
231
232 if ((*env)->ThrowNew(e, exceptionClass.get(), msg) != JNI_OK) {
Steve Block79a0d9c2012-01-06 19:16:58 +0000233 ALOGE("Failed throwing '%s' '%s'", className, msg);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700234 /* an exception, most likely OOM, will now be pending */
235 return -1;
236 }
237
238 return 0;
239}
240
241int jniThrowExceptionFmt(C_JNIEnv* env, const char* className, const char* fmt, va_list args) {
242 char msgBuf[512];
243 vsnprintf(msgBuf, sizeof(msgBuf), fmt, args);
244 return jniThrowException(env, className, msgBuf);
245}
246
247int jniThrowNullPointerException(C_JNIEnv* env, const char* msg) {
248 return jniThrowException(env, "java/lang/NullPointerException", msg);
249}
250
251int jniThrowRuntimeException(C_JNIEnv* env, const char* msg) {
252 return jniThrowException(env, "java/lang/RuntimeException", msg);
253}
254
255int jniThrowIOException(C_JNIEnv* env, int errnum) {
256 char buffer[80];
257 const char* message = jniStrError(errnum, buffer, sizeof(buffer));
258 return jniThrowException(env, "java/io/IOException", message);
259}
260
Elliott Hughesa4e4e742013-09-03 17:47:18 -0700261static std::string jniGetStackTrace(C_JNIEnv* env, jthrowable exception) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700262 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
263
Jeff Browne2b11e72012-04-10 20:34:39 -0700264 scoped_local_ref<jthrowable> currentException(env, (*env)->ExceptionOccurred(e));
Elliott Hughes87f62a82011-04-22 19:22:54 -0700265 if (exception == NULL) {
Jeff Browne2b11e72012-04-10 20:34:39 -0700266 exception = currentException.get();
Elliott Hughes87f62a82011-04-22 19:22:54 -0700267 if (exception == NULL) {
Brian Carlstromdd8af232012-05-13 23:56:07 -0700268 return "<no pending exception>";
Elliott Hughes87f62a82011-04-22 19:22:54 -0700269 }
Jeff Browne2b11e72012-04-10 20:34:39 -0700270 }
Elliott Hughes87f62a82011-04-22 19:22:54 -0700271
Jeff Browne2b11e72012-04-10 20:34:39 -0700272 if (currentException.get() != NULL) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700273 (*env)->ExceptionClear(e);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700274 }
275
Brian Carlstromdd8af232012-05-13 23:56:07 -0700276 std::string trace;
277 if (!getStackTrace(env, exception, trace)) {
Elliott Hughes87f62a82011-04-22 19:22:54 -0700278 (*env)->ExceptionClear(e);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700279 getExceptionSummary(env, exception, trace);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700280 }
281
Elliott Hughes87f62a82011-04-22 19:22:54 -0700282 if (currentException.get() != NULL) {
Jeff Browne2b11e72012-04-10 20:34:39 -0700283 (*env)->Throw(e, currentException.get()); // rethrow
Elliott Hughes87f62a82011-04-22 19:22:54 -0700284 }
Brian Carlstromdd8af232012-05-13 23:56:07 -0700285
286 return trace;
Elliott Hughes87f62a82011-04-22 19:22:54 -0700287}
288
Elliott Hughesa4e4e742013-09-03 17:47:18 -0700289void jniLogException(C_JNIEnv* env, int priority, const char* tag, jthrowable exception) {
290 std::string trace(jniGetStackTrace(env, exception));
291 __android_log_write(priority, tag, trace.c_str());
292}
293
Elliott Hughes87f62a82011-04-22 19:22:54 -0700294const char* jniStrError(int errnum, char* buf, size_t buflen) {
Elliott Hughesd60512c2013-10-08 14:15:18 -0700295#if __GLIBC__
Elliott Hughes87f62a82011-04-22 19:22:54 -0700296 // Note: glibc has a nonstandard strerror_r that returns char* rather than POSIX's int.
297 // char *strerror_r(int errnum, char *buf, size_t n);
Elliott Hughesd60512c2013-10-08 14:15:18 -0700298 return strerror_r(errnum, buf, buflen);
299#else
300 int rc = strerror_r(errnum, buf, buflen);
301 if (rc != 0) {
302 // (POSIX only guarantees a value other than 0. The safest
Elliott Hughes87f62a82011-04-22 19:22:54 -0700303 // way to implement this function is to use C++ and overload on the
Elliott Hughesd60512c2013-10-08 14:15:18 -0700304 // type of strerror_r to accurately distinguish GNU from POSIX.)
Elliott Hughes87f62a82011-04-22 19:22:54 -0700305 snprintf(buf, buflen, "errno %d", errnum);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700306 }
Elliott Hughesd60512c2013-10-08 14:15:18 -0700307 return buf;
308#endif
Elliott Hughes87f62a82011-04-22 19:22:54 -0700309}
310
Elliott Hughes87f62a82011-04-22 19:22:54 -0700311jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd) {
312 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700313 static jmethodID ctor = e->GetMethodID(JniConstants::fileDescriptorClass, "<init>", "()V");
314 jobject fileDescriptor = (*env)->NewObject(e, JniConstants::fileDescriptorClass, ctor);
Narayan Kamathe29dbf52013-10-31 17:17:10 +0000315 // NOTE: NewObject ensures that an OutOfMemoryError will be seen by the Java
316 // caller if the alloc fails, so we just return NULL when that happens.
317 if (fileDescriptor != NULL) {
318 jniSetFileDescriptorOfFD(env, fileDescriptor, fd);
319 }
Elliott Hughes87f62a82011-04-22 19:22:54 -0700320 return fileDescriptor;
321}
322
323int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor) {
324 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700325 static jfieldID fid = e->GetFieldID(JniConstants::fileDescriptorClass, "descriptor", "I");
Narayan Kamathe29dbf52013-10-31 17:17:10 +0000326 if (fileDescriptor != NULL) {
327 return (*env)->GetIntField(e, fileDescriptor, fid);
328 } else {
329 return -1;
330 }
Elliott Hughes87f62a82011-04-22 19:22:54 -0700331}
332
333void jniSetFileDescriptorOfFD(C_JNIEnv* env, jobject fileDescriptor, int value) {
334 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
Brian Carlstromdd8af232012-05-13 23:56:07 -0700335 static jfieldID fid = e->GetFieldID(JniConstants::fileDescriptorClass, "descriptor", "I");
336 (*env)->SetIntField(e, fileDescriptor, fid, value);
Elliott Hughes87f62a82011-04-22 19:22:54 -0700337}
338
Jeff Browndc176c52013-04-02 18:09:29 -0700339jobject jniGetReferent(C_JNIEnv* env, jobject ref) {
340 JNIEnv* e = reinterpret_cast<JNIEnv*>(env);
341 static jmethodID get = e->GetMethodID(JniConstants::referenceClass, "get", "()Ljava/lang/Object;");
342 return (*env)->CallObjectMethod(e, ref, get);
343}
344