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