com_android_internal_content_NativeLibraryHelper.cpp revision d47e38b6342fea93b007319431634a4bcfee452c
1/*
2 * Copyright (C) 2011 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#define LOG_TAG "NativeLibraryHelper"
18//#define LOG_NDEBUG 0
19
20#include <android_runtime/AndroidRuntime.h>
21
22#include <ScopedUtfChars.h>
23#include <UniquePtr.h>
24#include <androidfw/ZipFileRO.h>
25#include <androidfw/ZipUtils.h>
26#include <utils/Log.h>
27#include <utils/Vector.h>
28
29#include <zlib.h>
30
31#include <fcntl.h>
32#include <stdlib.h>
33#include <string.h>
34#include <time.h>
35#include <unistd.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38
39
40#define APK_LIB "lib/"
41#define APK_LIB_LEN (sizeof(APK_LIB) - 1)
42
43#define LIB_PREFIX "/lib"
44#define LIB_PREFIX_LEN (sizeof(LIB_PREFIX) - 1)
45
46#define LIB_SUFFIX ".so"
47#define LIB_SUFFIX_LEN (sizeof(LIB_SUFFIX) - 1)
48
49#define RS_BITCODE_SUFFIX ".bc"
50#define RS_BITCODE_SUFFIX_LEN (sizeof(RS_BITCODE_SUFFIX) -1)
51
52#define GDBSERVER "gdbserver"
53#define GDBSERVER_LEN (sizeof(GDBSERVER) - 1)
54
55#define TMP_FILE_PATTERN "/tmp.XXXXXX"
56#define TMP_FILE_PATTERN_LEN (sizeof(TMP_FILE_PATTERN) - 1)
57
58namespace android {
59
60// These match PackageManager.java install codes
61enum install_status_t {
62    INSTALL_SUCCEEDED = 1,
63    INSTALL_FAILED_INVALID_APK = -2,
64    INSTALL_FAILED_INSUFFICIENT_STORAGE = -4,
65    INSTALL_FAILED_CONTAINER_ERROR = -18,
66    INSTALL_FAILED_INTERNAL_ERROR = -110,
67    INSTALL_FAILED_NO_MATCHING_ABIS = -112,
68    NO_NATIVE_LIBRARIES = -113
69};
70
71typedef install_status_t (*iterFunc)(JNIEnv*, void*, ZipFileRO*, ZipEntryRO, const char*);
72
73// Equivalent to android.os.FileUtils.isFilenameSafe
74static bool
75isFilenameSafe(const char* filename)
76{
77    off_t offset = 0;
78    for (;;) {
79        switch (*(filename + offset)) {
80        case 0:
81            // Null.
82            // If we've reached the end, all the other characters are good.
83            return true;
84
85        case 'A' ... 'Z':
86        case 'a' ... 'z':
87        case '0' ... '9':
88        case '+':
89        case ',':
90        case '-':
91        case '.':
92        case '/':
93        case '=':
94        case '_':
95            offset++;
96            break;
97
98        default:
99            // We found something that is not good.
100            return false;
101        }
102    }
103    // Should not reach here.
104}
105
106static bool
107isFileDifferent(const char* filePath, size_t fileSize, time_t modifiedTime,
108        long zipCrc, struct stat64* st)
109{
110    if (lstat64(filePath, st) < 0) {
111        // File is not found or cannot be read.
112        ALOGV("Couldn't stat %s, copying: %s\n", filePath, strerror(errno));
113        return true;
114    }
115
116    if (!S_ISREG(st->st_mode)) {
117        return true;
118    }
119
120    if (st->st_size != fileSize) {
121        return true;
122    }
123
124    // For some reason, bionic doesn't define st_mtime as time_t
125    if (time_t(st->st_mtime) != modifiedTime) {
126        ALOGV("mod time doesn't match: %ld vs. %ld\n", st->st_mtime, modifiedTime);
127        return true;
128    }
129
130    int fd = TEMP_FAILURE_RETRY(open(filePath, O_RDONLY));
131    if (fd < 0) {
132        ALOGV("Couldn't open file %s: %s", filePath, strerror(errno));
133        return true;
134    }
135
136    long crc = crc32(0L, Z_NULL, 0);
137    unsigned char crcBuffer[16384];
138    ssize_t numBytes;
139    while ((numBytes = TEMP_FAILURE_RETRY(read(fd, crcBuffer, sizeof(crcBuffer)))) > 0) {
140        crc = crc32(crc, crcBuffer, numBytes);
141    }
142    close(fd);
143
144    ALOGV("%s: crc = %lx, zipCrc = %lx\n", filePath, crc, zipCrc);
145
146    if (crc != zipCrc) {
147        return true;
148    }
149
150    return false;
151}
152
153static install_status_t
154sumFiles(JNIEnv*, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char*)
155{
156    size_t* total = (size_t*) arg;
157    size_t uncompLen;
158
159    if (!zipFile->getEntryInfo(zipEntry, NULL, &uncompLen, NULL, NULL, NULL, NULL)) {
160        return INSTALL_FAILED_INVALID_APK;
161    }
162
163    *total += uncompLen;
164
165    return INSTALL_SUCCEEDED;
166}
167
168/*
169 * Copy the native library if needed.
170 *
171 * This function assumes the library and path names passed in are considered safe.
172 */
173static install_status_t
174copyFileIfChanged(JNIEnv *env, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char* fileName)
175{
176    jstring* javaNativeLibPath = (jstring*) arg;
177    ScopedUtfChars nativeLibPath(env, *javaNativeLibPath);
178
179    size_t uncompLen;
180    long when;
181    long crc;
182    time_t modTime;
183
184    if (!zipFile->getEntryInfo(zipEntry, NULL, &uncompLen, NULL, NULL, &when, &crc)) {
185        ALOGD("Couldn't read zip entry info\n");
186        return INSTALL_FAILED_INVALID_APK;
187    } else {
188        struct tm t;
189        ZipUtils::zipTimeToTimespec(when, &t);
190        modTime = mktime(&t);
191    }
192
193    // Build local file path
194    const size_t fileNameLen = strlen(fileName);
195    char localFileName[nativeLibPath.size() + fileNameLen + 2];
196
197    if (strlcpy(localFileName, nativeLibPath.c_str(), sizeof(localFileName)) != nativeLibPath.size()) {
198        ALOGD("Couldn't allocate local file name for library");
199        return INSTALL_FAILED_INTERNAL_ERROR;
200    }
201
202    *(localFileName + nativeLibPath.size()) = '/';
203
204    if (strlcpy(localFileName + nativeLibPath.size() + 1, fileName, sizeof(localFileName)
205                    - nativeLibPath.size() - 1) != fileNameLen) {
206        ALOGD("Couldn't allocate local file name for library");
207        return INSTALL_FAILED_INTERNAL_ERROR;
208    }
209
210    // Only copy out the native file if it's different.
211    struct stat64 st;
212    if (!isFileDifferent(localFileName, uncompLen, modTime, crc, &st)) {
213        return INSTALL_SUCCEEDED;
214    }
215
216    char localTmpFileName[nativeLibPath.size() + TMP_FILE_PATTERN_LEN + 2];
217    if (strlcpy(localTmpFileName, nativeLibPath.c_str(), sizeof(localTmpFileName))
218            != nativeLibPath.size()) {
219        ALOGD("Couldn't allocate local file name for library");
220        return INSTALL_FAILED_INTERNAL_ERROR;
221    }
222
223    *(localFileName + nativeLibPath.size()) = '/';
224
225    if (strlcpy(localTmpFileName + nativeLibPath.size(), TMP_FILE_PATTERN,
226                    TMP_FILE_PATTERN_LEN - nativeLibPath.size()) != TMP_FILE_PATTERN_LEN) {
227        ALOGI("Couldn't allocate temporary file name for library");
228        return INSTALL_FAILED_INTERNAL_ERROR;
229    }
230
231    int fd = mkstemp(localTmpFileName);
232    if (fd < 0) {
233        ALOGI("Couldn't open temporary file name: %s: %s\n", localTmpFileName, strerror(errno));
234        return INSTALL_FAILED_CONTAINER_ERROR;
235    }
236
237    if (!zipFile->uncompressEntry(zipEntry, fd)) {
238        ALOGI("Failed uncompressing %s to %s\n", fileName, localTmpFileName);
239        close(fd);
240        unlink(localTmpFileName);
241        return INSTALL_FAILED_CONTAINER_ERROR;
242    }
243
244    close(fd);
245
246    // Set the modification time for this file to the ZIP's mod time.
247    struct timeval times[2];
248    times[0].tv_sec = st.st_atime;
249    times[1].tv_sec = modTime;
250    times[0].tv_usec = times[1].tv_usec = 0;
251    if (utimes(localTmpFileName, times) < 0) {
252        ALOGI("Couldn't change modification time on %s: %s\n", localTmpFileName, strerror(errno));
253        unlink(localTmpFileName);
254        return INSTALL_FAILED_CONTAINER_ERROR;
255    }
256
257    // Set the mode to 755
258    static const mode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP |  S_IXGRP | S_IROTH | S_IXOTH;
259    if (chmod(localTmpFileName, mode) < 0) {
260        ALOGI("Couldn't change permissions on %s: %s\n", localTmpFileName, strerror(errno));
261        unlink(localTmpFileName);
262        return INSTALL_FAILED_CONTAINER_ERROR;
263    }
264
265    // Finally, rename it to the final name.
266    if (rename(localTmpFileName, localFileName) < 0) {
267        ALOGI("Couldn't rename %s to %s: %s\n", localTmpFileName, localFileName, strerror(errno));
268        unlink(localTmpFileName);
269        return INSTALL_FAILED_CONTAINER_ERROR;
270    }
271
272    ALOGV("Successfully moved %s to %s\n", localTmpFileName, localFileName);
273
274    return INSTALL_SUCCEEDED;
275}
276
277/*
278 * An iterator over all shared libraries in a zip file. An entry is
279 * considered to be a shared library if all of the conditions below are
280 * satisfied :
281 *
282 * - The entry is under the lib/ directory.
283 * - The entry name ends with ".so" and the entry name starts with "lib",
284 *   an exception is made for entries whose name is "gdbserver".
285 * - The entry filename is "safe" (as determined by isFilenameSafe).
286 *
287 */
288class NativeLibrariesIterator {
289private:
290    NativeLibrariesIterator(ZipFileRO* zipFile, void* cookie)
291        : mZipFile(zipFile), mCookie(cookie), mLastSlash(NULL) {
292        fileName[0] = '\0';
293    }
294
295public:
296    static NativeLibrariesIterator* create(ZipFileRO* zipFile) {
297        void* cookie = NULL;
298        if (!zipFile->startIteration(&cookie)) {
299            return NULL;
300        }
301
302        return new NativeLibrariesIterator(zipFile, cookie);
303    }
304
305    ZipEntryRO next() {
306        ZipEntryRO next = NULL;
307        while ((next = mZipFile->nextEntry(mCookie)) != NULL) {
308            // Make sure this entry has a filename.
309            if (mZipFile->getEntryFileName(next, fileName, sizeof(fileName))) {
310                continue;
311            }
312
313            // Make sure we're in the lib directory of the ZIP.
314            if (strncmp(fileName, APK_LIB, APK_LIB_LEN)) {
315                continue;
316            }
317
318            // Make sure the filename is at least to the minimum library name size.
319            const size_t fileNameLen = strlen(fileName);
320            static const size_t minLength = APK_LIB_LEN + 2 + LIB_PREFIX_LEN + 1 + LIB_SUFFIX_LEN;
321            if (fileNameLen < minLength) {
322                continue;
323            }
324
325            const char* lastSlash = strrchr(fileName, '/');
326            ALOG_ASSERT(lastSlash != NULL, "last slash was null somehow for %s\n", fileName);
327
328            // Exception: If we find the gdbserver binary, return it.
329            if (!strncmp(lastSlash + 1, GDBSERVER, GDBSERVER_LEN)) {
330                break;
331            }
332
333            // Make sure the filename starts with lib and ends with ".so".
334            if (strncmp(fileName + fileNameLen - LIB_SUFFIX_LEN, LIB_SUFFIX, LIB_SUFFIX_LEN)
335                || strncmp(lastSlash, LIB_PREFIX, LIB_PREFIX_LEN)) {
336                continue;
337            }
338
339            // Make sure the filename is safe.
340            if (!isFilenameSafe(lastSlash + 1)) {
341                continue;
342            }
343
344            mLastSlash = lastSlash;
345            break;
346        }
347
348        return next;
349    }
350
351    inline const char* currentEntry() const {
352        return fileName;
353    }
354
355    inline const char* lastSlash() const {
356        return mLastSlash;
357    }
358
359    virtual ~NativeLibrariesIterator() {
360        mZipFile->endIteration(mCookie);
361    }
362private:
363
364    char fileName[PATH_MAX];
365    ZipFileRO* const mZipFile;
366    void* mCookie;
367    const char* mLastSlash;
368};
369
370static install_status_t
371iterateOverNativeFiles(JNIEnv *env, jlong apkHandle, jstring javaCpuAbi,
372                       iterFunc callFunc, void* callArg) {
373    ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
374    if (zipFile == NULL) {
375        return INSTALL_FAILED_INVALID_APK;
376    }
377
378    UniquePtr<NativeLibrariesIterator> it(NativeLibrariesIterator::create(zipFile));
379    if (it.get() == NULL) {
380        return INSTALL_FAILED_INVALID_APK;
381    }
382
383    const ScopedUtfChars cpuAbi(env, javaCpuAbi);
384    if (cpuAbi.c_str() == NULL) {
385        // This would've thrown, so this return code isn't observable by
386        // Java.
387        return INSTALL_FAILED_INVALID_APK;
388    }
389    ZipEntryRO entry = NULL;
390    while ((entry = it->next()) != NULL) {
391        const char* fileName = it->currentEntry();
392        const char* lastSlash = it->lastSlash();
393
394        // Check to make sure the CPU ABI of this file is one we support.
395        const char* cpuAbiOffset = fileName + APK_LIB_LEN;
396        const size_t cpuAbiRegionSize = lastSlash - cpuAbiOffset;
397
398        if (cpuAbi.size() == cpuAbiRegionSize && !strncmp(cpuAbiOffset, cpuAbi.c_str(), cpuAbiRegionSize)) {
399            install_status_t ret = callFunc(env, callArg, zipFile, entry, lastSlash + 1);
400
401            if (ret != INSTALL_SUCCEEDED) {
402                ALOGV("Failure for entry %s", lastSlash + 1);
403                return ret;
404            }
405        }
406    }
407
408    return INSTALL_SUCCEEDED;
409}
410
411
412static int findSupportedAbi(JNIEnv *env, jlong apkHandle, jobjectArray supportedAbisArray) {
413    const int numAbis = env->GetArrayLength(supportedAbisArray);
414    Vector<ScopedUtfChars*> supportedAbis;
415
416    for (int i = 0; i < numAbis; ++i) {
417        supportedAbis.add(new ScopedUtfChars(env,
418            (jstring) env->GetObjectArrayElement(supportedAbisArray, i)));
419    }
420
421    ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
422    if (zipFile == NULL) {
423        return INSTALL_FAILED_INVALID_APK;
424    }
425
426    UniquePtr<NativeLibrariesIterator> it(NativeLibrariesIterator::create(zipFile));
427    if (it.get() == NULL) {
428        return INSTALL_FAILED_INVALID_APK;
429    }
430
431    ZipEntryRO entry = NULL;
432    char fileName[PATH_MAX];
433    int status = NO_NATIVE_LIBRARIES;
434    while ((entry = it->next()) != NULL) {
435        // We're currently in the lib/ directory of the APK, so it does have some native
436        // code. We should return INSTALL_FAILED_NO_MATCHING_ABIS if none of the
437        // libraries match.
438        if (status == NO_NATIVE_LIBRARIES) {
439            status = INSTALL_FAILED_NO_MATCHING_ABIS;
440        }
441
442        const char* fileName = it->currentEntry();
443        const char* lastSlash = it->lastSlash();
444
445        // Check to see if this CPU ABI matches what we are looking for.
446        const char* abiOffset = fileName + APK_LIB_LEN;
447        const size_t abiSize = lastSlash - abiOffset;
448        for (int i = 0; i < numAbis; i++) {
449            const ScopedUtfChars* abi = supportedAbis[i];
450            if (abi->size() == abiSize && !strncmp(abiOffset, abi->c_str(), abiSize)) {
451                // The entry that comes in first (i.e. with a lower index) has the higher priority.
452                if (((i < status) && (status >= 0)) || (status < 0) ) {
453                    status = i;
454                }
455            }
456        }
457    }
458
459    for (int i = 0; i < numAbis; ++i) {
460        delete supportedAbis[i];
461    }
462
463    return status;
464}
465
466static jint
467com_android_internal_content_NativeLibraryHelper_copyNativeBinaries(JNIEnv *env, jclass clazz,
468        jlong apkHandle, jstring javaNativeLibPath, jstring javaCpuAbi)
469{
470    return (jint) iterateOverNativeFiles(env, apkHandle, javaCpuAbi,
471            copyFileIfChanged, &javaNativeLibPath);
472}
473
474static jlong
475com_android_internal_content_NativeLibraryHelper_sumNativeBinaries(JNIEnv *env, jclass clazz,
476        jlong apkHandle, jstring javaCpuAbi)
477{
478    size_t totalSize = 0;
479
480    iterateOverNativeFiles(env, apkHandle, javaCpuAbi, sumFiles, &totalSize);
481
482    return totalSize;
483}
484
485static jint
486com_android_internal_content_NativeLibraryHelper_findSupportedAbi(JNIEnv *env, jclass clazz,
487        jlong apkHandle, jobjectArray javaCpuAbisToSearch)
488{
489    return (jint) findSupportedAbi(env, apkHandle, javaCpuAbisToSearch);
490}
491
492enum bitcode_scan_result_t {
493  APK_SCAN_ERROR = -1,
494  NO_BITCODE_PRESENT = 0,
495  BITCODE_PRESENT = 1,
496};
497
498static jint
499com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode(JNIEnv *env, jclass clazz,
500        jlong apkHandle) {
501    ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
502    void* cookie = NULL;
503    if (!zipFile->startIteration(&cookie)) {
504        return APK_SCAN_ERROR;
505    }
506
507    char fileName[PATH_MAX];
508    ZipEntryRO next = NULL;
509    while ((next = zipFile->nextEntry(cookie)) != NULL) {
510        if (zipFile->getEntryFileName(next, fileName, sizeof(fileName))) {
511            continue;
512        }
513
514        const size_t fileNameLen = strlen(fileName);
515        const char* lastSlash = strrchr(fileName, '/');
516        const char* baseName = (lastSlash == NULL) ? fileName : fileName + 1;
517        if (!strncmp(fileName + fileNameLen - RS_BITCODE_SUFFIX_LEN, RS_BITCODE_SUFFIX,
518                     RS_BITCODE_SUFFIX_LEN) && isFilenameSafe(baseName)) {
519            zipFile->endIteration(cookie);
520            return BITCODE_PRESENT;
521        }
522    }
523
524    zipFile->endIteration(cookie);
525    return NO_BITCODE_PRESENT;
526}
527
528static jlong
529com_android_internal_content_NativeLibraryHelper_openApk(JNIEnv *env, jclass, jstring apkPath)
530{
531    ScopedUtfChars filePath(env, apkPath);
532    ZipFileRO* zipFile = ZipFileRO::open(filePath.c_str());
533
534    return reinterpret_cast<jlong>(zipFile);
535}
536
537static void
538com_android_internal_content_NativeLibraryHelper_close(JNIEnv *env, jclass, jlong apkHandle)
539{
540    delete reinterpret_cast<ZipFileRO*>(apkHandle);
541}
542
543static JNINativeMethod gMethods[] = {
544    {"nativeOpenApk",
545            "(Ljava/lang/String;)J",
546            (void *)com_android_internal_content_NativeLibraryHelper_openApk},
547    {"nativeClose",
548            "(J)V",
549            (void *)com_android_internal_content_NativeLibraryHelper_close},
550    {"nativeCopyNativeBinaries",
551            "(JLjava/lang/String;Ljava/lang/String;)I",
552            (void *)com_android_internal_content_NativeLibraryHelper_copyNativeBinaries},
553    {"nativeSumNativeBinaries",
554            "(JLjava/lang/String;)J",
555            (void *)com_android_internal_content_NativeLibraryHelper_sumNativeBinaries},
556    {"nativeFindSupportedAbi",
557            "(J[Ljava/lang/String;)I",
558            (void *)com_android_internal_content_NativeLibraryHelper_findSupportedAbi},
559    {"hasRenderscriptBitcode", "(J)I",
560            (void *)com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode},
561};
562
563
564int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env)
565{
566    return AndroidRuntime::registerNativeMethods(env,
567                "com/android/internal/content/NativeLibraryHelper", gMethods, NELEM(gMethods));
568}
569
570};
571