apk_assets.cc 1.9 KB

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