1 /*
2 * Copyright (C) 2014 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 #include <errno.h>
18 #include <jni.h>
19 #include <string.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <cutils/log.h>
24 #include <inttypes.h>
25
isAddressExecutable(uintptr_t address)26 static jboolean isAddressExecutable(uintptr_t address) {
27 char line[1024];
28 jboolean retval = false;
29 FILE *fp = fopen("/proc/self/maps", "re");
30 if (fp == NULL) {
31 ALOGE("Unable to open /proc/self/maps: %s", strerror(errno));
32 return false;
33 }
34 while(fgets(line, sizeof(line), fp) != NULL) {
35 uintptr_t start;
36 uintptr_t end;
37 char permissions[10];
38 int scan = sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %9s ", &start, &end, permissions);
39 if ((scan == 3) && (start <= address) && (address < end)) {
40 retval = (permissions[2] == 'x');
41 break;
42 }
43 }
44 fclose(fp);
45 return retval;
46 }
47
android_os_cts_NoExecutePermissionTest_isStackExecutable(JNIEnv *,jobject)48 static jboolean android_os_cts_NoExecutePermissionTest_isStackExecutable(JNIEnv*, jobject)
49 {
50 unsigned int foo;
51 return isAddressExecutable((uintptr_t) &foo);
52 }
53
54
android_os_cts_NoExecutePermissionTest_isHeapExecutable(JNIEnv *,jobject)55 static jboolean android_os_cts_NoExecutePermissionTest_isHeapExecutable(JNIEnv*, jobject)
56 {
57 unsigned int* foo = (unsigned int *) malloc(sizeof(unsigned int));
58 if (foo == NULL) {
59 ALOGE("Unable to allocate memory");
60 return false;
61 }
62 jboolean result = isAddressExecutable((uintptr_t) foo);
63 free(foo);
64 return result;
65 }
66
67 static JNINativeMethod gMethods[] = {
68 { "isStackExecutable", "()Z",
69 (void *) android_os_cts_NoExecutePermissionTest_isStackExecutable },
70 { "isHeapExecutable", "()Z",
71 (void *) android_os_cts_NoExecutePermissionTest_isHeapExecutable }
72 };
73
register_android_os_cts_NoExecutePermissionTest(JNIEnv * env)74 int register_android_os_cts_NoExecutePermissionTest(JNIEnv* env)
75 {
76 jclass clazz = env->FindClass("android/os/cts/NoExecutePermissionTest");
77
78 return env->RegisterNatives(clazz, gMethods,
79 sizeof(gMethods) / sizeof(JNINativeMethod));
80 }
81