2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "NativeLibraryHelper"
18 //#define LOG_NDEBUG 0
20 #include "core_jni_helpers.h"
22 #include <nativehelper/ScopedUtfChars.h>
23 #include <androidfw/ZipFileRO.h>
24 #include <androidfw/ZipUtils.h>
25 #include <utils/Log.h>
26 #include <utils/Vector.h>
37 #include <sys/types.h>
41 #define APK_LIB "lib/"
42 #define APK_LIB_LEN (sizeof(APK_LIB) - 1)
44 #define LIB_PREFIX "/lib"
45 #define LIB_PREFIX_LEN (sizeof(LIB_PREFIX) - 1)
47 #define LIB_SUFFIX ".so"
48 #define LIB_SUFFIX_LEN (sizeof(LIB_SUFFIX) - 1)
50 #define RS_BITCODE_SUFFIX ".bc"
52 #define TMP_FILE_PATTERN "/tmp.XXXXXX"
53 #define TMP_FILE_PATTERN_LEN (sizeof(TMP_FILE_PATTERN) - 1)
57 // These match PackageManager.java install codes
58 enum install_status_t {
59 INSTALL_SUCCEEDED = 1,
60 INSTALL_FAILED_INVALID_APK = -2,
61 INSTALL_FAILED_INSUFFICIENT_STORAGE = -4,
62 INSTALL_FAILED_CONTAINER_ERROR = -18,
63 INSTALL_FAILED_INTERNAL_ERROR = -110,
64 INSTALL_FAILED_NO_MATCHING_ABIS = -113,
65 NO_NATIVE_LIBRARIES = -114
68 typedef install_status_t (*iterFunc)(JNIEnv*, void*, ZipFileRO*, ZipEntryRO, const char*);
70 // Equivalent to android.os.FileUtils.isFilenameSafe
72 isFilenameSafe(const char* filename)
76 switch (*(filename + offset)) {
79 // If we've reached the end, all the other characters are good.
96 // We found something that is not good.
100 // Should not reach here.
104 isFileDifferent(const char* filePath, uint32_t fileSize, time_t modifiedTime,
105 uint32_t zipCrc, struct stat64* st)
107 if (lstat64(filePath, st) < 0) {
108 // File is not found or cannot be read.
109 ALOGV("Couldn't stat %s, copying: %s\n", filePath, strerror(errno));
113 if (!S_ISREG(st->st_mode)) {
117 if (static_cast<uint64_t>(st->st_size) != static_cast<uint64_t>(fileSize)) {
121 // For some reason, bionic doesn't define st_mtime as time_t
122 if (time_t(st->st_mtime) != modifiedTime) {
123 ALOGV("mod time doesn't match: %ld vs. %ld\n", st->st_mtime, modifiedTime);
127 int fd = TEMP_FAILURE_RETRY(open(filePath, O_RDONLY));
129 ALOGV("Couldn't open file %s: %s", filePath, strerror(errno));
133 // uLong comes from zlib.h. It's a bit of a wart that they're
134 // potentially using a 64-bit type for a 32-bit CRC.
135 uLong crc = crc32(0L, Z_NULL, 0);
136 unsigned char crcBuffer[16384];
138 while ((numBytes = TEMP_FAILURE_RETRY(read(fd, crcBuffer, sizeof(crcBuffer)))) > 0) {
139 crc = crc32(crc, crcBuffer, numBytes);
143 ALOGV("%s: crc = %lx, zipCrc = %" PRIu32 "\n", filePath, crc, zipCrc);
145 if (crc != static_cast<uLong>(zipCrc)) {
152 static install_status_t
153 sumFiles(JNIEnv*, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char*)
155 size_t* total = (size_t*) arg;
158 if (!zipFile->getEntryInfo(zipEntry, NULL, &uncompLen, NULL, NULL, NULL, NULL)) {
159 return INSTALL_FAILED_INVALID_APK;
162 *total += static_cast<size_t>(uncompLen);
164 return INSTALL_SUCCEEDED;
168 * Copy the native library if needed.
170 * This function assumes the library and path names passed in are considered safe.
172 static install_status_t
173 copyFileIfChanged(JNIEnv *env, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char* fileName)
175 void** args = reinterpret_cast<void**>(arg);
176 jstring* javaNativeLibPath = (jstring*) args[0];
177 jboolean extractNativeLibs = *(jboolean*) args[1];
178 jboolean hasNativeBridge = *(jboolean*) args[2];
180 ScopedUtfChars nativeLibPath(env, *javaNativeLibPath);
189 if (!zipFile->getEntryInfo(zipEntry, &method, &uncompLen, NULL, &offset, &when, &crc)) {
190 ALOGD("Couldn't read zip entry info\n");
191 return INSTALL_FAILED_INVALID_APK;
194 if (!extractNativeLibs) {
195 // check if library is uncompressed and page-aligned
196 if (method != ZipFileRO::kCompressStored) {
197 ALOGD("Library '%s' is compressed - will not be able to open it directly from apk.\n",
199 return INSTALL_FAILED_INVALID_APK;
202 if (offset % PAGE_SIZE != 0) {
203 ALOGD("Library '%s' is not page-aligned - will not be able to open it directly from"
204 " apk.\n", fileName);
205 return INSTALL_FAILED_INVALID_APK;
208 if (!hasNativeBridge) {
209 return INSTALL_SUCCEEDED;
213 // Build local file path
214 const size_t fileNameLen = strlen(fileName);
215 char localFileName[nativeLibPath.size() + fileNameLen + 2];
217 if (strlcpy(localFileName, nativeLibPath.c_str(), sizeof(localFileName)) != nativeLibPath.size()) {
218 ALOGD("Couldn't allocate local file name for library");
219 return INSTALL_FAILED_INTERNAL_ERROR;
222 *(localFileName + nativeLibPath.size()) = '/';
224 if (strlcpy(localFileName + nativeLibPath.size() + 1, fileName, sizeof(localFileName)
225 - nativeLibPath.size() - 1) != fileNameLen) {
226 ALOGD("Couldn't allocate local file name for library");
227 return INSTALL_FAILED_INTERNAL_ERROR;
230 // Only copy out the native file if it's different.
232 ZipUtils::zipTimeToTimespec(when, &t);
233 const time_t modTime = mktime(&t);
235 if (!isFileDifferent(localFileName, uncompLen, modTime, crc, &st)) {
236 return INSTALL_SUCCEEDED;
239 char localTmpFileName[nativeLibPath.size() + TMP_FILE_PATTERN_LEN + 2];
240 if (strlcpy(localTmpFileName, nativeLibPath.c_str(), sizeof(localTmpFileName))
241 != nativeLibPath.size()) {
242 ALOGD("Couldn't allocate local file name for library");
243 return INSTALL_FAILED_INTERNAL_ERROR;
246 *(localTmpFileName + nativeLibPath.size()) = '/';
248 if (strlcpy(localTmpFileName + nativeLibPath.size(), TMP_FILE_PATTERN,
249 TMP_FILE_PATTERN_LEN - nativeLibPath.size()) != TMP_FILE_PATTERN_LEN) {
250 ALOGI("Couldn't allocate temporary file name for library");
251 return INSTALL_FAILED_INTERNAL_ERROR;
254 int fd = mkstemp(localTmpFileName);
256 ALOGI("Couldn't open temporary file name: %s: %s\n", localTmpFileName, strerror(errno));
257 return INSTALL_FAILED_CONTAINER_ERROR;
260 if (!zipFile->uncompressEntry(zipEntry, fd)) {
261 ALOGI("Failed uncompressing %s to %s\n", fileName, localTmpFileName);
263 unlink(localTmpFileName);
264 return INSTALL_FAILED_CONTAINER_ERROR;
269 // Set the modification time for this file to the ZIP's mod time.
270 struct timeval times[2];
271 times[0].tv_sec = st.st_atime;
272 times[1].tv_sec = modTime;
273 times[0].tv_usec = times[1].tv_usec = 0;
274 if (utimes(localTmpFileName, times) < 0) {
275 ALOGI("Couldn't change modification time on %s: %s\n", localTmpFileName, strerror(errno));
276 unlink(localTmpFileName);
277 return INSTALL_FAILED_CONTAINER_ERROR;
280 // Set the mode to 755
281 static const mode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
282 if (chmod(localTmpFileName, mode) < 0) {
283 ALOGI("Couldn't change permissions on %s: %s\n", localTmpFileName, strerror(errno));
284 unlink(localTmpFileName);
285 return INSTALL_FAILED_CONTAINER_ERROR;
288 // Finally, rename it to the final name.
289 if (rename(localTmpFileName, localFileName) < 0) {
290 ALOGI("Couldn't rename %s to %s: %s\n", localTmpFileName, localFileName, strerror(errno));
291 unlink(localTmpFileName);
292 return INSTALL_FAILED_CONTAINER_ERROR;
295 ALOGV("Successfully moved %s to %s\n", localTmpFileName, localFileName);
297 return INSTALL_SUCCEEDED;
301 * An iterator over all shared libraries in a zip file. An entry is
302 * considered to be a shared library if all of the conditions below are
305 * - The entry is under the lib/ directory.
306 * - The entry name ends with ".so" and the entry name starts with "lib",
307 * an exception is made for entries whose name is "gdbserver".
308 * - The entry filename is "safe" (as determined by isFilenameSafe).
311 class NativeLibrariesIterator {
313 NativeLibrariesIterator(ZipFileRO* zipFile, bool debuggable, void* cookie)
314 : mZipFile(zipFile), mDebuggable(debuggable), mCookie(cookie), mLastSlash(NULL) {
319 static NativeLibrariesIterator* create(ZipFileRO* zipFile, bool debuggable) {
321 // Do not specify a suffix to find both .so files and gdbserver.
322 if (!zipFile->startIteration(&cookie, APK_LIB, NULL /* suffix */)) {
326 return new NativeLibrariesIterator(zipFile, debuggable, cookie);
330 ZipEntryRO next = NULL;
331 while ((next = mZipFile->nextEntry(mCookie)) != NULL) {
332 // Make sure this entry has a filename.
333 if (mZipFile->getEntryFileName(next, fileName, sizeof(fileName))) {
337 // Make sure the filename is at least to the minimum library name size.
338 const size_t fileNameLen = strlen(fileName);
339 static const size_t minLength = APK_LIB_LEN + 2 + LIB_PREFIX_LEN + 1 + LIB_SUFFIX_LEN;
340 if (fileNameLen < minLength) {
344 const char* lastSlash = strrchr(fileName, '/');
345 ALOG_ASSERT(lastSlash != NULL, "last slash was null somehow for %s\n", fileName);
348 if (*(lastSlash + 1) == 0) {
352 // Make sure the filename is safe.
353 if (!isFilenameSafe(lastSlash + 1)) {
358 // Make sure the filename starts with lib and ends with ".so".
359 if (strncmp(fileName + fileNameLen - LIB_SUFFIX_LEN, LIB_SUFFIX, LIB_SUFFIX_LEN)
360 || strncmp(lastSlash, LIB_PREFIX, LIB_PREFIX_LEN)) {
365 mLastSlash = lastSlash;
372 inline const char* currentEntry() const {
376 inline const char* lastSlash() const {
380 virtual ~NativeLibrariesIterator() {
381 mZipFile->endIteration(mCookie);
385 char fileName[PATH_MAX];
386 ZipFileRO* const mZipFile;
387 const bool mDebuggable;
389 const char* mLastSlash;
392 static install_status_t
393 iterateOverNativeFiles(JNIEnv *env, jlong apkHandle, jstring javaCpuAbi,
394 jboolean debuggable, iterFunc callFunc, void* callArg) {
395 ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
396 if (zipFile == NULL) {
397 return INSTALL_FAILED_INVALID_APK;
400 std::unique_ptr<NativeLibrariesIterator> it(
401 NativeLibrariesIterator::create(zipFile, debuggable));
402 if (it.get() == NULL) {
403 return INSTALL_FAILED_INVALID_APK;
406 const ScopedUtfChars cpuAbi(env, javaCpuAbi);
407 if (cpuAbi.c_str() == NULL) {
408 // This would've thrown, so this return code isn't observable by
410 return INSTALL_FAILED_INVALID_APK;
412 ZipEntryRO entry = NULL;
413 while ((entry = it->next()) != NULL) {
414 const char* fileName = it->currentEntry();
415 const char* lastSlash = it->lastSlash();
417 // Check to make sure the CPU ABI of this file is one we support.
418 const char* cpuAbiOffset = fileName + APK_LIB_LEN;
419 const size_t cpuAbiRegionSize = lastSlash - cpuAbiOffset;
421 if (cpuAbi.size() == cpuAbiRegionSize && !strncmp(cpuAbiOffset, cpuAbi.c_str(), cpuAbiRegionSize)) {
422 install_status_t ret = callFunc(env, callArg, zipFile, entry, lastSlash + 1);
424 if (ret != INSTALL_SUCCEEDED) {
425 ALOGV("Failure for entry %s", lastSlash + 1);
431 return INSTALL_SUCCEEDED;
435 static int findSupportedAbi(JNIEnv *env, jlong apkHandle, jobjectArray supportedAbisArray,
436 jboolean debuggable) {
437 const int numAbis = env->GetArrayLength(supportedAbisArray);
438 Vector<ScopedUtfChars*> supportedAbis;
440 for (int i = 0; i < numAbis; ++i) {
441 supportedAbis.add(new ScopedUtfChars(env,
442 (jstring) env->GetObjectArrayElement(supportedAbisArray, i)));
445 ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
446 if (zipFile == NULL) {
447 return INSTALL_FAILED_INVALID_APK;
450 std::unique_ptr<NativeLibrariesIterator> it(
451 NativeLibrariesIterator::create(zipFile, debuggable));
452 if (it.get() == NULL) {
453 return INSTALL_FAILED_INVALID_APK;
456 ZipEntryRO entry = NULL;
457 int status = NO_NATIVE_LIBRARIES;
458 while ((entry = it->next()) != NULL) {
459 // We're currently in the lib/ directory of the APK, so it does have some native
460 // code. We should return INSTALL_FAILED_NO_MATCHING_ABIS if none of the
462 if (status == NO_NATIVE_LIBRARIES) {
463 status = INSTALL_FAILED_NO_MATCHING_ABIS;
466 const char* fileName = it->currentEntry();
467 const char* lastSlash = it->lastSlash();
469 // Check to see if this CPU ABI matches what we are looking for.
470 const char* abiOffset = fileName + APK_LIB_LEN;
471 const size_t abiSize = lastSlash - abiOffset;
472 for (int i = 0; i < numAbis; i++) {
473 const ScopedUtfChars* abi = supportedAbis[i];
474 if (abi->size() == abiSize && !strncmp(abiOffset, abi->c_str(), abiSize)) {
475 // The entry that comes in first (i.e. with a lower index) has the higher priority.
476 if (((i < status) && (status >= 0)) || (status < 0) ) {
483 for (int i = 0; i < numAbis; ++i) {
484 delete supportedAbis[i];
491 com_android_internal_content_NativeLibraryHelper_copyNativeBinaries(JNIEnv *env, jclass clazz,
492 jlong apkHandle, jstring javaNativeLibPath, jstring javaCpuAbi,
493 jboolean extractNativeLibs, jboolean hasNativeBridge, jboolean debuggable)
495 void* args[] = { &javaNativeLibPath, &extractNativeLibs, &hasNativeBridge };
496 return (jint) iterateOverNativeFiles(env, apkHandle, javaCpuAbi, debuggable,
497 copyFileIfChanged, reinterpret_cast<void*>(args));
501 com_android_internal_content_NativeLibraryHelper_sumNativeBinaries(JNIEnv *env, jclass clazz,
502 jlong apkHandle, jstring javaCpuAbi, jboolean debuggable)
504 size_t totalSize = 0;
506 iterateOverNativeFiles(env, apkHandle, javaCpuAbi, debuggable, sumFiles, &totalSize);
512 com_android_internal_content_NativeLibraryHelper_findSupportedAbi(JNIEnv *env, jclass clazz,
513 jlong apkHandle, jobjectArray javaCpuAbisToSearch, jboolean debuggable)
515 return (jint) findSupportedAbi(env, apkHandle, javaCpuAbisToSearch, debuggable);
518 enum bitcode_scan_result_t {
520 NO_BITCODE_PRESENT = 0,
525 com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode(JNIEnv *env, jclass clazz,
527 ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
529 if (!zipFile->startIteration(&cookie, NULL /* prefix */, RS_BITCODE_SUFFIX)) {
530 return APK_SCAN_ERROR;
533 char fileName[PATH_MAX];
534 ZipEntryRO next = NULL;
535 while ((next = zipFile->nextEntry(cookie)) != NULL) {
536 if (zipFile->getEntryFileName(next, fileName, sizeof(fileName))) {
539 const char* lastSlash = strrchr(fileName, '/');
540 const char* baseName = (lastSlash == NULL) ? fileName : fileName + 1;
541 if (isFilenameSafe(baseName)) {
542 zipFile->endIteration(cookie);
543 return BITCODE_PRESENT;
547 zipFile->endIteration(cookie);
548 return NO_BITCODE_PRESENT;
552 com_android_internal_content_NativeLibraryHelper_openApk(JNIEnv *env, jclass, jstring apkPath)
554 ScopedUtfChars filePath(env, apkPath);
555 ZipFileRO* zipFile = ZipFileRO::open(filePath.c_str());
557 return reinterpret_cast<jlong>(zipFile);
561 com_android_internal_content_NativeLibraryHelper_close(JNIEnv *env, jclass, jlong apkHandle)
563 delete reinterpret_cast<ZipFileRO*>(apkHandle);
566 static const JNINativeMethod gMethods[] = {
568 "(Ljava/lang/String;)J",
569 (void *)com_android_internal_content_NativeLibraryHelper_openApk},
572 (void *)com_android_internal_content_NativeLibraryHelper_close},
573 {"nativeCopyNativeBinaries",
574 "(JLjava/lang/String;Ljava/lang/String;ZZZ)I",
575 (void *)com_android_internal_content_NativeLibraryHelper_copyNativeBinaries},
576 {"nativeSumNativeBinaries",
577 "(JLjava/lang/String;Z)J",
578 (void *)com_android_internal_content_NativeLibraryHelper_sumNativeBinaries},
579 {"nativeFindSupportedAbi",
580 "(J[Ljava/lang/String;Z)I",
581 (void *)com_android_internal_content_NativeLibraryHelper_findSupportedAbi},
582 {"hasRenderscriptBitcode", "(J)I",
583 (void *)com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode},
587 int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env)
589 return RegisterMethodsOrDie(env,
590 "com/android/internal/content/NativeLibraryHelper", gMethods, NELEM(gMethods));