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 #ifdef _PRC_COMPATIBILITY_PACKAGE_
42 #include "abipicker/ABIPicker.h"
45 #define APK_LIB "lib/"
46 #define APK_LIB_LEN (sizeof(APK_LIB) - 1)
48 #define LIB_PREFIX "/lib"
49 #define LIB_PREFIX_LEN (sizeof(LIB_PREFIX) - 1)
51 #define LIB_SUFFIX ".so"
52 #define LIB_SUFFIX_LEN (sizeof(LIB_SUFFIX) - 1)
54 #define RS_BITCODE_SUFFIX ".bc"
56 #define TMP_FILE_PATTERN "/tmp.XXXXXX"
57 #define TMP_FILE_PATTERN_LEN (sizeof(TMP_FILE_PATTERN) - 1)
59 #ifdef _PRC_COMPATIBILITY_PACKAGE_
61 #define X8664ABI "x86_64"
66 // These match PackageManager.java install codes
67 enum install_status_t {
68 INSTALL_SUCCEEDED = 1,
69 INSTALL_FAILED_INVALID_APK = -2,
70 INSTALL_FAILED_INSUFFICIENT_STORAGE = -4,
71 INSTALL_FAILED_CONTAINER_ERROR = -18,
72 INSTALL_FAILED_INTERNAL_ERROR = -110,
73 INSTALL_FAILED_NO_MATCHING_ABIS = -113,
74 NO_NATIVE_LIBRARIES = -114
77 typedef install_status_t (*iterFunc)(JNIEnv*, void*, ZipFileRO*, ZipEntryRO, const char*);
79 // Equivalent to android.os.FileUtils.isFilenameSafe
81 isFilenameSafe(const char* filename)
85 switch (*(filename + offset)) {
88 // If we've reached the end, all the other characters are good.
105 // We found something that is not good.
109 // Should not reach here.
113 isFileDifferent(const char* filePath, uint32_t fileSize, time_t modifiedTime,
114 uint32_t zipCrc, struct stat64* st)
116 if (lstat64(filePath, st) < 0) {
117 // File is not found or cannot be read.
118 ALOGV("Couldn't stat %s, copying: %s\n", filePath, strerror(errno));
122 if (!S_ISREG(st->st_mode)) {
126 if (static_cast<uint64_t>(st->st_size) != static_cast<uint64_t>(fileSize)) {
130 // For some reason, bionic doesn't define st_mtime as time_t
131 if (time_t(st->st_mtime) != modifiedTime) {
132 ALOGV("mod time doesn't match: %ld vs. %ld\n", st->st_mtime, modifiedTime);
136 int fd = TEMP_FAILURE_RETRY(open(filePath, O_RDONLY));
138 ALOGV("Couldn't open file %s: %s", filePath, strerror(errno));
142 // uLong comes from zlib.h. It's a bit of a wart that they're
143 // potentially using a 64-bit type for a 32-bit CRC.
144 uLong crc = crc32(0L, Z_NULL, 0);
145 unsigned char crcBuffer[16384];
147 while ((numBytes = TEMP_FAILURE_RETRY(read(fd, crcBuffer, sizeof(crcBuffer)))) > 0) {
148 crc = crc32(crc, crcBuffer, numBytes);
152 ALOGV("%s: crc = %lx, zipCrc = %" PRIu32 "\n", filePath, crc, zipCrc);
154 if (crc != static_cast<uLong>(zipCrc)) {
161 static install_status_t
162 sumFiles(JNIEnv*, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char*)
164 size_t* total = (size_t*) arg;
167 if (!zipFile->getEntryInfo(zipEntry, NULL, &uncompLen, NULL, NULL, NULL, NULL)) {
168 return INSTALL_FAILED_INVALID_APK;
171 *total += static_cast<size_t>(uncompLen);
173 return INSTALL_SUCCEEDED;
177 * Copy the native library if needed.
179 * This function assumes the library and path names passed in are considered safe.
181 static install_status_t
182 copyFileIfChanged(JNIEnv *env, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char* fileName)
184 void** args = reinterpret_cast<void**>(arg);
185 jstring* javaNativeLibPath = (jstring*) args[0];
186 jboolean extractNativeLibs = *(jboolean*) args[1];
187 jboolean hasNativeBridge = *(jboolean*) args[2];
189 ScopedUtfChars nativeLibPath(env, *javaNativeLibPath);
198 if (!zipFile->getEntryInfo(zipEntry, &method, &uncompLen, NULL, &offset, &when, &crc)) {
199 ALOGD("Couldn't read zip entry info\n");
200 return INSTALL_FAILED_INVALID_APK;
203 if (!extractNativeLibs) {
204 // check if library is uncompressed and page-aligned
205 if (method != ZipFileRO::kCompressStored) {
206 ALOGD("Library '%s' is compressed - will not be able to open it directly from apk.\n",
208 return INSTALL_FAILED_INVALID_APK;
211 if (offset % PAGE_SIZE != 0) {
212 ALOGD("Library '%s' is not page-aligned - will not be able to open it directly from"
213 " apk.\n", fileName);
214 return INSTALL_FAILED_INVALID_APK;
217 if (!hasNativeBridge) {
218 return INSTALL_SUCCEEDED;
222 // Build local file path
223 const size_t fileNameLen = strlen(fileName);
224 char localFileName[nativeLibPath.size() + fileNameLen + 2];
226 if (strlcpy(localFileName, nativeLibPath.c_str(), sizeof(localFileName)) != nativeLibPath.size()) {
227 ALOGD("Couldn't allocate local file name for library");
228 return INSTALL_FAILED_INTERNAL_ERROR;
231 *(localFileName + nativeLibPath.size()) = '/';
233 if (strlcpy(localFileName + nativeLibPath.size() + 1, fileName, sizeof(localFileName)
234 - nativeLibPath.size() - 1) != fileNameLen) {
235 ALOGD("Couldn't allocate local file name for library");
236 return INSTALL_FAILED_INTERNAL_ERROR;
239 // Only copy out the native file if it's different.
241 ZipUtils::zipTimeToTimespec(when, &t);
242 const time_t modTime = mktime(&t);
244 if (!isFileDifferent(localFileName, uncompLen, modTime, crc, &st)) {
245 return INSTALL_SUCCEEDED;
248 char localTmpFileName[nativeLibPath.size() + TMP_FILE_PATTERN_LEN + 2];
249 if (strlcpy(localTmpFileName, nativeLibPath.c_str(), sizeof(localTmpFileName))
250 != nativeLibPath.size()) {
251 ALOGD("Couldn't allocate local file name for library");
252 return INSTALL_FAILED_INTERNAL_ERROR;
255 *(localTmpFileName + nativeLibPath.size()) = '/';
257 if (strlcpy(localTmpFileName + nativeLibPath.size(), TMP_FILE_PATTERN,
258 TMP_FILE_PATTERN_LEN - nativeLibPath.size()) != TMP_FILE_PATTERN_LEN) {
259 ALOGI("Couldn't allocate temporary file name for library");
260 return INSTALL_FAILED_INTERNAL_ERROR;
263 int fd = mkstemp(localTmpFileName);
265 ALOGI("Couldn't open temporary file name: %s: %s\n", localTmpFileName, strerror(errno));
266 return INSTALL_FAILED_CONTAINER_ERROR;
269 if (!zipFile->uncompressEntry(zipEntry, fd)) {
270 ALOGI("Failed uncompressing %s to %s\n", fileName, localTmpFileName);
272 unlink(localTmpFileName);
273 return INSTALL_FAILED_CONTAINER_ERROR;
278 // Set the modification time for this file to the ZIP's mod time.
279 struct timeval times[2];
280 times[0].tv_sec = st.st_atime;
281 times[1].tv_sec = modTime;
282 times[0].tv_usec = times[1].tv_usec = 0;
283 if (utimes(localTmpFileName, times) < 0) {
284 ALOGI("Couldn't change modification time on %s: %s\n", localTmpFileName, strerror(errno));
285 unlink(localTmpFileName);
286 return INSTALL_FAILED_CONTAINER_ERROR;
289 // Set the mode to 755
290 static const mode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
291 if (chmod(localTmpFileName, mode) < 0) {
292 ALOGI("Couldn't change permissions on %s: %s\n", localTmpFileName, strerror(errno));
293 unlink(localTmpFileName);
294 return INSTALL_FAILED_CONTAINER_ERROR;
297 // Finally, rename it to the final name.
298 if (rename(localTmpFileName, localFileName) < 0) {
299 ALOGI("Couldn't rename %s to %s: %s\n", localTmpFileName, localFileName, strerror(errno));
300 unlink(localTmpFileName);
301 return INSTALL_FAILED_CONTAINER_ERROR;
304 ALOGV("Successfully moved %s to %s\n", localTmpFileName, localFileName);
306 return INSTALL_SUCCEEDED;
310 * An iterator over all shared libraries in a zip file. An entry is
311 * considered to be a shared library if all of the conditions below are
314 * - The entry is under the lib/ directory.
315 * - The entry name ends with ".so" and the entry name starts with "lib",
316 * an exception is made for entries whose name is "gdbserver".
317 * - The entry filename is "safe" (as determined by isFilenameSafe).
320 class NativeLibrariesIterator {
322 NativeLibrariesIterator(ZipFileRO* zipFile, bool debuggable, void* cookie)
323 : mZipFile(zipFile), mDebuggable(debuggable), mCookie(cookie), mLastSlash(NULL) {
328 static NativeLibrariesIterator* create(ZipFileRO* zipFile, bool debuggable) {
330 // Do not specify a suffix to find both .so files and gdbserver.
331 if (!zipFile->startIteration(&cookie, APK_LIB, NULL /* suffix */)) {
335 return new NativeLibrariesIterator(zipFile, debuggable, cookie);
339 ZipEntryRO next = NULL;
340 while ((next = mZipFile->nextEntry(mCookie)) != NULL) {
341 // Make sure this entry has a filename.
342 if (mZipFile->getEntryFileName(next, fileName, sizeof(fileName))) {
346 // Make sure the filename is at least to the minimum library name size.
347 const size_t fileNameLen = strlen(fileName);
348 static const size_t minLength = APK_LIB_LEN + 2 + LIB_PREFIX_LEN + 1 + LIB_SUFFIX_LEN;
349 if (fileNameLen < minLength) {
353 const char* lastSlash = strrchr(fileName, '/');
354 ALOG_ASSERT(lastSlash != NULL, "last slash was null somehow for %s\n", fileName);
357 if (*(lastSlash + 1) == 0) {
361 // Make sure the filename is safe.
362 if (!isFilenameSafe(lastSlash + 1)) {
367 // Make sure the filename starts with lib and ends with ".so".
368 if (strncmp(fileName + fileNameLen - LIB_SUFFIX_LEN, LIB_SUFFIX, LIB_SUFFIX_LEN)
369 || strncmp(lastSlash, LIB_PREFIX, LIB_PREFIX_LEN)) {
374 mLastSlash = lastSlash;
381 inline const char* currentEntry() const {
385 inline const char* lastSlash() const {
389 virtual ~NativeLibrariesIterator() {
390 mZipFile->endIteration(mCookie);
394 char fileName[PATH_MAX];
395 ZipFileRO* const mZipFile;
396 const bool mDebuggable;
398 const char* mLastSlash;
401 static install_status_t
402 iterateOverNativeFiles(JNIEnv *env, jlong apkHandle, jstring javaCpuAbi,
403 jboolean debuggable, iterFunc callFunc, void* callArg) {
404 ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
405 if (zipFile == NULL) {
406 return INSTALL_FAILED_INVALID_APK;
409 std::unique_ptr<NativeLibrariesIterator> it(
410 NativeLibrariesIterator::create(zipFile, debuggable));
411 if (it.get() == NULL) {
412 return INSTALL_FAILED_INVALID_APK;
415 const ScopedUtfChars cpuAbi(env, javaCpuAbi);
416 if (cpuAbi.c_str() == NULL) {
417 // This would've thrown, so this return code isn't observable by
419 return INSTALL_FAILED_INVALID_APK;
421 ZipEntryRO entry = NULL;
422 while ((entry = it->next()) != NULL) {
423 const char* fileName = it->currentEntry();
424 const char* lastSlash = it->lastSlash();
426 // Check to make sure the CPU ABI of this file is one we support.
427 const char* cpuAbiOffset = fileName + APK_LIB_LEN;
428 const size_t cpuAbiRegionSize = lastSlash - cpuAbiOffset;
430 if (cpuAbi.size() == cpuAbiRegionSize && !strncmp(cpuAbiOffset, cpuAbi.c_str(), cpuAbiRegionSize)) {
431 install_status_t ret = callFunc(env, callArg, zipFile, entry, lastSlash + 1);
433 if (ret != INSTALL_SUCCEEDED) {
434 ALOGV("Failure for entry %s", lastSlash + 1);
440 return INSTALL_SUCCEEDED;
444 static int findSupportedAbi(JNIEnv *env, jlong apkHandle, jobjectArray supportedAbisArray,
445 jboolean debuggable) {
446 const int numAbis = env->GetArrayLength(supportedAbisArray);
447 Vector<ScopedUtfChars*> supportedAbis;
449 for (int i = 0; i < numAbis; ++i) {
450 supportedAbis.add(new ScopedUtfChars(env,
451 (jstring) env->GetObjectArrayElement(supportedAbisArray, i)));
454 ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
455 if (zipFile == NULL) {
456 return INSTALL_FAILED_INVALID_APK;
459 std::unique_ptr<NativeLibrariesIterator> it(
460 NativeLibrariesIterator::create(zipFile, debuggable));
461 if (it.get() == NULL) {
462 return INSTALL_FAILED_INVALID_APK;
465 ZipEntryRO entry = NULL;
466 int status = NO_NATIVE_LIBRARIES;
467 while ((entry = it->next()) != NULL) {
468 // We're currently in the lib/ directory of the APK, so it does have some native
469 // code. We should return INSTALL_FAILED_NO_MATCHING_ABIS if none of the
471 if (status == NO_NATIVE_LIBRARIES) {
472 status = INSTALL_FAILED_NO_MATCHING_ABIS;
475 const char* fileName = it->currentEntry();
476 const char* lastSlash = it->lastSlash();
478 // Check to see if this CPU ABI matches what we are looking for.
479 const char* abiOffset = fileName + APK_LIB_LEN;
480 const size_t abiSize = lastSlash - abiOffset;
481 for (int i = 0; i < numAbis; i++) {
482 const ScopedUtfChars* abi = supportedAbis[i];
483 if (abi->size() == abiSize && !strncmp(abiOffset, abi->c_str(), abiSize)) {
484 // The entry that comes in first (i.e. with a lower index) has the higher priority.
485 if (((i < status) && (status >= 0)) || (status < 0) ) {
492 for (int i = 0; i < numAbis; ++i) {
493 delete supportedAbis[i];
500 com_android_internal_content_NativeLibraryHelper_copyNativeBinaries(JNIEnv *env, jclass clazz,
501 jlong apkHandle, jstring javaNativeLibPath, jstring javaCpuAbi,
502 jboolean extractNativeLibs, jboolean hasNativeBridge, jboolean debuggable)
504 void* args[] = { &javaNativeLibPath, &extractNativeLibs, &hasNativeBridge };
505 return (jint) iterateOverNativeFiles(env, apkHandle, javaCpuAbi, debuggable,
506 copyFileIfChanged, reinterpret_cast<void*>(args));
510 com_android_internal_content_NativeLibraryHelper_sumNativeBinaries(JNIEnv *env, jclass clazz,
511 jlong apkHandle, jstring javaCpuAbi, jboolean debuggable)
513 size_t totalSize = 0;
515 iterateOverNativeFiles(env, apkHandle, javaCpuAbi, debuggable, sumFiles, &totalSize);
521 com_android_internal_content_NativeLibraryHelper_findSupportedAbi_replace(
525 jobjectArray javaCpuAbisToSearch,
530 #ifdef _PRC_COMPATIBILITY_PACKAGE_
532 int abiType = findSupportedAbi(env, apkHandle, javaCpuAbisToSearch, debuggable);
533 if (apkDir == NULL) {
534 return (jint)abiType;
537 char abiFlag[256] = {'\0'};
538 ScopedUtfChars apkdir(env, apkDir);
539 size_t apkdir_size = apkdir.size();
540 const int numAbis = env->GetArrayLength(javaCpuAbisToSearch);
541 Vector<ScopedUtfChars*> supportedAbis;
543 assert(apkdir_size < 256 - 15);
544 if (strlcpy(abiFlag, apkdir.c_str(), 256) != apkdir.size()) {
545 return (jint)abiType;
549 abiFlag[apkdir_size] = '/';
550 abiFlag[apkdir_size + 1] = '.';
551 for (abiIndex = 0; abiIndex < numAbis; abiIndex++) {
552 ScopedUtfChars* abiName = new ScopedUtfChars(env,
553 (jstring)env->GetObjectArrayElement(javaCpuAbisToSearch, abiIndex));
554 supportedAbis.push_back(abiName);
555 if (abiName == NULL || abiName->c_str() == NULL || abiName->size() <= 0) {
558 if ((strlcpy(abiFlag + apkdir_size + 2, abiName->c_str(), 256 - apkdir_size - 2)
559 == abiName->size()) && (access(abiFlag, F_OK) == 0)) {
565 if (abiIndex < numAbis) {
566 for (int j = 0; j < abiIndex; ++j) {
567 if (supportedAbis[j] != NULL) {
568 delete supportedAbis[j];
571 return (jint)abiType;
575 if (abiType < 0 || abiType >= numAbis) {
579 if (0 != strcmp(supportedAbis[abiType]->c_str(), X86ABI) &&
580 0 != strcmp(supportedAbis[abiType]->c_str(), X8664ABI)) {
584 ScopedUtfChars name(env, apkPkgName);
585 if (NULL == name.c_str()) {
589 if (isInOEMWhiteList(name.c_str())) {
593 ABIPicker picker(name.c_str(),supportedAbis);
594 if (!picker.buildNativeLibList((void*)apkHandle)) {
598 abiType = picker.pickupRightABI(abiType);
599 if (abiType >= 0 && abiType < numAbis &&
600 (strlcpy(abiFlag + apkdir_size + 2, supportedAbis[abiType]->c_str(),
601 256 - apkdir_size - 2) == supportedAbis[abiType]->size())) {
602 int flagFp = creat(abiFlag, 0644);
610 for (int i = 0; i < numAbis; ++i) {
611 delete supportedAbis[i];
613 return (jint)abiType;
615 return (jint)findSupportedAbi(env, apkHandle, javaCpuAbisToSearch, debuggable);
619 enum bitcode_scan_result_t {
621 NO_BITCODE_PRESENT = 0,
626 com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode(JNIEnv *env, jclass clazz,
628 ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
630 if (!zipFile->startIteration(&cookie, NULL /* prefix */, RS_BITCODE_SUFFIX)) {
631 return APK_SCAN_ERROR;
634 char fileName[PATH_MAX];
635 ZipEntryRO next = NULL;
636 while ((next = zipFile->nextEntry(cookie)) != NULL) {
637 if (zipFile->getEntryFileName(next, fileName, sizeof(fileName))) {
640 const char* lastSlash = strrchr(fileName, '/');
641 const char* baseName = (lastSlash == NULL) ? fileName : fileName + 1;
642 if (isFilenameSafe(baseName)) {
643 zipFile->endIteration(cookie);
644 return BITCODE_PRESENT;
648 zipFile->endIteration(cookie);
649 return NO_BITCODE_PRESENT;
653 com_android_internal_content_NativeLibraryHelper_openApk(JNIEnv *env, jclass, jstring apkPath)
655 ScopedUtfChars filePath(env, apkPath);
656 ZipFileRO* zipFile = ZipFileRO::open(filePath.c_str());
658 return reinterpret_cast<jlong>(zipFile);
662 com_android_internal_content_NativeLibraryHelper_close(JNIEnv *env, jclass, jlong apkHandle)
664 delete reinterpret_cast<ZipFileRO*>(apkHandle);
667 static const JNINativeMethod gMethods[] = {
669 "(Ljava/lang/String;)J",
670 (void *)com_android_internal_content_NativeLibraryHelper_openApk},
673 (void *)com_android_internal_content_NativeLibraryHelper_close},
674 {"nativeCopyNativeBinaries",
675 "(JLjava/lang/String;Ljava/lang/String;ZZZ)I",
676 (void *)com_android_internal_content_NativeLibraryHelper_copyNativeBinaries},
677 {"nativeSumNativeBinaries",
678 "(JLjava/lang/String;Z)J",
679 (void *)com_android_internal_content_NativeLibraryHelper_sumNativeBinaries},
680 {"nativeFindSupportedAbiReplace",
681 "(J[Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)I",
682 (void *)com_android_internal_content_NativeLibraryHelper_findSupportedAbi_replace},
683 {"hasRenderscriptBitcode", "(J)I",
684 (void *)com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode},
688 int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env)
690 return RegisterMethodsOrDie(env,
691 "com/android/internal/content/NativeLibraryHelper", gMethods, NELEM(gMethods));