/
ShadowArscAssetManager10.java
1951 lines (1746 loc) · 75.1 KB
/
ShadowArscAssetManager10.java
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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 android.os.Build.VERSION_CODES.S;
import static org.robolectric.res.android.ApkAssetsCookie.K_INVALID_COOKIE;
import static org.robolectric.res.android.ApkAssetsCookie.kInvalidCookie;
import static org.robolectric.res.android.Asset.SEEK_CUR;
import static org.robolectric.res.android.Asset.SEEK_END;
import static org.robolectric.res.android.Asset.SEEK_SET;
import static org.robolectric.res.android.AttributeResolution10.ApplyStyle;
import static org.robolectric.res.android.AttributeResolution10.ResolveAttrs;
import static org.robolectric.res.android.AttributeResolution10.RetrieveAttributes;
import static org.robolectric.res.android.Errors.NO_ERROR;
import static org.robolectric.res.android.Registries.NATIVE_RES_XML_PARSERS;
import static org.robolectric.res.android.Registries.NATIVE_RES_XML_TREES;
import static org.robolectric.res.android.Util.ATRACE_NAME;
import static org.robolectric.res.android.Util.CHECK;
import static org.robolectric.res.android.Util.JNI_FALSE;
import static org.robolectric.res.android.Util.JNI_TRUE;
import static org.robolectric.res.android.Util.isTruthy;
import static org.robolectric.shadow.api.Shadow.invokeConstructor;
import static org.robolectric.util.reflector.Reflector.reflector;
import android.annotation.AnyRes;
import android.annotation.ArrayRes;
import android.annotation.AttrRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.StyleRes;
import android.content.res.ApkAssets;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Configuration.NativeConfig;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.ArraySet;
import android.util.SparseArray;
import android.util.TypedValue;
import dalvik.system.VMRuntime;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.res.Fs;
import org.robolectric.res.android.ApkAssetsCookie;
import org.robolectric.res.android.Asset;
import org.robolectric.res.android.AssetDir;
import org.robolectric.res.android.AssetPath;
import org.robolectric.res.android.CppApkAssets;
import org.robolectric.res.android.CppAssetManager;
import org.robolectric.res.android.CppAssetManager2;
import org.robolectric.res.android.CppAssetManager2.ResolvedBag;
import org.robolectric.res.android.CppAssetManager2.ResourceName;
import org.robolectric.res.android.CppAssetManager2.Theme;
import org.robolectric.res.android.DynamicRefTable;
import org.robolectric.res.android.Ref;
import org.robolectric.res.android.Registries;
import org.robolectric.res.android.ResStringPool;
import org.robolectric.res.android.ResTable_config;
import org.robolectric.res.android.ResXMLParser;
import org.robolectric.res.android.ResXMLTree;
import org.robolectric.res.android.ResourceTypes.Res_value;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.util.PerfStatsCollector;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;
import org.robolectric.util.reflector.Direct;
import org.robolectric.util.reflector.ForType;
import org.robolectric.util.reflector.Static;
// TODO: update path to released version.
// transliterated from
// https://android.googlesource.com/platform/frameworks/base/+/android-10.0.0_rXX/core/jni/android_util_AssetManager.cpp
@Implements(
value = AssetManager.class,
minSdk = Build.VERSION_CODES.Q,
shadowPicker = ShadowAssetManager.Picker.class)
@SuppressWarnings("NewApi")
public class ShadowArscAssetManager10 extends ShadowAssetManager.ArscBase {
// Offsets into the outValues array populated by the methods below. outValues is a uint32_t
// array, but each logical element takes up 7 uint32_t-sized physical elements.
// Keep these in sync with android.content.res.TypedArray java class
private static final int STYLE_NUM_ENTRIES = 7;
private static final int STYLE_TYPE = 0;
private static final int STYLE_DATA = 1;
private static final int STYLE_ASSET_COOKIE = 2;
private static final int STYLE_RESOURCE_ID = 3;
private static final int STYLE_CHANGING_CONFIGURATIONS = 4;
private static final int STYLE_DENSITY = 5;
private static final int STYLE_SOURCE_STYLE_RESOURCE_ID = 6;
private static CppAssetManager2 systemCppAssetManager2;
private static long systemCppAssetManager2Ref;
private static boolean inNonSystemConstructor;
private static ApkAssets[] cachedSystemApkAssets;
private static ArraySet<ApkAssets> cachedSystemApkAssetsSet;
@RealObject AssetManager realAssetManager;
// @RealObject // protected AssetManager realObject;
// #define ATRACE_TAG ATRACE_TAG_RESOURCES
// #define LOG_TAG "asset"
//
// #include <inttypes.h>
// #include <linux/capability.h>
// #include <stdio.h>
// #include <sys/stat.h>
// #include <sys/system_properties.h>
// #include <sys/types.h>
// #include <sys/wait.h>
//
// #include <private/android_filesystem_config.h> // for AID_SYSTEM
//
// #include "android-base/logging.h"
// #include "android-base/properties.h"
// #include "android-base/stringprintf.h"
// #include "android_runtime/android_util_AssetManager.h"
// #include "android_runtime/AndroidRuntime.h"
// #include "android_util_Binder.h"
// #include "androidfw/Asset.h"
// #include "androidfw/AssetManager.h"
// #include "androidfw/AssetManager2.h"
// #include "androidfw/AttributeResolution.h"
// #include "androidfw/MutexGuard.h"
// #include "androidfw/ResourceTypes.h"
// #include "core_jni_helpers.h"
// #include "jni.h"
// #include "nativehelper/JNIHelp.h"
// #include "nativehelper/ScopedPrimitiveArray.h"
// #include "nativehelper/ScopedStringChars.h"
// #include "nativehelper/String.h"
// #include "utils/Log.h"
// #include "utils/misc.h"
// #include "utils/String.h"
// #include "utils/Trace.h"
//
// extern "C" int capget(cap_user_header_t hdrp, cap_user_data_t datap);
// extern "C" int capset(cap_user_header_t hdrp, const cap_user_data_t datap);
//
// using ::android::base::StringPrintf;
//
// namespace android {
//
// // ----------------------------------------------------------------------------
//
// static class typedvalue_offsets_t {
// jfieldID mType;
// jfieldID mData;
// jfieldID mString;
// jfieldID mAssetCookie;
// jfieldID mResourceId;
// jfieldID mChangingConfigurations;
// jfieldID mDensity;
// }
// static final typedvalue_offsets_t gTypedValueOffsets = new typedvalue_offsets_t();
//
// static class assetfiledescriptor_offsets_t {
// jfieldID mFd;
// jfieldID mStartOffset;
// jfieldID mLength;
// }
// static final assetfiledescriptor_offsets_t gAssetFileDescriptorOffsets = new
// assetfiledescriptor_offsets_t();
//
// static class assetmanager_offsets_t
// {
// jfieldID mObject;
// };
// // This is also used by asset_manager.cpp.
// static final assetmanager_offsets_t gAssetManagerOffsets = new assetmanager_offsets_t();
//
// static class apkassetsfields {
// jfieldID native_ptr;
// }
// static final apkassetsfields gApkAssetsFields = new apkassetsfields();
//
// static class sparsearray_offsets_t {
// jclass classObject;
// jmethodID constructor;
// jmethodID put;
// }
// static final sparsearray_offsets_t gSparseArrayOffsets = new sparsearray_offsets_t();
//
// static class configuration_offsets_t {
// jclass classObject;
// jmethodID constructor;
// jfieldID mSmallestScreenWidthDpOffset;
// jfieldID mScreenWidthDpOffset;
// jfieldID mScreenHeightDpOffset;
// }
// static final configuration_offsets_t gConfigurationOffsets = new configuration_offsets_t();
//
// jclass g_stringClass = nullptr;
//
// // ----------------------------------------------------------------------------
@Implementation(maxSdk = Q)
protected static void createSystemAssetsInZygoteLocked() {
_AssetManager28_ _assetManagerStatic_ = reflector(_AssetManager28_.class);
AssetManager sSystem = _assetManagerStatic_.getSystem();
if (sSystem != null) {
return;
}
if (systemCppAssetManager2 == null) {
// first time! let the framework create a CppAssetManager2 and an AssetManager, which we'll
// hang on to.
reflector(AssetManagerReflector.class).createSystemAssetsInZygoteLocked();
cachedSystemApkAssets = _assetManagerStatic_.getSystemApkAssets();
cachedSystemApkAssetsSet = _assetManagerStatic_.getSystemApkAssetsSet();
} else {
// reuse the shared system CppAssetManager2; create a new AssetManager around it.
_assetManagerStatic_.setSystemApkAssets(cachedSystemApkAssets);
_assetManagerStatic_.setSystemApkAssetsSet(cachedSystemApkAssetsSet);
sSystem =
ReflectionHelpers.callConstructor(
AssetManager.class, ClassParameter.from(boolean.class, true /*sentinel*/));
sSystem.setApkAssets(cachedSystemApkAssets, false /*invalidateCaches*/);
ReflectionHelpers.setStaticField(AssetManager.class, "sSystem", sSystem);
}
}
@Resetter
public static void reset() {
// todo: ShadowPicker doesn't discriminate properly between concrete shadow classes for
// resetters...
if (!useLegacy() && RuntimeEnvironment.getApiLevel() >= P) {
_AssetManager28_ _assetManagerStatic_ = reflector(_AssetManager28_.class);
_assetManagerStatic_.setSystemApkAssetsSet(null);
_assetManagerStatic_.setSystemApkAssets(null);
_assetManagerStatic_.setSystem(null);
}
}
// Java asset cookies have 0 as an invalid cookie, but TypedArray expects < 0.
static int ApkAssetsCookieToJavaCookie(ApkAssetsCookie cookie) {
return cookie.intValue() != kInvalidCookie ? (cookie.intValue() + 1) : -1;
}
static ApkAssetsCookie JavaCookieToApkAssetsCookie(int cookie) {
return ApkAssetsCookie.forInt(cookie > 0 ? (cookie - 1) : kInvalidCookie);
}
// This is called by zygote (running as user root) as part of preloadResources.
// static void NativeVerifySystemIdmaps(JNIEnv* /*env*/, jclass /*clazz*/) {
@Implementation(minSdk = P, maxSdk = Q)
protected static void nativeVerifySystemIdmaps() {
return;
// todo: maybe implement?
// switch (pid_t pid = fork()) {
// case -1:
// PLOG(ERROR) << "failed to fork for idmap";
// break;
//
// // child
// case 0: {
// struct __user_cap_header_struct capheader;
// struct __user_cap_data_struct capdata;
//
// memset(&capheader, 0, sizeof(capheader));
// memset(&capdata, 0, sizeof(capdata));
//
// capheader.version = _LINUX_CAPABILITY_VERSION;
// capheader.pid = 0;
//
// if (capget(&capheader, &capdata) != 0) {
// PLOG(ERROR) << "capget";
// exit(1);
// }
//
// capdata.effective = capdata.permitted;
// if (capset(&capheader, &capdata) != 0) {
// PLOG(ERROR) << "capset";
// exit(1);
// }
//
// if (setgid(AID_SYSTEM) != 0) {
// PLOG(ERROR) << "setgid";
// exit(1);
// }
//
// if (setuid(AID_SYSTEM) != 0) {
// PLOG(ERROR) << "setuid";
// exit(1);
// }
//
// // Generic idmap parameters
// char* argv[8];
// int argc = 0;
// struct stat st;
//
// memset(argv, 0, sizeof(argv));
// argv[argc++] = AssetManager.IDMAP_BIN;
// argv[argc++] = "--scan";
// argv[argc++] = AssetManager.TARGET_PACKAGE_NAME;
// argv[argc++] = AssetManager.TARGET_APK_PATH;
// argv[argc++] = AssetManager.IDMAP_DIR;
//
// // Directories to scan for overlays: if OVERLAY_THEME_DIR_PROPERTY is defined,
// // use OVERLAY_DIR/<value of OVERLAY_THEME_DIR_PROPERTY> in addition to OVERLAY_DIR.
// String overlay_theme_path = base.GetProperty(AssetManager.OVERLAY_THEME_DIR_PROPERTY,
// "");
// if (!overlay_theme_path.empty()) {
// overlay_theme_path = String(AssetManager.OVERLAY_DIR) + "/" + overlay_theme_path;
// if (stat(overlay_theme_path, &st) == 0) {
// argv[argc++] = overlay_theme_path;
// }
// }
//
// if (stat(AssetManager.OVERLAY_DIR, &st) == 0) {
// argv[argc++] = AssetManager.OVERLAY_DIR;
// }
//
// if (stat(AssetManager.PRODUCT_OVERLAY_DIR, &st) == 0) {
// argv[argc++] = AssetManager.PRODUCT_OVERLAY_DIR;
// }
//
// // Finally, invoke idmap (if any overlay directory exists)
// if (argc > 5) {
// execv(AssetManager.IDMAP_BIN, (char* const*)argv);
// PLOG(ERROR) << "failed to execv for idmap";
// exit(1); // should never get here
// } else {
// exit(0);
// }
// } break;
//
// // parent
// default:
// waitpid(pid, null, 0);
// break;
// }
}
@Implementation(minSdk = Build.VERSION_CODES.Q, maxSdk = Build.VERSION_CODES.R)
protected static String[] nativeCreateIdmapsForStaticOverlaysTargetingAndroid() {
return new String[0];
}
static int CopyValue(
/*JNIEnv* env,*/ ApkAssetsCookie cookie,
Res_value value,
int ref,
int type_spec_flags,
ResTable_config config,
TypedValue out_typed_value) {
out_typed_value.type = value.dataType;
out_typed_value.assetCookie = ApkAssetsCookieToJavaCookie(cookie);
out_typed_value.data = value.data;
out_typed_value.string = null;
out_typed_value.resourceId = ref;
out_typed_value.changingConfigurations = type_spec_flags;
if (config != null) {
out_typed_value.density = config.density;
}
return (int) (ApkAssetsCookieToJavaCookie(cookie));
}
// @Override
// protected int addAssetPathNative(String path) {
// throw new UnsupportedOperationException(); // todo
// }
@Override
Collection<Path> getAllAssetDirs() {
ApkAssets[] apkAssetsArray = reflector(_AssetManager28_.class, realAssetManager).getApkAssets();
ArrayList<Path> assetDirs = new ArrayList<>();
for (ApkAssets apkAssets : apkAssetsArray) {
long apk_assets_native_ptr =
((ShadowArscApkAssets9) Shadow.extract(apkAssets)).getNativePtr();
CppApkAssets cppApkAssets =
Registries.NATIVE_APK_ASSETS_REGISTRY.getNativeObject(apk_assets_native_ptr);
if (new File(cppApkAssets.GetPath()).isFile()) {
assetDirs.add(Fs.forJar(Paths.get(cppApkAssets.GetPath())).getPath("assets"));
} else {
assetDirs.add(Paths.get(cppApkAssets.GetPath()));
}
}
return assetDirs;
}
@Override
List<AssetPath> getAssetPaths() {
return AssetManagerForJavaObject(realAssetManager).getAssetPaths();
}
// ----------------------------------------------------------------------------
// interface AAssetManager {}
//
// // Let the opaque type AAssetManager refer to a guarded AssetManager2 instance.
// static class GuardedAssetManager implements AAssetManager {
// CppAssetManager2 guarded_assetmanager = new CppAssetManager2();
// }
static CppAssetManager2 NdkAssetManagerForJavaObject(
/* JNIEnv* env,*/ AssetManager jassetmanager) {
// long assetmanager_handle = env.GetLongField(jassetmanager, gAssetManagerOffsets.mObject);
long assetmanager_handle = ReflectionHelpers.getField(jassetmanager, "mObject");
CppAssetManager2 am =
Registries.NATIVE_ASSET_MANAGER_REGISTRY.getNativeObject(assetmanager_handle);
if (am == null) {
throw new IllegalStateException("AssetManager has been finalized!");
}
return am;
}
static CppAssetManager2 AssetManagerForJavaObject(/* JNIEnv* env,*/ AssetManager jassetmanager) {
return NdkAssetManagerForJavaObject(jassetmanager);
}
static CppAssetManager2 AssetManagerFromLong(long ptr) {
// return *AssetManagerForNdkAssetManager(reinterpret_cast<AAssetManager>(ptr));
return Registries.NATIVE_ASSET_MANAGER_REGISTRY.getNativeObject(ptr);
}
static ParcelFileDescriptor ReturnParcelFileDescriptor(
/* JNIEnv* env,*/ Asset asset, long[] out_offsets) throws FileNotFoundException {
final Ref<Long> start_offset = new Ref<>(0L);
final Ref<Long> length = new Ref<>(0L);
FileDescriptor fd = asset.openFileDescriptor(start_offset, length);
// asset.reset();
if (fd == null) {
throw new FileNotFoundException(
"This file can not be opened as a file descriptor; it is probably compressed");
}
long[] offsets =
out_offsets; // reinterpret_cast<long*>(env.GetPrimitiveArrayCritical(out_offsets, 0));
if (offsets == null) {
// close(fd);
return null;
}
offsets[0] = start_offset.get();
offsets[1] = length.get();
// env.ReleasePrimitiveArrayCritical(out_offsets, offsets, 0);
// jniCreateFileDescriptor(env, fd);
// if (file_desc == null) {
// close(fd);
// return null;
// }
// TODO: consider doing this
// return new ParcelFileDescriptor(file_desc);
return ParcelFileDescriptor.open(asset.getFile(), ParcelFileDescriptor.MODE_READ_ONLY);
}
/** Used for the creation of system assets. */
@Implementation(minSdk = P)
protected void __constructor__(boolean sentinel) {
inNonSystemConstructor = true;
try {
// call real constructor so field initialization happens.
invokeConstructor(
AssetManager.class, realAssetManager, ClassParameter.from(boolean.class, sentinel));
} finally {
inNonSystemConstructor = false;
}
}
// static jint NativeGetGlobalAssetCount(JNIEnv* /*env*/, jobject /*clazz*/) {
@Implementation(minSdk = P)
protected static int getGlobalAssetCount() {
return Asset.getGlobalCount();
}
// static jobject NativeGetAssetAllocations(JNIEnv* env, jobject /*clazz*/) {
@Implementation(minSdk = P)
protected static String getAssetAllocations() {
String alloc = Asset.getAssetAllocations();
if (alloc.length() <= 0) {
return null;
}
return alloc;
}
// static jint NativeGetGlobalAssetManagerCount(JNIEnv* /*env*/, jobject /*clazz*/) {
@Implementation(minSdk = P)
protected static int getGlobalAssetManagerCount() {
// TODO(adamlesinski): Switch to AssetManager2.
return CppAssetManager.getGlobalCount();
}
// static jlong NativeCreate(JNIEnv* /*env*/, jclass /*clazz*/) {
@Implementation(minSdk = P)
protected static long nativeCreate() {
// AssetManager2 needs to be protected by a lock. To avoid cache misses, we allocate the lock
// and
// AssetManager2 in a contiguous block (GuardedAssetManager).
// return reinterpret_cast<long>(new GuardedAssetManager());
long cppAssetManagerRef;
// we want to share a single instance of the system CppAssetManager2
if (inNonSystemConstructor) {
CppAssetManager2 appAssetManager = new CppAssetManager2();
cppAssetManagerRef = Registries.NATIVE_ASSET_MANAGER_REGISTRY.register(appAssetManager);
} else {
if (systemCppAssetManager2 == null) {
systemCppAssetManager2 = new CppAssetManager2();
systemCppAssetManager2Ref =
Registries.NATIVE_ASSET_MANAGER_REGISTRY.register(systemCppAssetManager2);
}
cppAssetManagerRef = systemCppAssetManager2Ref;
}
return cppAssetManagerRef;
}
// static void NativeDestroy(JNIEnv* /*env*/, jclass /*clazz*/, jlong ptr) {
@Implementation(minSdk = P)
protected static void nativeDestroy(long ptr) {
if (ptr == systemCppAssetManager2Ref) {
// don't destroy the shared system CppAssetManager2!
return;
}
// delete reinterpret_cast<GuardedAssetManager*>(ptr);
Registries.NATIVE_ASSET_MANAGER_REGISTRY.unregister(ptr);
}
// static void NativeSetApkAssets(JNIEnv* env, jclass /*clazz*/, jlong ptr,
// jobjectArray apk_assets_array, jboolean invalidate_caches) {
@Implementation(minSdk = P)
protected static void nativeSetApkAssets(
long ptr,
@NonNull android.content.res.ApkAssets[] apk_assets_array,
boolean invalidate_caches) {
ATRACE_NAME("AssetManager::SetApkAssets");
int apk_assets_len = apk_assets_array.length;
List<CppApkAssets> apk_assets = new ArrayList<>();
// apk_assets.reserve(apk_assets_len);
for (int i = 0; i < apk_assets_len; i++) {
android.content.res.ApkAssets apkAssets =
apk_assets_array[i]; // env.GetObjectArrayElement(apk_assets_array, i);
if (apkAssets == null) {
throw new NullPointerException(String.format("ApkAssets at index %d is null", i));
}
long apk_assets_native_ptr =
((ShadowArscApkAssets9) Shadow.extract(apkAssets)).getNativePtr();
// if (env.ExceptionCheck()) {
// return;
// }
apk_assets.add(Registries.NATIVE_APK_ASSETS_REGISTRY.getNativeObject(apk_assets_native_ptr));
}
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
assetmanager.SetApkAssets(apk_assets, invalidate_caches);
}
// static void NativeSetConfiguration(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint mcc, jint
// mnc,
// jstring locale, jint orientation, jint touchscreen, jint
// density,
// jint keyboard, jint keyboard_hidden, jint navigation,
// jint screen_width, jint screen_height,
// jint smallest_screen_width_dp, jint screen_width_dp,
// jint screen_height_dp, jint screen_layout, jint ui_mode,
// jint color_mode, jint major_version) {
@Implementation(minSdk = P)
protected static void nativeSetConfiguration(
long ptr,
int mcc,
int mnc,
@Nullable String locale,
int orientation,
int touchscreen,
int density,
int keyboard,
int keyboard_hidden,
int navigation,
int screen_width,
int screen_height,
int smallest_screen_width_dp,
int screen_width_dp,
int screen_height_dp,
int screen_layout,
int ui_mode,
int color_mode,
int major_version) {
ATRACE_NAME("AssetManager::SetConfiguration");
ResTable_config configuration = new ResTable_config();
// memset(&configuration, 0, sizeof(configuration));
configuration.mcc = (short) (mcc);
configuration.mnc = (short) (mnc);
configuration.orientation = (byte) (orientation);
configuration.touchscreen = (byte) (touchscreen);
configuration.density = (short) (density);
configuration.keyboard = (byte) (keyboard);
configuration.inputFlags = (byte) (keyboard_hidden);
configuration.navigation = (byte) (navigation);
configuration.screenWidth = (short) (screen_width);
configuration.screenHeight = (short) (screen_height);
configuration.smallestScreenWidthDp = (short) (smallest_screen_width_dp);
configuration.screenWidthDp = (short) (screen_width_dp);
configuration.screenHeightDp = (short) (screen_height_dp);
configuration.screenLayout = (byte) (screen_layout);
configuration.uiMode = (byte) (ui_mode);
configuration.colorMode = (byte) (color_mode);
configuration.sdkVersion = (short) (major_version);
if (locale != null) {
String locale_utf8 = locale;
CHECK(locale_utf8 != null);
configuration.setBcp47Locale(locale_utf8);
}
// Constants duplicated from Java class android.content.res.Configuration.
int kScreenLayoutRoundMask = 0x300;
int kScreenLayoutRoundShift = 8;
// In Java, we use a 32bit integer for screenLayout, while we only use an 8bit integer
// in C++. We must extract the round qualifier out of the Java screenLayout and put it
// into screenLayout2.
configuration.screenLayout2 =
(byte) ((screen_layout & kScreenLayoutRoundMask) >> kScreenLayoutRoundShift);
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
assetmanager.SetConfiguration(configuration);
}
// static jobject NativeGetAssignedPackageIdentifiers(JNIEnv* env, jclass /*clazz*/, jlong ptr) {
@Implementation(minSdk = P, maxSdk = Q)
protected static @NonNull SparseArray<String> nativeGetAssignedPackageIdentifiers(long ptr) {
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
SparseArray<String> sparse_array = new SparseArray<>();
if (sparse_array == null) {
// An exception is pending.
return null;
}
assetmanager.ForEachPackage(
(String package_name, byte package_id) -> {
String jpackage_name = package_name; // env.NewStringUTF(package_name);
if (jpackage_name == null) {
// An exception is pending.
return;
}
// env.CallVoidMethod(sparse_array, gSparseArrayOffsets.put, (int) (package_id),
// jpackage_name);
sparse_array.put(package_id, jpackage_name);
});
return sparse_array;
}
@Implementation(minSdk = R)
protected static SparseArray<String> nativeGetAssignedPackageIdentifiers(
long ptr, boolean includeOverlays, boolean includeLoaders) {
return nativeGetAssignedPackageIdentifiers(ptr);
}
// static jobjectArray NativeList(JNIEnv* env, jclass /*clazz*/, jlong ptr, jstring path) {
@Implementation(minSdk = P)
protected static @Nullable String[] nativeList(long ptr, @NonNull String path)
throws IOException {
String path_utf8 = path;
if (path_utf8 == null) {
// This will throw NPE.
return null;
}
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
AssetDir asset_dir = assetmanager.OpenDir(path_utf8);
if (asset_dir == null) {
throw new FileNotFoundException(path_utf8);
}
int file_count = asset_dir.getFileCount();
String[] array = new String[file_count]; // env.NewObjectArray(file_count, g_stringClass, null);
// if (array == null) {
// return null;
// }
for (int i = 0; i < file_count; i++) {
String java_string = asset_dir.getFileName(i).string();
// Check for errors creating the strings (if malformed or no memory).
// if (env.ExceptionCheck()) {
// return null;
// }
// env.SetObjectArrayElement(array, i, java_string);
array[i] = java_string;
// If we have a large amount of string in our array, we might overflow the
// local reference table of the VM.
// env.DeleteLocalRef(java_string);
}
return array;
}
// static jlong NativeOpenAsset(JNIEnv* env, jclass /*clazz*/, jlong ptr, jstring asset_path,
// jint access_mode) {
@Implementation(minSdk = P)
protected static long nativeOpenAsset(long ptr, @NonNull String asset_path, int access_mode)
throws FileNotFoundException {
String asset_path_utf8 = asset_path;
if (asset_path_utf8 == null) {
// This will throw NPE.
return 0;
}
ATRACE_NAME(String.format("AssetManager::OpenAsset(%s)", asset_path_utf8));
if (access_mode != Asset.AccessMode.ACCESS_UNKNOWN.mode()
&& access_mode != Asset.AccessMode.ACCESS_RANDOM.mode()
&& access_mode != Asset.AccessMode.ACCESS_STREAMING.mode()
&& access_mode != Asset.AccessMode.ACCESS_BUFFER.mode()) {
throw new IllegalArgumentException("Bad access mode");
}
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
Asset asset = assetmanager.Open(asset_path_utf8, Asset.AccessMode.fromInt(access_mode));
if (!isTruthy(asset)) {
throw new FileNotFoundException(asset_path_utf8);
}
return Registries.NATIVE_ASSET_REGISTRY.register(asset);
}
// static jobject NativeOpenAssetFd(JNIEnv* env, jclass /*clazz*/, jlong ptr, jstring asset_path,
// jlongArray out_offsets) {
@Implementation(minSdk = P)
protected static ParcelFileDescriptor nativeOpenAssetFd(
long ptr, @NonNull String asset_path, long[] out_offsets) throws IOException {
String asset_path_utf8 = asset_path;
if (asset_path_utf8 == null) {
// This will throw NPE.
return null;
}
ATRACE_NAME(String.format("AssetManager::OpenAssetFd(%s)", asset_path_utf8));
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
Asset asset = assetmanager.Open(asset_path_utf8, Asset.AccessMode.ACCESS_RANDOM);
if (!isTruthy(asset)) {
throw new FileNotFoundException(asset_path_utf8);
}
return ReturnParcelFileDescriptor(asset, out_offsets);
}
// static jlong NativeOpenNonAsset(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint jcookie,
// jstring asset_path, jint access_mode) {
@Implementation(minSdk = P)
protected static long nativeOpenNonAsset(
long ptr, int jcookie, @NonNull String asset_path, int access_mode)
throws FileNotFoundException {
ApkAssetsCookie cookie = JavaCookieToApkAssetsCookie(jcookie);
String asset_path_utf8 = asset_path;
if (asset_path_utf8 == null) {
// This will throw NPE.
return 0;
}
ATRACE_NAME(String.format("AssetManager::OpenNonAsset(%s)", asset_path_utf8));
if (access_mode != Asset.AccessMode.ACCESS_UNKNOWN.mode()
&& access_mode != Asset.AccessMode.ACCESS_RANDOM.mode()
&& access_mode != Asset.AccessMode.ACCESS_STREAMING.mode()
&& access_mode != Asset.AccessMode.ACCESS_BUFFER.mode()) {
throw new IllegalArgumentException("Bad access mode");
}
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
Asset asset;
if (cookie.intValue() != kInvalidCookie) {
asset =
assetmanager.OpenNonAsset(asset_path_utf8, cookie, Asset.AccessMode.fromInt(access_mode));
} else {
asset = assetmanager.OpenNonAsset(asset_path_utf8, Asset.AccessMode.fromInt(access_mode));
}
if (!isTruthy(asset)) {
throw new FileNotFoundException(asset_path_utf8);
}
return Registries.NATIVE_ASSET_REGISTRY.register(asset);
}
// static jobject NativeOpenNonAssetFd(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint jcookie,
// jstring asset_path, jlongArray out_offsets) {
@Implementation(minSdk = P)
protected static @Nullable ParcelFileDescriptor nativeOpenNonAssetFd(
long ptr, int jcookie, @NonNull String asset_path, @NonNull long[] out_offsets)
throws IOException {
ApkAssetsCookie cookie = JavaCookieToApkAssetsCookie(jcookie);
String asset_path_utf8 = asset_path;
if (asset_path_utf8 == null) {
// This will throw NPE.
return null;
}
ATRACE_NAME(String.format("AssetManager::OpenNonAssetFd(%s)", asset_path_utf8));
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
Asset asset;
if (cookie.intValue() != kInvalidCookie) {
asset = assetmanager.OpenNonAsset(asset_path_utf8, cookie, Asset.AccessMode.ACCESS_RANDOM);
} else {
asset = assetmanager.OpenNonAsset(asset_path_utf8, Asset.AccessMode.ACCESS_RANDOM);
}
if (!isTruthy(asset)) {
throw new FileNotFoundException(asset_path_utf8);
}
return ReturnParcelFileDescriptor(asset, out_offsets);
}
// static jlong NativeOpenXmlAsset(JNIEnv* env, jobject /*clazz*/, jlong ptr, jint jcookie,
// jstring asset_path) {
@Implementation(minSdk = P)
protected static long nativeOpenXmlAsset(long ptr, int jcookie, @NonNull String asset_path)
throws FileNotFoundException {
ApkAssetsCookie cookie = JavaCookieToApkAssetsCookie(jcookie);
String asset_path_utf8 = asset_path;
if (asset_path_utf8 == null) {
// This will throw NPE.
return 0;
}
ATRACE_NAME(String.format("AssetManager::OpenXmlAsset(%s)", asset_path_utf8));
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
Asset asset;
if (cookie.intValue() != kInvalidCookie) {
asset = assetmanager.OpenNonAsset(asset_path_utf8, cookie, Asset.AccessMode.ACCESS_RANDOM);
} else {
Ref<ApkAssetsCookie> cookieRef = new Ref<>(cookie);
asset = assetmanager.OpenNonAsset(asset_path_utf8, Asset.AccessMode.ACCESS_RANDOM, cookieRef);
cookie = cookieRef.get();
}
if (!isTruthy(asset)) {
throw new FileNotFoundException(asset_path_utf8);
}
// May be nullptr.
DynamicRefTable dynamic_ref_table = assetmanager.GetDynamicRefTableForCookie(cookie);
ResXMLTree xml_tree = new ResXMLTree(dynamic_ref_table);
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 NATIVE_RES_XML_TREES.register(xml_tree);
}
// static jint NativeGetResourceValue(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint resid,
// jshort density, jobject typed_value,
// jboolean resolve_references) {
@Implementation(minSdk = P)
protected static int nativeGetResourceValue(
long ptr,
@AnyRes int resid,
short density,
@NonNull TypedValue typed_value,
boolean resolve_references) {
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
final Ref<Res_value> value = new Ref<>(null);
final Ref<ResTable_config> selected_config = new Ref<>(null);
final Ref<Integer> flags = new Ref<>(0);
ApkAssetsCookie cookie =
assetmanager.GetResource(
resid, false /*may_be_bag*/, (short) (density), value, selected_config, flags);
if (cookie.intValue() == kInvalidCookie) {
return ApkAssetsCookieToJavaCookie(K_INVALID_COOKIE);
}
final Ref<Integer> ref = new Ref<>(resid);
if (resolve_references) {
cookie = assetmanager.ResolveReference(cookie, value, selected_config, flags, ref);
if (cookie.intValue() == kInvalidCookie) {
return ApkAssetsCookieToJavaCookie(K_INVALID_COOKIE);
}
}
return CopyValue(
cookie, value.get(), ref.get(), flags.get(), selected_config.get(), typed_value);
}
// static jint NativeGetResourceBagValue(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint resid,
// jint bag_entry_id, jobject typed_value) {
@Implementation(minSdk = P)
protected static int nativeGetResourceBagValue(
long ptr, @AnyRes int resid, int bag_entry_id, @NonNull TypedValue typed_value) {
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
ResolvedBag bag = assetmanager.GetBag(resid);
if (bag == null) {
return ApkAssetsCookieToJavaCookie(K_INVALID_COOKIE);
}
final Ref<Integer> type_spec_flags = new Ref<>(bag.type_spec_flags);
ApkAssetsCookie cookie = K_INVALID_COOKIE;
Res_value bag_value = null;
for (ResolvedBag.Entry entry : bag.entries) {
if (entry.key == (int) (bag_entry_id)) {
cookie = entry.cookie;
bag_value = entry.value;
// Keep searching (the old implementation did that).
}
}
if (cookie.intValue() == kInvalidCookie) {
return ApkAssetsCookieToJavaCookie(K_INVALID_COOKIE);
}
final Ref<Res_value> value = new Ref<>(bag_value);
final Ref<Integer> ref = new Ref<>(resid);
final Ref<ResTable_config> selected_config = new Ref<>(null);
cookie = assetmanager.ResolveReference(cookie, value, selected_config, type_spec_flags, ref);
if (cookie.intValue() == kInvalidCookie) {
return ApkAssetsCookieToJavaCookie(K_INVALID_COOKIE);
}
return CopyValue(cookie, value.get(), ref.get(), type_spec_flags.get(), null, typed_value);
}
// static jintArray NativeGetStyleAttributes(JNIEnv* env, jclass /*clazz*/, jlong ptr, jint resid)
// {
@Implementation(minSdk = P)
protected static @Nullable @AttrRes int[] nativeGetStyleAttributes(
long ptr, @StyleRes int resid) {
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
ResolvedBag bag = assetmanager.GetBag(resid);
if (bag == null) {
return null;
}
int[] array = new int[bag.entry_count];
// if (env.ExceptionCheck()) {
// return null;
// }
for (int i = 0; i < bag.entry_count; i++) {
int attr_resid = bag.entries[i].key;
// env.SetIntArrayRegion(array, i, 1, &attr_resid);
array[i] = attr_resid;
}
return array;
}
// static jobjectArray NativeGetResourceStringArray(JNIEnv* env, jclass /*clazz*/, jlong ptr,
// jint resid) {
@Implementation(minSdk = P)
protected static @Nullable String[] nativeGetResourceStringArray(long ptr, @ArrayRes int resid) {
CppAssetManager2 assetmanager = AssetManagerFromLong(ptr);
ResolvedBag bag = assetmanager.GetBag(resid);
if (bag == null) {
return null;
}
String[] array = new String[bag.entry_count];
if (array == null) {
return null;
}
for (int i = 0; i < bag.entry_count; i++) {
ResolvedBag.Entry entry = bag.entries[i];
// Resolve any references to their final value.
final Ref<Res_value> value = new Ref<>(entry.value);
final Ref<ResTable_config> selected_config = new Ref<>(null);
final Ref<Integer> flags = new Ref<>(0);
final Ref<Integer> ref = new Ref<>(0);
ApkAssetsCookie cookie =
assetmanager.ResolveReference(entry.cookie, value, selected_config, flags, ref);
if (cookie.intValue() == kInvalidCookie) {
return null;
}