1 // Copyright 2015 The Chromium Authors. All rights reserved.
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/file_descriptor_store.h"
13 #include "jni/ApkAssets_jni.h"
14
15 namespace base {
16 namespace android {
17
OpenApkAsset(const std::string & file_path,base::MemoryMappedFile::Region * region)18 int OpenApkAsset(const std::string& file_path,
19 base::MemoryMappedFile::Region* region) {
20 // The AssetManager API of the NDK does not expose a method for accessing raw
21 // resources :(
22 JNIEnv* env = base::android::AttachCurrentThread();
23 ScopedJavaLocalRef<jlongArray> jarr = Java_ApkAssets_open(
24 env, base::android::ConvertUTF8ToJavaString(env, file_path));
25 std::vector<jlong> results;
26 base::android::JavaLongArrayToLongVector(env, jarr.obj(), &results);
27 CHECK_EQ(3U, results.size());
28 int fd = static_cast<int>(results[0]);
29 region->offset = results[1];
30 region->size = results[2];
31 return fd;
32 }
33
RegisterApkAssetWithFileDescriptorStore(const std::string & key,const base::FilePath & file_path)34 bool RegisterApkAssetWithFileDescriptorStore(const std::string& key,
35 const base::FilePath& file_path) {
36 base::MemoryMappedFile::Region region =
37 base::MemoryMappedFile::Region::kWholeFile;
38 int asset_fd = OpenApkAsset(file_path.value(), ®ion);
39 if (asset_fd == -1)
40 return false;
41 base::FileDescriptorStore::GetInstance().Set(key, base::ScopedFD(asset_fd),
42 region);
43 return true;
44 }
45
46 } // namespace android
47 } // namespace base
48