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