blob: 748d8ff9b05a0bfbf29160049c1b8fea3014c1a4 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * JNI helper functions.
5 */
6#define LOG_TAG "JNIHelp"
7#include "JNIHelp.h"
8#include "utils/Log.h"
9
10#include <string.h>
11#include <assert.h>
12
13/*
14 * Register native JNI-callable methods.
15 *
16 * "className" looks like "java/lang/String".
17 */
18int jniRegisterNativeMethods(JNIEnv* env, const char* className,
19 const JNINativeMethod* gMethods, int numMethods)
20{
21 jclass clazz;
22
23 LOGV("Registering %s natives\n", className);
24 clazz = (*env)->FindClass(env, className);
25 if (clazz == NULL) {
26 LOGE("Native registration unable to find class '%s'\n", className);
27 return -1;
28 }
29 if ((*env)->RegisterNatives(env, clazz, gMethods, numMethods) < 0) {
30 LOGE("RegisterNatives failed for '%s'\n", className);
31 return -1;
32 }
33 return 0;
34}
35
36/*
37 * Throw an exception with the specified class and an optional message.
38 */
39int jniThrowException(JNIEnv* env, const char* className, const char* msg)
40{
41 jclass exceptionClass;
42
43 exceptionClass = (*env)->FindClass(env, className);
44 if (exceptionClass == NULL) {
45 LOGE("Unable to find exception class %s\n", className);
46 assert(0); /* fatal during dev; should always be fatal? */
47 return -1;
48 }
49
50 if ((*env)->ThrowNew(env, exceptionClass, msg) != JNI_OK) {
51 LOGE("Failed throwing '%s' '%s'\n", className, msg);
52 assert(!"failed to throw");
53 }
54 return 0;
55}
56
57/*
Dan Bornstein4a888b02009-12-07 15:46:23 -080058 * Throw a java.lang.RuntimeException, with an optional message.
59 */
60int jniThrowRuntimeException(JNIEnv* env, const char* msg)
61{
62 return jniThrowException(env, "java/lang/RuntimeException", msg);
63}
64
65/*
66 * Throw a java.io.IOException, generating the message from errno.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080067 */
68int jniThrowIOException(JNIEnv* env, int errnum)
69{
70 // note: glibc has a nonstandard
71 // strerror_r that looks like this:
72 // char *strerror_r(int errnum, char *buf, size_t n);
73
74 const char* message;
75 char buffer[80];
76 char* ret;
77
78 buffer[0] = 0;
79 ret = (char*) strerror_r(errnum, buffer, sizeof(buffer));
80
81 if (((int)ret) == 0) {
82 //POSIX strerror_r, success
83 message = buffer;
84 } else if (((int)ret) == -1) {
85 //POSIX strerror_r, failure
86
87 snprintf (buffer, sizeof(buffer), "errno %d", errnum);
88 message = buffer;
89 } else {
90 //glibc strerror_r returning a string
91 message = ret;
92 }
93
94 return jniThrowException(env, "java/io/IOException", message);
95}