1 /*
2  * Copyright (C) 2007 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 /*
18  * JNI helper functions.
19  *
20  * This file may be included by C or C++ code, which is trouble because jni.h
21  * uses different typedefs for JNIEnv in each language.
22  */
23 #ifndef NATIVEHELPER_JNIHELP_H_
24 #define NATIVEHELPER_JNIHELP_H_
25 
26 #include <errno.h>
27 #include <unistd.h>
28 
29 #include <jni.h>
30 #include "module_api.h"
31 
32 #ifndef NELEM
33 # define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
34 #endif
35 
36 /*
37  * Register one or more native methods with a particular class.
38  * "className" looks like "java/lang/String". Aborts on failure.
39  * TODO: fix all callers and change the return type to void.
40  */
41 MODULE_API int jniRegisterNativeMethods(C_JNIEnv* env,
42                                         const char* className,
43                                         const JNINativeMethod* gMethods,
44                                         int numMethods);
45 
46 /*
47  * Throw an exception with the specified class and an optional message.
48  *
49  * The "className" argument will be passed directly to FindClass, which
50  * takes strings with slashes (e.g. "java/lang/Object").
51  *
52  * If an exception is currently pending, we log a warning message and
53  * clear it.
54  *
55  * Returns 0 on success, nonzero if something failed (e.g. the exception
56  * class couldn't be found, so *an* exception will still be pending).
57  *
58  * Currently aborts the VM if it can't throw the exception.
59  */
60 MODULE_API int jniThrowException(C_JNIEnv* env, const char* className, const char* msg);
61 
62 /*
63  * Throw an exception with the specified class and formatted error message.
64  *
65  * The "className" argument will be passed directly to FindClass, which
66  * takes strings with slashes (e.g. "java/lang/Object").
67  *
68  * If an exception is currently pending, we log a warning message and
69  * clear it.
70  *
71  * Returns 0 on success, nonzero if something failed (e.g. the exception
72  * class couldn't be found, so *an* exception will still be pending).
73  *
74  * Currently aborts the VM if it can't throw the exception.
75  */
76 MODULE_API int jniThrowExceptionFmt(C_JNIEnv* env, const char* className, const char* fmt, va_list args);
77 
78 /*
79  * Throw a java.lang.NullPointerException, with an optional message.
80  */
81 MODULE_API int jniThrowNullPointerException(C_JNIEnv* env, const char* msg);
82 
83 /*
84  * Throw a java.lang.RuntimeException, with an optional message.
85  */
86 MODULE_API int jniThrowRuntimeException(C_JNIEnv* env, const char* msg);
87 
88 /*
89  * Throw a java.io.IOException, generating the message from errno.
90  */
91 MODULE_API int jniThrowIOException(C_JNIEnv* env, int errnum);
92 
93 /*
94  * Return a pointer to a locale-dependent error string explaining errno
95  * value 'errnum'. The returned pointer may or may not be equal to 'buf'.
96  * This function is thread-safe (unlike strerror) and portable (unlike
97  * strerror_r).
98  */
99 MODULE_API const char* jniStrError(int errnum, char* buf, size_t buflen);
100 
101 /*
102  * Returns a new java.io.FileDescriptor for the given int fd.
103  */
104 MODULE_API jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd);
105 
106 /*
107  * Returns the int fd from a java.io.FileDescriptor.
108  */
109 MODULE_API int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);
110 
111 /*
112  * Sets the int fd in a java.io.FileDescriptor.  Throws java.lang.NullPointerException
113  * if fileDescriptor is null.
114  */
115 MODULE_API void jniSetFileDescriptorOfFD(C_JNIEnv* env,
116                                          jobject fileDescriptor,
117                                          int value);
118 
119 /*
120  * Returns the long ownerId from a java.io.FileDescriptor.
121  */
122 MODULE_API jlong jniGetOwnerIdFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);
123 
124 /*
125  * Gets the managed heap array backing a java.nio.Buffer instance.
126  *
127  * Returns nullptr if there is no array backing.
128  *
129  * This method performs a JNI call to java.nio.NIOAccess.getBaseArray().
130  */
131 MODULE_API jarray jniGetNioBufferBaseArray(C_JNIEnv* env, jobject nioBuffer);
132 
133 /*
134  * Gets the offset in bytes from the start of the managed heap array backing the buffer.
135  *
136  * Returns 0 if there is no array backing.
137  *
138  * This method performs a JNI call to java.nio.NIOAccess.getBaseArrayOffset().
139  */
140 MODULE_API jint jniGetNioBufferBaseArrayOffset(C_JNIEnv* env, jobject nioBuffer);
141 
142 /*
143  * Gets field information from a java.nio.Buffer instance.
144  *
145  * Reads the |position|, |limit|, and |elementSizeShift| fields from the buffer instance.
146  *
147  * Returns the |address| field of the java.nio.Buffer instance which is only valid (non-zero) when
148  * the buffer is backed by a direct buffer.
149  */
150 MODULE_API jlong jniGetNioBufferFields(C_JNIEnv* env,
151                                        jobject nioBuffer,
152                                        /*out*/jint* position,
153                                        /*out*/jint* limit,
154                                        /*out*/jint* elementSizeShift);
155 
156 /*
157  * Gets the current position from a java.nio.Buffer as a pointer to memory in a fixed buffer.
158  *
159  * Returns 0 if |nioBuffer| is not backed by a direct buffer.
160  *
161  * This method reads the |address|, |position|, and |elementSizeShift| fields from the
162  * java.nio.Buffer instance to calculate the pointer address for the current position.
163  */
164 MODULE_API jlong jniGetNioBufferPointer(C_JNIEnv* env, jobject nioBuffer);
165 
166 /*
167  * Returns the reference from a java.lang.ref.Reference.
168  */
169 MODULE_API jobject jniGetReferent(C_JNIEnv* env, jobject ref);
170 
171 /*
172  * Returns a Java String object created from UTF-16 data either from jchar or,
173  * if called from C++11, char16_t (a bitwise identical distinct type).
174  */
175 MODULE_API jstring jniCreateString(C_JNIEnv* env, const jchar* unicodeChars, jsize len);
176 
177 /*
178  * Log a message and an exception.
179  * If exception is NULL, logs the current exception in the JNI environment.
180  */
181 MODULE_API void jniLogException(C_JNIEnv* env, int priority, const char* tag, jthrowable exception);
182 
183 /*
184  * Clear the cache of constants libnativehelper is using.
185  */
186 MODULE_API void jniUninitializeConstants();
187 
188 /*
189  * For C++ code, we provide inlines that map to the C functions.  g++ always
190  * inlines these, even on non-optimized builds.
191  */
192 #if defined(__cplusplus)
193 
jniRegisterNativeMethods(JNIEnv * env,const char * className,const JNINativeMethod * gMethods,int numMethods)194 inline int jniRegisterNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods) {
195     return jniRegisterNativeMethods(&env->functions, className, gMethods, numMethods);
196 }
197 
jniThrowException(JNIEnv * env,const char * className,const char * msg)198 inline int jniThrowException(JNIEnv* env, const char* className, const char* msg) {
199     return jniThrowException(&env->functions, className, msg);
200 }
201 
202 /*
203  * Equivalent to jniThrowException but with a printf-like format string and
204  * variable-length argument list. This is only available in C++.
205  */
jniThrowExceptionFmt(JNIEnv * env,const char * className,const char * fmt,...)206 inline int jniThrowExceptionFmt(JNIEnv* env, const char* className, const char* fmt, ...) {
207     va_list args;
208     va_start(args, fmt);
209     return jniThrowExceptionFmt(&env->functions, className, fmt, args);
210     va_end(args);
211 }
212 
jniThrowNullPointerException(JNIEnv * env,const char * msg)213 inline int jniThrowNullPointerException(JNIEnv* env, const char* msg) {
214     return jniThrowNullPointerException(&env->functions, msg);
215 }
216 
jniThrowRuntimeException(JNIEnv * env,const char * msg)217 inline int jniThrowRuntimeException(JNIEnv* env, const char* msg) {
218     return jniThrowRuntimeException(&env->functions, msg);
219 }
220 
jniThrowIOException(JNIEnv * env,int errnum)221 inline int jniThrowIOException(JNIEnv* env, int errnum) {
222     return jniThrowIOException(&env->functions, errnum);
223 }
224 
jniCreateFileDescriptor(JNIEnv * env,int fd)225 inline jobject jniCreateFileDescriptor(JNIEnv* env, int fd) {
226     return jniCreateFileDescriptor(&env->functions, fd);
227 }
228 
jniGetFDFromFileDescriptor(JNIEnv * env,jobject fileDescriptor)229 inline int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) {
230     return jniGetFDFromFileDescriptor(&env->functions, fileDescriptor);
231 }
232 
jniSetFileDescriptorOfFD(JNIEnv * env,jobject fileDescriptor,int value)233 inline void jniSetFileDescriptorOfFD(JNIEnv* env, jobject fileDescriptor, int value) {
234     jniSetFileDescriptorOfFD(&env->functions, fileDescriptor, value);
235 }
236 
jniGetOwnerIdFromFileDescriptor(JNIEnv * env,jobject fileDescriptor)237 inline jlong jniGetOwnerIdFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) {
238     return jniGetOwnerIdFromFileDescriptor(&env->functions, fileDescriptor);
239 }
240 
jniGetNioBufferBaseArray(JNIEnv * env,jobject nioBuffer)241 inline jarray jniGetNioBufferBaseArray(JNIEnv* env, jobject nioBuffer) {
242     return jniGetNioBufferBaseArray(&env->functions, nioBuffer);
243 }
244 
jniGetNioBufferBaseArrayOffset(JNIEnv * env,jobject nioBuffer)245 inline jint jniGetNioBufferBaseArrayOffset(JNIEnv* env, jobject nioBuffer) {
246     return jniGetNioBufferBaseArrayOffset(&env->functions, nioBuffer);
247 }
248 
jniGetNioBufferFields(JNIEnv * env,jobject nioBuffer,jint * position,jint * limit,jint * elementSizeShift)249 inline jlong jniGetNioBufferFields(JNIEnv* env, jobject nioBuffer,
250                                    jint* position, jint* limit, jint* elementSizeShift) {
251     return jniGetNioBufferFields(&env->functions, nioBuffer,
252                                  position, limit, elementSizeShift);
253 }
254 
jniGetNioBufferPointer(JNIEnv * env,jobject nioBuffer)255 inline jlong jniGetNioBufferPointer(JNIEnv* env, jobject nioBuffer) {
256     return jniGetNioBufferPointer(&env->functions, nioBuffer);
257 }
258 
jniGetReferent(JNIEnv * env,jobject ref)259 inline jobject jniGetReferent(JNIEnv* env, jobject ref) {
260     return jniGetReferent(&env->functions, ref);
261 }
262 
jniCreateString(JNIEnv * env,const jchar * unicodeChars,jsize len)263 inline jstring jniCreateString(JNIEnv* env, const jchar* unicodeChars, jsize len) {
264     return jniCreateString(&env->functions, unicodeChars, len);
265 }
266 
jniCreateString(JNIEnv * env,const char16_t * unicodeChars,jsize len)267 inline jstring jniCreateString(JNIEnv* env, const char16_t* unicodeChars, jsize len) {
268     return jniCreateString(&env->functions, reinterpret_cast<const jchar*>(unicodeChars), len);
269 }
270 
271 inline void jniLogException(JNIEnv* env, int priority, const char* tag, jthrowable exception = NULL) {
272     jniLogException(&env->functions, priority, tag, exception);
273 }
274 
275 #if !defined(DISALLOW_COPY_AND_ASSIGN)
276 // DISALLOW_COPY_AND_ASSIGN disallows the copy and operator= functions. It goes in the private:
277 // declarations in a class.
278 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
279   TypeName(const TypeName&) = delete;  \
280   void operator=(const TypeName&) = delete
281 #endif  // !defined(DISALLOW_COPY_AND_ASSIGN)
282 
283 #endif  // defined(__cplusplus)
284 
285 /*
286  * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
287  * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
288  * not already defined, then define it here.
289  */
290 #ifndef TEMP_FAILURE_RETRY
291 /* Used to retry syscalls that can return EINTR. */
292 #define TEMP_FAILURE_RETRY(exp) ({         \
293     typeof (exp) _rc;                      \
294     do {                                   \
295         _rc = (exp);                       \
296     } while (_rc == -1 && errno == EINTR); \
297     _rc; })
298 #endif
299 
300 #endif  /* NATIVEHELPER_JNIHELP_H_ */
301