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/context_utils.h"
10 #include "base/android/jni_array.h"
11 #include "base/android/jni_string.h"
12 #include "base/android/scoped_java_ref.h"
13 #include "jni/ApkAssets_jni.h"
14
15 namespace base {
16 namespace android {
17
RegisterApkAssets(JNIEnv * env)18 bool RegisterApkAssets(JNIEnv* env) {
19 return RegisterNativesImpl(env);
20 }
21
OpenApkAsset(const std::string & file_path,base::MemoryMappedFile::Region * region)22 int OpenApkAsset(const std::string& file_path,
23 base::MemoryMappedFile::Region* region) {
24 // The AAssetManager API of the NDK is does not expose a method for accessing
25 // raw resources :(.
26 JNIEnv* env = base::android::AttachCurrentThread();
27 ScopedJavaLocalRef<jlongArray> jarr = Java_ApkAssets_open(
28 env,
29 base::android::GetApplicationContext(),
30 base::android::ConvertUTF8ToJavaString(env, file_path).obj());
31 std::vector<jlong> results;
32 base::android::JavaLongArrayToLongVector(env, jarr.obj(), &results);
33 CHECK_EQ(3U, results.size());
34 int fd = static_cast<int>(results[0]);
35 region->offset = results[1];
36 region->size = results[2];
37 return fd;
38 }
39
RegisterApkAssetWithGlobalDescriptors(base::GlobalDescriptors::Key key,const std::string & file_path)40 bool RegisterApkAssetWithGlobalDescriptors(base::GlobalDescriptors::Key key,
41 const std::string& file_path) {
42 base::MemoryMappedFile::Region region =
43 base::MemoryMappedFile::Region::kWholeFile;
44 int asset_fd = OpenApkAsset(file_path, ®ion);
45 if (asset_fd != -1) {
46 base::GlobalDescriptors::GetInstance()->Set(key, asset_fd, region);
47 }
48 return asset_fd != -1;
49 }
50
51 } // namespace android
52 } // namespace base
53