com_android_internal_content_NativeLibraryHelper.cpp revision ad076286c3140ce9f1f25b8503bdfd2047a968a7
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 <utils/Log.h>
23#include <androidfw/ZipFileRO.h>
24#include <androidfw/ZipUtils.h>
25#include <ScopedUtfChars.h>
26#include <UniquePtr.h>
27
28#include <zlib.h>
29
30#include <fcntl.h>
31#include <stdlib.h>
32#include <string.h>
33#include <time.h>
34#include <unistd.h>
35#include <sys/stat.h>
36#include <sys/types.h>
37
38
39#define APK_LIB "lib/"
40#define APK_LIB_LEN (sizeof(APK_LIB) - 1)
41
42#define LIB_PREFIX "/lib"
43#define LIB_PREFIX_LEN (sizeof(LIB_PREFIX) - 1)
44
45#define LIB_SUFFIX ".so"
46#define LIB_SUFFIX_LEN (sizeof(LIB_SUFFIX) - 1)
47
48#define GDBSERVER "gdbserver"
49#define GDBSERVER_LEN (sizeof(GDBSERVER) - 1)
50
51#define TMP_FILE_PATTERN "/tmp.XXXXXX"
52#define TMP_FILE_PATTERN_LEN (sizeof(TMP_FILE_PATTERN) - 1)
53
54namespace android {
55
56// These match PackageManager.java install codes
57typedef enum {
58    INSTALL_SUCCEEDED = 1,
59    INSTALL_FAILED_INVALID_APK = -2,
60    INSTALL_FAILED_INSUFFICIENT_STORAGE = -4,
61    INSTALL_FAILED_CONTAINER_ERROR = -18,
62    INSTALL_FAILED_INTERNAL_ERROR = -110,
63} install_status_t;
64
65typedef install_status_t (*iterFunc)(JNIEnv*, void*, ZipFileRO*, ZipEntryRO, const char*);
66
67// Equivalent to isFilenameSafe
68static bool
69isFilenameSafe(const char* filename)
70{
71    off_t offset = 0;
72    for (;;) {
73        switch (*(filename + offset)) {
74        case 0:
75            // Null.
76            // If we've reached the end, all the other characters are good.
77            return true;
78
79        case 'A' ... 'Z':
80        case 'a' ... 'z':
81        case '0' ... '9':
82        case '+':
83        case ',':
84        case '-':
85        case '.':
86        case '/':
87        case '=':
88        case '_':
89            offset++;
90            break;
91
92        default:
93            // We found something that is not good.
94            return false;
95        }
96    }
97    // Should not reach here.
98}
99
100static bool
101isFileDifferent(const char* filePath, size_t fileSize, time_t modifiedTime,
102        long zipCrc, struct stat64* st)
103{
104    if (lstat64(filePath, st) < 0) {
105        // File is not found or cannot be read.
106        ALOGV("Couldn't stat %s, copying: %s\n", filePath, strerror(errno));
107        return true;
108    }
109
110    if (!S_ISREG(st->st_mode)) {
111        return true;
112    }
113
114    if (st->st_size != fileSize) {
115        return true;
116    }
117
118    // For some reason, bionic doesn't define st_mtime as time_t
119    if (time_t(st->st_mtime) != modifiedTime) {
120        ALOGV("mod time doesn't match: %ld vs. %ld\n", st->st_mtime, modifiedTime);
121        return true;
122    }
123
124    int fd = TEMP_FAILURE_RETRY(open(filePath, O_RDONLY));
125    if (fd < 0) {
126        ALOGV("Couldn't open file %s: %s", filePath, strerror(errno));
127        return true;
128    }
129
130    long crc = crc32(0L, Z_NULL, 0);
131    unsigned char crcBuffer[16384];
132    ssize_t numBytes;
133    while ((numBytes = TEMP_FAILURE_RETRY(read(fd, crcBuffer, sizeof(crcBuffer)))) > 0) {
134        crc = crc32(crc, crcBuffer, numBytes);
135    }
136    close(fd);
137
138    ALOGV("%s: crc = %lx, zipCrc = %lx\n", filePath, crc, zipCrc);
139
140    if (crc != zipCrc) {
141        return true;
142    }
143
144    return false;
145}
146
147static install_status_t
148sumFiles(JNIEnv*, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char*)
149{
150    size_t* total = (size_t*) arg;
151    size_t uncompLen;
152
153    if (!zipFile->getEntryInfo(zipEntry, NULL, &uncompLen, NULL, NULL, NULL, NULL)) {
154        return INSTALL_FAILED_INVALID_APK;
155    }
156
157    *total += uncompLen;
158
159    return INSTALL_SUCCEEDED;
160}
161
162/*
163 * Copy the native library if needed.
164 *
165 * This function assumes the library and path names passed in are considered safe.
166 */
167static install_status_t
168copyFileIfChanged(JNIEnv *env, void* arg, ZipFileRO* zipFile, ZipEntryRO zipEntry, const char* fileName)
169{
170    jstring* javaNativeLibPath = (jstring*) arg;
171    ScopedUtfChars nativeLibPath(env, *javaNativeLibPath);
172
173    size_t uncompLen;
174    long when;
175    long crc;
176    time_t modTime;
177
178    if (!zipFile->getEntryInfo(zipEntry, NULL, &uncompLen, NULL, NULL, &when, &crc)) {
179        ALOGD("Couldn't read zip entry info\n");
180        return INSTALL_FAILED_INVALID_APK;
181    } else {
182        struct tm t;
183        ZipUtils::zipTimeToTimespec(when, &t);
184        modTime = mktime(&t);
185    }
186
187    // Build local file path
188    const size_t fileNameLen = strlen(fileName);
189    char localFileName[nativeLibPath.size() + fileNameLen + 2];
190
191    if (strlcpy(localFileName, nativeLibPath.c_str(), sizeof(localFileName)) != nativeLibPath.size()) {
192        ALOGD("Couldn't allocate local file name for library");
193        return INSTALL_FAILED_INTERNAL_ERROR;
194    }
195
196    *(localFileName + nativeLibPath.size()) = '/';
197
198    if (strlcpy(localFileName + nativeLibPath.size() + 1, fileName, sizeof(localFileName)
199                    - nativeLibPath.size() - 1) != fileNameLen) {
200        ALOGD("Couldn't allocate local file name for library");
201        return INSTALL_FAILED_INTERNAL_ERROR;
202    }
203
204    // Only copy out the native file if it's different.
205    struct stat64 st;
206    if (!isFileDifferent(localFileName, uncompLen, modTime, crc, &st)) {
207        return INSTALL_SUCCEEDED;
208    }
209
210    char localTmpFileName[nativeLibPath.size() + TMP_FILE_PATTERN_LEN + 2];
211    if (strlcpy(localTmpFileName, nativeLibPath.c_str(), sizeof(localTmpFileName))
212            != nativeLibPath.size()) {
213        ALOGD("Couldn't allocate local file name for library");
214        return INSTALL_FAILED_INTERNAL_ERROR;
215    }
216
217    *(localFileName + nativeLibPath.size()) = '/';
218
219    if (strlcpy(localTmpFileName + nativeLibPath.size(), TMP_FILE_PATTERN,
220                    TMP_FILE_PATTERN_LEN - nativeLibPath.size()) != TMP_FILE_PATTERN_LEN) {
221        ALOGI("Couldn't allocate temporary file name for library");
222        return INSTALL_FAILED_INTERNAL_ERROR;
223    }
224
225    int fd = mkstemp(localTmpFileName);
226    if (fd < 0) {
227        ALOGI("Couldn't open temporary file name: %s: %s\n", localTmpFileName, strerror(errno));
228        return INSTALL_FAILED_CONTAINER_ERROR;
229    }
230
231    if (!zipFile->uncompressEntry(zipEntry, fd)) {
232        ALOGI("Failed uncompressing %s to %s\n", fileName, localTmpFileName);
233        close(fd);
234        unlink(localTmpFileName);
235        return INSTALL_FAILED_CONTAINER_ERROR;
236    }
237
238    close(fd);
239
240    // Set the modification time for this file to the ZIP's mod time.
241    struct timeval times[2];
242    times[0].tv_sec = st.st_atime;
243    times[1].tv_sec = modTime;
244    times[0].tv_usec = times[1].tv_usec = 0;
245    if (utimes(localTmpFileName, times) < 0) {
246        ALOGI("Couldn't change modification time on %s: %s\n", localTmpFileName, strerror(errno));
247        unlink(localTmpFileName);
248        return INSTALL_FAILED_CONTAINER_ERROR;
249    }
250
251    // Set the mode to 755
252    static const mode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP |  S_IXGRP | S_IROTH | S_IXOTH;
253    if (chmod(localTmpFileName, mode) < 0) {
254        ALOGI("Couldn't change permissions on %s: %s\n", localTmpFileName, strerror(errno));
255        unlink(localTmpFileName);
256        return INSTALL_FAILED_CONTAINER_ERROR;
257    }
258
259    // Finally, rename it to the final name.
260    if (rename(localTmpFileName, localFileName) < 0) {
261        ALOGI("Couldn't rename %s to %s: %s\n", localTmpFileName, localFileName, strerror(errno));
262        unlink(localTmpFileName);
263        return INSTALL_FAILED_CONTAINER_ERROR;
264    }
265
266    ALOGV("Successfully moved %s to %s\n", localTmpFileName, localFileName);
267
268    return INSTALL_SUCCEEDED;
269}
270
271static install_status_t
272iterateOverNativeFiles(JNIEnv *env, jstring javaFilePath, jstring javaCpuAbi, jstring javaCpuAbi2,
273        iterFunc callFunc, void* callArg) {
274    ScopedUtfChars filePath(env, javaFilePath);
275    ScopedUtfChars cpuAbi(env, javaCpuAbi);
276    ScopedUtfChars cpuAbi2(env, javaCpuAbi2);
277
278    UniquePtr<ZipFileRO> zipFile(ZipFileRO::open(filePath.c_str()));
279    if (zipFile.get() == NULL) {
280        ALOGI("Couldn't open APK %s\n", filePath.c_str());
281        return INSTALL_FAILED_INVALID_APK;
282    }
283
284    char fileName[PATH_MAX];
285    bool hasPrimaryAbi = false;
286
287    void* cookie = NULL;
288    if (!zipFile->startIteration(&cookie)) {
289        ALOGI("Couldn't iterate over APK%s\n", filePath.c_str());
290        return INSTALL_FAILED_INVALID_APK;
291    }
292
293    ZipEntryRO entry = NULL;
294    while ((entry = zipFile->nextEntry(cookie)) != NULL) {
295        // Make sure this entry has a filename.
296        if (zipFile->getEntryFileName(entry, fileName, sizeof(fileName))) {
297            continue;
298        }
299
300        // Make sure we're in the lib directory of the ZIP.
301        if (strncmp(fileName, APK_LIB, APK_LIB_LEN)) {
302            continue;
303        }
304
305        // Make sure the filename is at least to the minimum library name size.
306        const size_t fileNameLen = strlen(fileName);
307        static const size_t minLength = APK_LIB_LEN + 2 + LIB_PREFIX_LEN + 1 + LIB_SUFFIX_LEN;
308        if (fileNameLen < minLength) {
309            continue;
310        }
311
312        const char* lastSlash = strrchr(fileName, '/');
313        ALOG_ASSERT(lastSlash != NULL, "last slash was null somehow for %s\n", fileName);
314
315        // Check to make sure the CPU ABI of this file is one we support.
316        const char* cpuAbiOffset = fileName + APK_LIB_LEN;
317        const size_t cpuAbiRegionSize = lastSlash - cpuAbiOffset;
318
319        ALOGV("Comparing ABIs %s and %s versus %s\n", cpuAbi.c_str(), cpuAbi2.c_str(), cpuAbiOffset);
320        if (cpuAbi.size() == cpuAbiRegionSize
321                && *(cpuAbiOffset + cpuAbi.size()) == '/'
322                && !strncmp(cpuAbiOffset, cpuAbi.c_str(), cpuAbiRegionSize)) {
323            ALOGV("Using primary ABI %s\n", cpuAbi.c_str());
324            hasPrimaryAbi = true;
325        } else if (cpuAbi2.size() == cpuAbiRegionSize
326                && *(cpuAbiOffset + cpuAbi2.size()) == '/'
327                && !strncmp(cpuAbiOffset, cpuAbi2.c_str(), cpuAbiRegionSize)) {
328
329            /*
330             * If this library matches both the primary and secondary ABIs,
331             * only use the primary ABI.
332             */
333            if (hasPrimaryAbi) {
334                ALOGV("Already saw primary ABI, skipping secondary ABI %s\n", cpuAbi2.c_str());
335                continue;
336            } else {
337                ALOGV("Using secondary ABI %s\n", cpuAbi2.c_str());
338            }
339        } else {
340            ALOGV("abi didn't match anything: %s (end at %zd)\n", cpuAbiOffset, cpuAbiRegionSize);
341            continue;
342        }
343
344        // If this is a .so file, check to see if we need to copy it.
345        if ((!strncmp(fileName + fileNameLen - LIB_SUFFIX_LEN, LIB_SUFFIX, LIB_SUFFIX_LEN)
346                    && !strncmp(lastSlash, LIB_PREFIX, LIB_PREFIX_LEN)
347                    && isFilenameSafe(lastSlash + 1))
348                || !strncmp(lastSlash + 1, GDBSERVER, GDBSERVER_LEN)) {
349
350            install_status_t ret = callFunc(env, callArg, zipFile.get(), entry, lastSlash + 1);
351
352            if (ret != INSTALL_SUCCEEDED) {
353                ALOGV("Failure for entry %s", lastSlash + 1);
354                zipFile->endIteration(cookie);
355                return ret;
356            }
357        }
358    }
359
360    zipFile->endIteration(cookie);
361
362    return INSTALL_SUCCEEDED;
363}
364
365static jint
366com_android_internal_content_NativeLibraryHelper_copyNativeBinaries(JNIEnv *env, jclass clazz,
367        jstring javaFilePath, jstring javaNativeLibPath, jstring javaCpuAbi, jstring javaCpuAbi2)
368{
369    return (jint) iterateOverNativeFiles(env, javaFilePath, javaCpuAbi, javaCpuAbi2,
370            copyFileIfChanged, &javaNativeLibPath);
371}
372
373static jlong
374com_android_internal_content_NativeLibraryHelper_sumNativeBinaries(JNIEnv *env, jclass clazz,
375        jstring javaFilePath, jstring javaCpuAbi, jstring javaCpuAbi2)
376{
377    size_t totalSize = 0;
378
379    iterateOverNativeFiles(env, javaFilePath, javaCpuAbi, javaCpuAbi2, sumFiles, &totalSize);
380
381    return totalSize;
382}
383
384static JNINativeMethod gMethods[] = {
385    {"nativeCopyNativeBinaries",
386            "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I",
387            (void *)com_android_internal_content_NativeLibraryHelper_copyNativeBinaries},
388    {"nativeSumNativeBinaries",
389            "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)J",
390            (void *)com_android_internal_content_NativeLibraryHelper_sumNativeBinaries},
391};
392
393
394int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env)
395{
396    return AndroidRuntime::registerNativeMethods(env,
397                "com/android/internal/content/NativeLibraryHelper", gMethods, NELEM(gMethods));
398}
399
400};
401