1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <jni.h>
6
7 #include "base/android/apk_assets.h"
8
9 #include "base/android/jni_array.h"
10 #include "base/android/jni_string.h"
11 #include "base/android/scoped_java_ref.h"
12 #include "base/base_jni/ApkAssets_jni.h"
13 #include "base/debug/crash_logging.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/file_descriptor_store.h"
16
17 namespace base {
18 namespace android {
19
OpenApkAsset(const std::string & file_path,const std::string & split_name,base::MemoryMappedFile::Region * region)20 int OpenApkAsset(const std::string& file_path,
21 const std::string& split_name,
22 base::MemoryMappedFile::Region* region) {
23 // The AssetManager API of the NDK does not expose a method for accessing raw
24 // resources :(
25 JNIEnv* env = base::android::AttachCurrentThread();
26 ScopedJavaLocalRef<jlongArray> jarr =
27 Java_ApkAssets_open(env, ConvertUTF8ToJavaString(env, file_path),
28 ConvertUTF8ToJavaString(env, split_name));
29 std::vector<jlong> results;
30 base::android::JavaLongArrayToLongVector(env, jarr, &results);
31 CHECK_EQ(3U, results.size());
32 int fd = static_cast<int>(results[0]);
33 region->offset = results[1];
34 // Not a checked_cast because open() may return -1.
35 region->size = static_cast<size_t>(results[2]);
36 return fd;
37 }
38
OpenApkAsset(const std::string & file_path,base::MemoryMappedFile::Region * region)39 int OpenApkAsset(const std::string& file_path,
40 base::MemoryMappedFile::Region* region) {
41 return OpenApkAsset(file_path, std::string(), region);
42 }
43
RegisterApkAssetWithFileDescriptorStore(const std::string & key,const base::FilePath & file_path)44 bool RegisterApkAssetWithFileDescriptorStore(const std::string& key,
45 const base::FilePath& file_path) {
46 base::MemoryMappedFile::Region region =
47 base::MemoryMappedFile::Region::kWholeFile;
48 int asset_fd = OpenApkAsset(file_path.value(), ®ion);
49 if (asset_fd == -1)
50 return false;
51 base::FileDescriptorStore::GetInstance().Set(key, base::ScopedFD(asset_fd),
52 region);
53 return true;
54 }
55
DumpLastOpenApkAssetFailure()56 void DumpLastOpenApkAssetFailure() {
57 JNIEnv* env = base::android::AttachCurrentThread();
58 base::android::ScopedJavaLocalRef<jstring> error =
59 Java_ApkAssets_takeLastErrorString(env);
60 if (!error) {
61 return;
62 }
63 SCOPED_CRASH_KEY_STRING256("base", "OpenApkAssetError",
64 ConvertJavaStringToUTF8(env, error));
65 base::debug::DumpWithoutCrashing();
66 }
67
68 } // namespace android
69 } // namespace base
70