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 18 #define LOG_TAG "MMapExecutableTest" 19 20 #include <android/log.h> 21 #include <cutils/log.h> 22 #include <fcntl.h> 23 #include <jni.h> 24 #include <nativehelper/JNIHelp.h> 25 #include <nativehelper/ScopedUtfChars.h> 26 #include <string.h> 27 #include <sys/mman.h> 28 #include <sys/stat.h> 29 #include <sys/types.h> 30 #include <unistd.h> 31 32 const size_t kOffset = 4096; 33 34 // Verify that we can mmap a region of a file with a non-zero offset executable 35 static jboolean mmap_executable(JNIEnv *env, jobject, jstring jfilename) { 36 if (jfilename == NULL) { 37 jniThrowNullPointerException(env, NULL); 38 return false; 39 } 40 41 ScopedUtfChars filename(env, jfilename); 42 int fd = open(filename.c_str(), O_RDONLY); 43 if (fd == -1) { 44 ALOGE("open %s: %s", filename.c_str(), strerror(errno)); 45 return false; 46 } 47 48 struct stat stat_buf; 49 if (fstat(fd, &stat_buf) == -1) { 50 ALOGE("fstat %s: %s", filename.c_str(), strerror(errno)); 51 return false; 52 } 53 54 if (stat_buf.st_size < kOffset) { 55 ALOGE("file %s is too small", filename.c_str()); 56 return false; 57 } 58 59 void * mem = 60 mmap(NULL, stat_buf.st_size - kOffset, 61 PROT_EXEC | PROT_READ, MAP_PRIVATE, fd, kOffset); 62 if (mem == MAP_FAILED) { 63 ALOGE("mmap %s: %s", filename.c_str(), strerror(errno)); 64 return false; 65 } 66 67 if (munmap(mem, stat_buf.st_size - kOffset) == -1) { 68 ALOGE("munmap %s: %s", filename.c_str(), strerror(errno)); 69 return false; 70 } 71 72 return true; 73 } 74 75 static JNINativeMethod gMethods[] = { 76 { (char*)"mmapExecutable", 77 (char*)"(Ljava/lang/String;)Z", (void *)mmap_executable } 78 }; 79 80 int register_android_security_cts_MMapExecutableTest(JNIEnv* env) { 81 jclass clazz = env->FindClass("android/security/cts/MMapExecutableTest"); 82 return env->RegisterNatives( 83 clazz, gMethods, sizeof(gMethods) / sizeof(JNINativeMethod)); 84 } 85