blob: aacecb68bd1eaee0d7ee52b5cd68761a6ad35d75 [file] [log] [blame]
The Android Open Source Project7f844dd2009-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/*
58 * Throw a java.IO.IOException, generating the message from errno.
59 */
60int jniThrowIOException(JNIEnv* env, int errnum)
61{
62 // note: glibc has a nonstandard
63 // strerror_r that looks like this:
64 // char *strerror_r(int errnum, char *buf, size_t n);
65
66 const char* message;
67 char buffer[80];
68 char* ret;
69
70 buffer[0] = 0;
71 ret = (char*) strerror_r(errnum, buffer, sizeof(buffer));
72
73 if (((int)ret) == 0) {
74 //POSIX strerror_r, success
75 message = buffer;
76 } else if (((int)ret) == -1) {
77 //POSIX strerror_r, failure
78
79 snprintf (buffer, sizeof(buffer), "errno %d", errnum);
80 message = buffer;
81 } else {
82 //glibc strerror_r returning a string
83 message = ret;
84 }
85
86 return jniThrowException(env, "java/io/IOException", message);
87}
88