com_android_internal_content_NativeLibraryHelper.cpp revision 195b23ef712c51dc8d2f3a1f1943a27054dc4e74
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                mLastSlash = lastSlash;
331                break;
332            }
333
334            // Make sure the filename starts with lib and ends with ".so".
335            if (strncmp(fileName + fileNameLen - LIB_SUFFIX_LEN, LIB_SUFFIX, LIB_SUFFIX_LEN)
336                || strncmp(lastSlash, LIB_PREFIX, LIB_PREFIX_LEN)) {
337                continue;
338            }
339
340            // Make sure the filename is safe.
341            if (!isFilenameSafe(lastSlash + 1)) {
342                continue;
343            }
344
345            mLastSlash = lastSlash;
346            break;
347        }
348
349        return next;
350    }
351
352    inline const char* currentEntry() const {
353        return fileName;
354    }
355
356    inline const char* lastSlash() const {
357        return mLastSlash;
358    }
359
360    virtual ~NativeLibrariesIterator() {
361        mZipFile->endIteration(mCookie);
362    }
363private:
364
365    char fileName[PATH_MAX];
366    ZipFileRO* const mZipFile;
367    void* mCookie;
368    const char* mLastSlash;
369};
370
371static install_status_t
372iterateOverNativeFiles(JNIEnv *env, jlong apkHandle, jstring javaCpuAbi,
373                       iterFunc callFunc, void* callArg) {
374    ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
375    if (zipFile == NULL) {
376        return INSTALL_FAILED_INVALID_APK;
377    }
378
379    UniquePtr<NativeLibrariesIterator> it(NativeLibrariesIterator::create(zipFile));
380    if (it.get() == NULL) {
381        return INSTALL_FAILED_INVALID_APK;
382    }
383
384    const ScopedUtfChars cpuAbi(env, javaCpuAbi);
385    if (cpuAbi.c_str() == NULL) {
386        // This would've thrown, so this return code isn't observable by
387        // Java.
388        return INSTALL_FAILED_INVALID_APK;
389    }
390    ZipEntryRO entry = NULL;
391    while ((entry = it->next()) != NULL) {
392        const char* fileName = it->currentEntry();
393        const char* lastSlash = it->lastSlash();
394
395        // Check to make sure the CPU ABI of this file is one we support.
396        const char* cpuAbiOffset = fileName + APK_LIB_LEN;
397        const size_t cpuAbiRegionSize = lastSlash - cpuAbiOffset;
398
399        if (cpuAbi.size() == cpuAbiRegionSize && !strncmp(cpuAbiOffset, cpuAbi.c_str(), cpuAbiRegionSize)) {
400            install_status_t ret = callFunc(env, callArg, zipFile, entry, lastSlash + 1);
401
402            if (ret != INSTALL_SUCCEEDED) {
403                ALOGV("Failure for entry %s", lastSlash + 1);
404                return ret;
405            }
406        }
407    }
408
409    return INSTALL_SUCCEEDED;
410}
411
412
413static int findSupportedAbi(JNIEnv *env, jlong apkHandle, jobjectArray supportedAbisArray) {
414    const int numAbis = env->GetArrayLength(supportedAbisArray);
415    Vector<ScopedUtfChars*> supportedAbis;
416
417    for (int i = 0; i < numAbis; ++i) {
418        supportedAbis.add(new ScopedUtfChars(env,
419            (jstring) env->GetObjectArrayElement(supportedAbisArray, i)));
420    }
421
422    ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
423    if (zipFile == NULL) {
424        return INSTALL_FAILED_INVALID_APK;
425    }
426
427    UniquePtr<NativeLibrariesIterator> it(NativeLibrariesIterator::create(zipFile));
428    if (it.get() == NULL) {
429        return INSTALL_FAILED_INVALID_APK;
430    }
431
432    ZipEntryRO entry = NULL;
433    char fileName[PATH_MAX];
434    int status = NO_NATIVE_LIBRARIES;
435    while ((entry = it->next()) != NULL) {
436        // We're currently in the lib/ directory of the APK, so it does have some native
437        // code. We should return INSTALL_FAILED_NO_MATCHING_ABIS if none of the
438        // libraries match.
439        if (status == NO_NATIVE_LIBRARIES) {
440            status = INSTALL_FAILED_NO_MATCHING_ABIS;
441        }
442
443        const char* fileName = it->currentEntry();
444        const char* lastSlash = it->lastSlash();
445
446        // Check to see if this CPU ABI matches what we are looking for.
447        const char* abiOffset = fileName + APK_LIB_LEN;
448        const size_t abiSize = lastSlash - abiOffset;
449        for (int i = 0; i < numAbis; i++) {
450            const ScopedUtfChars* abi = supportedAbis[i];
451            if (abi->size() == abiSize && !strncmp(abiOffset, abi->c_str(), abiSize)) {
452                // The entry that comes in first (i.e. with a lower index) has the higher priority.
453                if (((i < status) && (status >= 0)) || (status < 0) ) {
454                    status = i;
455                }
456            }
457        }
458    }
459
460    for (int i = 0; i < numAbis; ++i) {
461        delete supportedAbis[i];
462    }
463
464    return status;
465}
466
467static jint
468com_android_internal_content_NativeLibraryHelper_copyNativeBinaries(JNIEnv *env, jclass clazz,
469        jlong apkHandle, jstring javaNativeLibPath, jstring javaCpuAbi)
470{
471    return (jint) iterateOverNativeFiles(env, apkHandle, javaCpuAbi,
472            copyFileIfChanged, &javaNativeLibPath);
473}
474
475static jlong
476com_android_internal_content_NativeLibraryHelper_sumNativeBinaries(JNIEnv *env, jclass clazz,
477        jlong apkHandle, jstring javaCpuAbi)
478{
479    size_t totalSize = 0;
480
481    iterateOverNativeFiles(env, apkHandle, javaCpuAbi, sumFiles, &totalSize);
482
483    return totalSize;
484}
485
486static jint
487com_android_internal_content_NativeLibraryHelper_findSupportedAbi(JNIEnv *env, jclass clazz,
488        jlong apkHandle, jobjectArray javaCpuAbisToSearch)
489{
490    return (jint) findSupportedAbi(env, apkHandle, javaCpuAbisToSearch);
491}
492
493enum bitcode_scan_result_t {
494  APK_SCAN_ERROR = -1,
495  NO_BITCODE_PRESENT = 0,
496  BITCODE_PRESENT = 1,
497};
498
499static jint
500com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode(JNIEnv *env, jclass clazz,
501        jlong apkHandle) {
502    ZipFileRO* zipFile = reinterpret_cast<ZipFileRO*>(apkHandle);
503    void* cookie = NULL;
504    if (!zipFile->startIteration(&cookie)) {
505        return APK_SCAN_ERROR;
506    }
507
508    char fileName[PATH_MAX];
509    ZipEntryRO next = NULL;
510    while ((next = zipFile->nextEntry(cookie)) != NULL) {
511        if (zipFile->getEntryFileName(next, fileName, sizeof(fileName))) {
512            continue;
513        }
514
515        const size_t fileNameLen = strlen(fileName);
516        const char* lastSlash = strrchr(fileName, '/');
517        const char* baseName = (lastSlash == NULL) ? fileName : fileName + 1;
518        if (!strncmp(fileName + fileNameLen - RS_BITCODE_SUFFIX_LEN, RS_BITCODE_SUFFIX,
519                     RS_BITCODE_SUFFIX_LEN) && isFilenameSafe(baseName)) {
520            zipFile->endIteration(cookie);
521            return BITCODE_PRESENT;
522        }
523    }
524
525    zipFile->endIteration(cookie);
526    return NO_BITCODE_PRESENT;
527}
528
529static jlong
530com_android_internal_content_NativeLibraryHelper_openApk(JNIEnv *env, jclass, jstring apkPath)
531{
532    ScopedUtfChars filePath(env, apkPath);
533    ZipFileRO* zipFile = ZipFileRO::open(filePath.c_str());
534
535    return reinterpret_cast<jlong>(zipFile);
536}
537
538static void
539com_android_internal_content_NativeLibraryHelper_close(JNIEnv *env, jclass, jlong apkHandle)
540{
541    delete reinterpret_cast<ZipFileRO*>(apkHandle);
542}
543
544static JNINativeMethod gMethods[] = {
545    {"nativeOpenApk",
546            "(Ljava/lang/String;)J",
547            (void *)com_android_internal_content_NativeLibraryHelper_openApk},
548    {"nativeClose",
549            "(J)V",
550            (void *)com_android_internal_content_NativeLibraryHelper_close},
551    {"nativeCopyNativeBinaries",
552            "(JLjava/lang/String;Ljava/lang/String;)I",
553            (void *)com_android_internal_content_NativeLibraryHelper_copyNativeBinaries},
554    {"nativeSumNativeBinaries",
555            "(JLjava/lang/String;)J",
556            (void *)com_android_internal_content_NativeLibraryHelper_sumNativeBinaries},
557    {"nativeFindSupportedAbi",
558            "(J[Ljava/lang/String;)I",
559            (void *)com_android_internal_content_NativeLibraryHelper_findSupportedAbi},
560    {"hasRenderscriptBitcode", "(J)I",
561            (void *)com_android_internal_content_NativeLibraryHelper_hasRenderscriptBitcode},
562};
563
564
565int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env)
566{
567    return AndroidRuntime::registerNativeMethods(env,
568                "com/android/internal/content/NativeLibraryHelper", gMethods, NELEM(gMethods));
569}
570
571};
572