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.
7 #include "base/android/apk_assets.h"
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"
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
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]);
39 int OpenApkAsset(const std::string& file_path,
40 base::MemoryMappedFile::Region* region) {
41 return OpenApkAsset(file_path, std::string(), region);
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);
51 base::FileDescriptorStore::GetInstance().Set(key, base::ScopedFD(asset_fd),
56 void DumpLastOpenApkAssetFailure() {
57 JNIEnv* env = base::android::AttachCurrentThread();
58 base::android::ScopedJavaLocalRef<jstring> error =
59 Java_ApkAssets_takeLastErrorString(env);
63 SCOPED_CRASH_KEY_STRING256("base", "OpenApkAssetError",
64 ConvertJavaStringToUTF8(env, error));
65 base::debug::DumpWithoutCrashing();
68 } // namespace android