aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowArscApkAssets9.java
blob: 9ab0887c72a0f9875f73358d849fa3925cb8e2d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static org.robolectric.res.android.Errors.NO_ERROR;
import static org.robolectric.res.android.Util.ATRACE_NAME;
import static org.robolectric.res.android.Util.JNI_TRUE;
import static org.robolectric.util.reflector.Reflector.reflector;

import android.content.res.ApkAssets;
import android.content.res.AssetManager;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.res.android.ApkAssetsCache;
import org.robolectric.res.android.Asset;
import org.robolectric.res.android.CppApkAssets;
import org.robolectric.res.android.Registries;
import org.robolectric.res.android.ResXMLTree;
import org.robolectric.shadows.ShadowApkAssets.Picker;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.reflector.Accessor;
import org.robolectric.util.reflector.Direct;
import org.robolectric.util.reflector.ForType;
import org.robolectric.util.reflector.Static;

// transliterated from
// https://android.googlesource.com/platform/frameworks/base/+/android-9.0.0_r12/core/jni/android_content_res_ApkAssets.cpp

/** Shadow for {@link ApkAssets} for Android P+ */
@Implements(
    value = ApkAssets.class,
    minSdk = P,
    shadowPicker = Picker.class,
    isInAndroidSdk = false,
    looseSignatures = true)
public class ShadowArscApkAssets9 extends ShadowApkAssets {
  // #define ATRACE_TAG ATRACE_TAG_RESOURCES
  //
  // #include "android-base/macros.h"
  // #include "android-base/stringprintf.h"
  // #include "android-base/unique_fd.h"
  // #include "androidfw/ApkAssets.h"
  // #include "utils/misc.h"
  // #include "utils/Trace.h"
  //
  // #include "core_jni_helpers.h"
  // #include "jni.h"
  // #include "nativehelper/ScopedUtfChars.h"
  //
  // using ::android::base::unique_fd;
  //
  // namespace android {

  // TODO: just use the ApkAssets constants. For some unknown reason these cannot be found
  private static final int PROPERTY_SYSTEM = 1 << 0;
  private static final int PROPERTY_DYNAMIC = 1 << 1;
  private static final int PROPERTY_OVERLAY = 1 << 3;

  protected static final String FRAMEWORK_APK_PATH =
      ReflectionHelpers.getStaticField(AssetManager.class, "FRAMEWORK_APK_PATH");

  @RealObject private ApkAssets realApkAssets;

  long getNativePtr() {
    return reflector(_ApkAssets_.class, realApkAssets).getNativePtr();
  }

  /** Reflector interface for {@link ApkAssets}'s internals. */
  @ForType(ApkAssets.class)
  interface _ApkAssets_ {
    @Static
    @Direct
    ApkAssets loadFromPath(String finalPath, boolean system);

    @Static
    @Direct
    ApkAssets loadFromPath(String finalPath, int flags);

    @Accessor("mNativePtr")
    long getNativePtr();
  }

  /**
   * Necessary to shadow this method because the framework path is hard-coded. Called from
   * AssetManager.createSystemAssetsInZygoteLocked() in P+.
   */
  @Implementation(maxSdk = Q)
  protected static ApkAssets loadFromPath(String path, boolean system) throws IOException {
    if (FRAMEWORK_APK_PATH.equals(path)) {
      path = RuntimeEnvironment.getAndroidFrameworkJarPath().toString();
    }

    return reflector(_ApkAssets_.class).loadFromPath(path, system);
  }

  @Implementation(minSdk = R)
  protected static ApkAssets loadFromPath(String path, int flags) throws IOException {
    if (FRAMEWORK_APK_PATH.equals(path)) {
      path = RuntimeEnvironment.getAndroidFrameworkJarPath().toString();
    }
    return reflector(_ApkAssets_.class).loadFromPath(path, flags);
  }

  // static jlong NativeLoad(JNIEnv* env, jclass /*clazz*/, jstring java_path, jboolean system,
  //                         jboolean force_shared_lib, jboolean overlay) {

  @Implementation(maxSdk = Q)
  protected static long nativeLoad(
      String path, boolean system, boolean forceSharedLib, boolean overlay) throws IOException {
    if (path == null) {
      return 0;
    }

    long cachedApkAssetsPtr = ApkAssetsCache.get(path, system, RuntimeEnvironment.getApiLevel());
    if (cachedApkAssetsPtr != -1) {
      return cachedApkAssetsPtr;
    }

    ATRACE_NAME(String.format("LoadApkAssets(%s)", path));

    CppApkAssets apk_assets;
    try {
      if (overlay) {
        apk_assets = CppApkAssets.LoadOverlay(path, system);
      } else if (forceSharedLib) {
        apk_assets = CppApkAssets.LoadAsSharedLibrary(path, system);
      } else {
        apk_assets = CppApkAssets.Load(path, system);
      }
    } catch (OutOfMemoryError e) {
      OutOfMemoryError outOfMemoryError = new OutOfMemoryError("Failed to load " + path);
      outOfMemoryError.initCause(e);
      throw outOfMemoryError;
    }

    if (apk_assets == null) {
      String error_msg = String.format("Failed to load asset path %s", path);
      throw new IOException(error_msg);
    }
    long ptr = Registries.NATIVE_APK_ASSETS_REGISTRY.register(apk_assets);
    ApkAssetsCache.put(path, system, RuntimeEnvironment.getApiLevel(), ptr);
    return ptr;
  }

  @Implementation(minSdk = R)
  protected static Object nativeLoad(
      Object format, Object javaPath, Object flags, Object assetsProvider) throws IOException {
    boolean system = ((int) flags & PROPERTY_SYSTEM) == PROPERTY_SYSTEM;
    boolean overlay = ((int) flags & PROPERTY_OVERLAY) == PROPERTY_OVERLAY;
    boolean forceSharedLib = ((int) flags & PROPERTY_DYNAMIC) == PROPERTY_DYNAMIC;
    return nativeLoad((String) javaPath, system, forceSharedLib, overlay);
  }

  // static jlong NativeLoadFromFd(JNIEnv* env, jclass /*clazz*/, jobject file_descriptor,
  //                               jstring friendly_name, jboolean system, jboolean
  // force_shared_lib) {
  @Implementation(maxSdk = Q)
  protected static long nativeLoadFromFd(
      FileDescriptor file_descriptor,
      String friendly_name,
      boolean system,
      boolean force_shared_lib) {
    String friendly_name_utf8 = friendly_name;
    if (friendly_name_utf8 == null) {
      return 0;
    }

    throw new UnsupportedOperationException();
    // ATRACE_NAME(String.format("LoadApkAssetsFd(%s)", friendly_name_utf8));
    //
    // int fd = jniGetFDFromFileDescriptor(env, file_descriptor);
    // if (fd < 0) {
    //   throw new IllegalArgumentException("Bad FileDescriptor");
    // }
    //
    // unique_fd dup_fd(.dup(fd));
    // if (dup_fd < 0) {
    //   throw new IOException(errno);
    //   return 0;
    // }
    //
    // ApkAssets apk_assets = ApkAssets.LoadFromFd(std.move(dup_fd),
    //                                                                     friendly_name_utf8,
    //                                                                     system, force_shared_lib);
    // if (apk_assets == null) {
    //   String error_msg = String.format("Failed to load asset path %s from fd %d",
    //                                              friendly_name_utf8, dup_fd.get());
    //   throw new IOException(error_msg);
    //   return 0;
    // }
    // return ShadowArscAssetManager9.NATIVE_APK_ASSETS_REGISTRY.getNativeObjectId(apk_assets);
  }

  // static jstring NativeGetAssetPath(JNIEnv* env, jclass /*clazz*/, jlong ptr) {
  @Implementation
  protected static String nativeGetAssetPath(long ptr) {
    CppApkAssets apk_assets = Registries.NATIVE_APK_ASSETS_REGISTRY.getNativeObject(ptr);
    return apk_assets.GetPath();
  }

  // static jlong NativeGetStringBlock(JNIEnv* /*env*/, jclass /*clazz*/, jlong ptr) {
  @Implementation
  protected static long nativeGetStringBlock(long ptr) {
    CppApkAssets apk_assets = Registries.NATIVE_APK_ASSETS_REGISTRY.getNativeObject(ptr);
    return apk_assets.GetLoadedArsc().GetStringPool().getNativePtr();
  }

  // static jboolean NativeIsUpToDate(JNIEnv* /*env*/, jclass /*clazz*/, jlong ptr) {
  @Implementation
  protected static boolean nativeIsUpToDate(long ptr) {
    // (void)apk_assets;
    return JNI_TRUE;
  }

  // static jlong NativeOpenXml(JNIEnv* env, jclass /*clazz*/, jlong ptr, jstring file_name) {
  @Implementation
  protected static long nativeOpenXml(long ptr, String file_name) throws FileNotFoundException {
    String path_utf8 = file_name;
    if (path_utf8 == null) {
      return 0;
    }

    CppApkAssets apk_assets =
        Registries.NATIVE_APK_ASSETS_REGISTRY.getNativeObject(ptr);
    Asset asset = apk_assets.Open(path_utf8, Asset.AccessMode.ACCESS_RANDOM);
    if (asset == null) {
      throw new FileNotFoundException(path_utf8);
    }

    // DynamicRefTable is only needed when looking up resource references. Opening an XML file
    // directly from an ApkAssets has no notion of proper resource references.
    ResXMLTree xml_tree = new ResXMLTree(null); // util.make_unique<ResXMLTree>(nullptr /*dynamicRefTable*/);
    int err = xml_tree.setTo(asset.getBuffer(true), (int) asset.getLength(), true);
    // asset.reset();

    if (err != NO_ERROR) {
      throw new FileNotFoundException("Corrupt XML binary file");
    }
    return Registries.NATIVE_RES_XML_TREES.register(xml_tree); // reinterpret_cast<jlong>(xml_tree.release());
  }

  // // JNI registration.
  // static const JNINativeMethod gApkAssetsMethods[] = {
  //     {"nativeLoad", "(Ljava/lang/String;ZZZ)J", (void*)NativeLoad},
  //     {"nativeLoadFromFd", "(Ljava/io/FileDescriptor;Ljava/lang/String;ZZ)J",
  //         (void*)NativeLoadFromFd},
  //     {"nativeDestroy", "(J)V", (void*)NativeDestroy},
  //     {"nativeGetAssetPath", "(J)Ljava/lang/String;", (void*)NativeGetAssetPath},
  //     {"nativeGetStringBlock", "(J)J", (void*)NativeGetStringBlock},
  //     {"nativeIsUpToDate", "(J)Z", (void*)NativeIsUpToDate},
  //     {"nativeOpenXml", "(JLjava/lang/String;)J", (void*)NativeOpenXml},
  // };
  //
  // int register_android_content_res_ApkAssets(JNIEnv* env) {
  //   return RegisterMethodsOrDie(env, "android/content/res/ApkAssets", gApkAssetsMethods,
  //                               arraysize(gApkAssetsMethods));
  // }
  //
  // }  // namespace android
}