-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathApkModule.java
More file actions
1266 lines (1247 loc) · 46.4 KB
/
ApkModule.java
File metadata and controls
1266 lines (1247 loc) · 46.4 KB
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
/*
* Copyright (C) 2022 github.com/REAndroid
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reandroid.apk;
import com.reandroid.archive.*;
import com.reandroid.archive.block.ApkSignatureBlock;
import com.reandroid.archive.io.ArchiveFileEntrySource;
import com.reandroid.archive.writer.ApkByteWriter;
import com.reandroid.archive.writer.ApkFileWriter;
import com.reandroid.archive.writer.ApkStreamWriter;
import com.reandroid.arsc.ApkFile;
import com.reandroid.arsc.array.PackageArray;
import com.reandroid.arsc.base.Block;
import com.reandroid.arsc.chunk.PackageBlock;
import com.reandroid.arsc.chunk.TableBlock;
import com.reandroid.arsc.chunk.TypeBlock;
import com.reandroid.arsc.chunk.xml.AndroidManifestBlock;
import com.reandroid.arsc.chunk.xml.ResXmlDocument;
import com.reandroid.arsc.container.SpecTypePair;
import com.reandroid.arsc.item.TableString;
import com.reandroid.arsc.model.FrameworkTable;
import com.reandroid.arsc.pool.TableStringPool;
import com.reandroid.arsc.value.Entry;
import com.reandroid.arsc.value.ResConfig;
import com.reandroid.identifiers.PackageIdentifier;
import com.reandroid.utils.collection.ArrayCollection;
import com.reandroid.utils.collection.CollectionUtil;
import com.reandroid.xml.XMLDocument;
import com.reandroid.xml.XMLElement;
import java.io.*;
import java.util.*;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
public class ApkModule implements ApkFile, Closeable {
private String moduleName;
private final ZipEntryMap zipEntryMap;
private boolean loadDefaultFramework = true;
private boolean mDisableLoadFramework = false;
private TableBlock mTableBlock;
private InputSource mTableOriginalSource;
private AndroidManifestBlock mManifestBlock;
private InputSource mManifestOriginalSource;
private final UncompressedFiles mUncompressedFiles;
private APKLogger apkLogger;
private ApkType mApkType;
private ApkSignatureBlock apkSignatureBlock;
private Integer preferredFramework;
private Closeable mCloseable;
private final List<TableBlock> mExternalFrameworks;
private final Map<Object, Object> mTagMaps;
public ApkModule(String moduleName, ZipEntryMap zipEntryMap){
this.moduleName = moduleName;
this.zipEntryMap = zipEntryMap;
this.mUncompressedFiles=new UncompressedFiles();
this.mUncompressedFiles.addPath(zipEntryMap);
this.mExternalFrameworks = new ArrayCollection<>();
this.zipEntryMap.setModuleName(moduleName);
this.mTagMaps = new HashMap<>();
}
public ApkModule(ZipEntryMap zipEntryMap){
this("base", zipEntryMap);
}
public ApkModule(){
this("base", new ZipEntryMap());
}
public void putTag(Object key, Object item){
mTagMaps.put(key, item);
}
public Object getTag(Object key){
return mTagMaps.get(key);
}
public Object removeTag(Object key){
return mTagMaps.remove(key);
}
public void clearTags(){
mTagMaps.clear();
}
public void addExternalFramework(File frameworkFile) throws IOException {
if(frameworkFile == null){
return;
}
logMessage("Loading external framework: " + frameworkFile);
FrameworkApk framework = FrameworkApk.loadTableBlock(frameworkFile);
framework.setAPKLogger(getApkLogger());
addExternalFramework(framework);
}
public void addExternalFramework(ApkModule apkModule){
if(apkModule == null || apkModule == this || !apkModule.hasTableBlock()){
return;
}
addExternalFramework(apkModule.getTableBlock());
}
public void addExternalFramework(TableBlock tableBlock){
if(tableBlock == null
|| tableBlock.getApkFile() == this
|| mExternalFrameworks.contains(tableBlock)){
return;
}
mExternalFrameworks.add(tableBlock);
updateExternalFramework();
}
public String refreshTable(){
TableBlock tableBlock = this.mTableBlock;
if(tableBlock != null){
return tableBlock.refreshFull();
}
return null;
}
public String refreshManifest(){
AndroidManifestBlock manifestBlock = this.mManifestBlock;
if(manifestBlock != null){
return manifestBlock.refreshFull();
}
return null;
}
public void validateResourceNames(){
if(!hasTableBlock()){
return;
}
logMessage("Validating resource names ...");
TableBlock tableBlock = getTableBlock();
for(PackageBlock packageBlock : tableBlock.listPackages()){
validateResourceNames(packageBlock);
}
}
public void validateResourceNames(PackageBlock packageBlock){
PackageIdentifier packageIdentifier = new PackageIdentifier();
packageIdentifier.load(packageBlock);
if(!packageIdentifier.hasDuplicateResources()){
return;
}
logMessage("Renaming duplicate resources ... ");
packageIdentifier.ensureUniqueResourceNames();
packageIdentifier.setResourceNamesToPackage(packageBlock);
}
public ApkSignatureBlock getApkSignatureBlock() {
return apkSignatureBlock;
}
public void setApkSignatureBlock(ApkSignatureBlock apkSignatureBlock) {
this.apkSignatureBlock = apkSignatureBlock;
}
public boolean hasSignatureBlock(){
return getApkSignatureBlock() != null;
}
public void dumpSignatureInfoFiles(File directory) throws IOException{
ApkSignatureBlock apkSignatureBlock = getApkSignatureBlock();
if(apkSignatureBlock == null){
throw new IOException("Don't have signature block");
}
apkSignatureBlock.writeSplitRawToDirectory(directory);
}
public void dumpSignatureBlock(File file) throws IOException{
ApkSignatureBlock apkSignatureBlock = getApkSignatureBlock();
if(apkSignatureBlock == null){
throw new IOException("Don't have signature block");
}
apkSignatureBlock.writeRaw(file);
}
public void scanSignatureInfoFiles(File directory) throws IOException{
if(!directory.isDirectory()){
throw new IOException("No such directory: " + directory);
}
ApkSignatureBlock apkSignatureBlock = this.apkSignatureBlock;
if(apkSignatureBlock == null){
apkSignatureBlock = new ApkSignatureBlock();
}
apkSignatureBlock.scanSplitFiles(directory);
setApkSignatureBlock(apkSignatureBlock);
}
public void loadSignatureBlock(File file) throws IOException{
if(!file.isFile()){
throw new IOException("No such file: " + file);
}
ApkSignatureBlock apkSignatureBlock = this.apkSignatureBlock;
if(apkSignatureBlock == null){
apkSignatureBlock = new ApkSignatureBlock();
}
apkSignatureBlock.read(file);
setApkSignatureBlock(apkSignatureBlock);
}
public String getSplit(){
if(!hasAndroidManifest()){
return null;
}
return getAndroidManifest().getSplit();
}
public List<TableBlock> getLoadedFrameworks(){
List<TableBlock> results = new ArrayCollection<>();
if(!hasTableBlock()){
return results;
}
TableBlock tableBlock = getTableBlock(false);
results.addAll(tableBlock.getFrameWorks());
return results;
}
public boolean isFrameworkVersionLoaded(Integer version){
if(version == null){
return false;
}
for(TableBlock tableBlock : getLoadedFrameworks()){
if(!(tableBlock instanceof FrameworkTable)){
continue;
}
FrameworkTable frame = (FrameworkTable) tableBlock;
if(version.equals(frame.getVersionCode())){
return true;
}
}
return false;
}
public FrameworkApk getLoadedFramework(Integer version, boolean onlyAndroid){
for(TableBlock tableBlock : getLoadedFrameworks()){
if(!(tableBlock instanceof FrameworkTable)){
continue;
}
FrameworkTable frame = (FrameworkTable) tableBlock;
if(onlyAndroid && !isAndroid(frame)){
continue;
}
if(version == null || version.equals(frame.getVersionCode())){
return (FrameworkApk) frame.getApkFile();
}
}
return null;
}
public FrameworkApk initializeAndroidFramework(Integer version) throws IOException {
TableBlock tableBlock = getTableBlock(false);
return initializeAndroidFramework(tableBlock, version);
}
public FrameworkApk initializeAndroidFramework(TableBlock tableBlock, Integer version) throws IOException {
if(mDisableLoadFramework || tableBlock == null || isAndroid(tableBlock)){
return null;
}
FrameworkApk exist = getLoadedFramework(version, true);
if(exist != null){
return exist;
}
logMessage("Initializing android framework ...");
FrameworkApk frameworkApk;
if(version == null){
logMessage("Can not read framework version, loading latest");
frameworkApk = AndroidFrameworks.getLatest();
}else {
logMessage("Loading android framework for version: " + version);
frameworkApk = AndroidFrameworks.getBestMatch(version);
}
FrameworkTable frameworkTable = frameworkApk.getTableBlock();
tableBlock.addFramework(frameworkTable);
logMessage("Initialized framework: " + frameworkApk.getName()
+ " (" + frameworkApk.getVersionName() + ")");
return frameworkApk;
}
public FrameworkApk initializeAndroidFramework(XMLDocument xmlDocument) throws IOException {
if(this.preferredFramework != null){
return initializeAndroidFramework(preferredFramework);
}
if(isAndroidCoreApp(xmlDocument)){
logMessage("Looks framework itself, skip loading frameworks");
return null;
}
Integer version = readVersionCode(xmlDocument);
return initializeAndroidFramework(version);
}
private boolean isAndroid(TableBlock tableBlock){
if(tableBlock instanceof FrameworkTable){
FrameworkTable frameworkTable = (FrameworkTable) tableBlock;
return frameworkTable.isAndroid();
}
return false;
}
private boolean isAndroidCoreApp(XMLDocument manifestDocument){
XMLElement root = manifestDocument.getDocumentElement();
if(root == null){
return false;
}
if(!"android".equals(root.getAttributeValue("package"))){
return false;
}
String coreApp = root.getAttributeValue("coreApp");
return "true".equals(coreApp);
}
private Integer readVersionCode(XMLDocument xmlDocument){
if(xmlDocument == null){
return null;
}
XMLElement manifestRoot = xmlDocument.getDocumentElement();
if(manifestRoot == null){
logMessage("WARN: Manifest root not found");
return null;
}
String versionString = manifestRoot.getAttributeValue("android:compileSdkVersion");
Integer version = null;
if(versionString!=null){
version = safeParseInteger(versionString);
}
if(version == null){
versionString = manifestRoot.getAttributeValue("platformBuildVersionCode");
if(versionString!=null){
version = safeParseInteger(versionString);
}
}
Integer target = null;
Iterator<XMLElement> iterator = manifestRoot
.getElements(AndroidManifestBlock.TAG_uses_sdk);
while (iterator.hasNext()){
XMLElement element = iterator.next();
versionString = element.getAttributeValue("android:targetSdkVersion");
if(versionString != null){
target = safeParseInteger(versionString);
}
}
if(version == null){
version = target;
}else if(target != null && target > version){
version = target;
}
return version;
}
private Integer safeParseInteger(String versionString) {
try{
return Integer.parseInt(versionString);
}catch (NumberFormatException exception){
logMessage("NumberFormatException on manifest version reading: '"
+versionString+"': "+exception.getMessage());
return null;
}
}
public void setPreferredFramework(Integer version) {
if(version != null && version.equals(preferredFramework)){
return;
}
this.preferredFramework = version;
if(version == null || mTableBlock == null){
return;
}
if(isFrameworkVersionLoaded(version)){
return;
}
logMessage("Initializing preferred framework: " + version);
mTableBlock.clearFrameworks();
FrameworkApk frameworkApk = AndroidFrameworks.getBestMatch(version);
AndroidFrameworks.setCurrent(frameworkApk);
mTableBlock.addFramework(frameworkApk.getTableBlock());
logMessage("Initialized framework: " + frameworkApk.getVersionCode());
}
public Integer getAndroidFrameworkVersion(){
if(preferredFramework != null){
return preferredFramework;
}
if(!hasAndroidManifest()){
return null;
}
AndroidManifestBlock manifest = getAndroidManifest();
Integer version = manifest.getCompileSdkVersion();
if(version == null){
version = manifest.getPlatformBuildVersionCode();
}
Integer target = manifest.getTargetSdkVersion();
if(version == null){
version = target;
}else if(target != null && target > version){
version = target;
}
return version;
}
public void removeResFilesWithEntry(int resourceId) {
removeResFilesWithEntry(resourceId, null, true);
}
public void removeResFilesWithEntry(int resourceId, ResConfig resConfig, boolean trimEntryArray) {
List<Entry> removedList = removeResFiles(resourceId, resConfig);
SpecTypePair specTypePair = null;
for(Entry entry:removedList){
if(entry == null || entry.isNull()){
continue;
}
if(trimEntryArray && specTypePair==null){
specTypePair = entry.getTypeBlock().getParentSpecTypePair();
}
entry.setNull(true);
}
if(specTypePair!=null){
specTypePair.removeNullEntries(resourceId);
}
}
public List<Entry> removeResFiles(int resourceId) {
return removeResFiles(resourceId, null);
}
public List<Entry> removeResFiles(int resourceId, ResConfig resConfig) {
ArrayCollection<Entry> results = new ArrayCollection<>();
if(resourceId == 0 && resConfig == null){
return results;
}
List<ResFile> resFileList = listResFiles(resourceId, resConfig);
ZipEntryMap zipEntryMap = getZipEntryMap();
for(ResFile resFile:resFileList){
results.addAll(resFile.iterator());
zipEntryMap.remove(resFile.getInputSource());
}
return results;
}
public XMLDocument decodeXMLFile(String path) throws IOException {
ResXmlDocument resXmlDocument = loadResXmlDocument(path);
AndroidManifestBlock manifest = getAndroidManifest();
int pkgId = manifest.guessCurrentPackageId();
if(pkgId != 0 && hasTableBlock()){
PackageBlock packageBlock = getTableBlock().pickOne(pkgId);
if(packageBlock != null){
resXmlDocument.setPackageBlock(packageBlock);
}
}
return resXmlDocument.decodeToXml();
}
public List<DexFileInputSource> listDexFiles(){
List<DexFileInputSource> results = new ArrayCollection<>();
for(InputSource source: getInputSources()){
if(DexFileInputSource.isDexName(source.getAlias())){
DexFileInputSource inputSource;
if(source instanceof DexFileInputSource){
inputSource = (DexFileInputSource)source;
}else {
inputSource = new DexFileInputSource(source.getAlias(), source);
}
results.add(inputSource);
}
}
DexFileInputSource.sort(results);
return results;
}
public boolean isBaseModule(){
if(!hasAndroidManifest()){
return false;
}
AndroidManifestBlock manifest;
try {
manifest= getAndroidManifest();
return !(manifest.isSplit() || manifest.getMainActivity()==null);
} catch (Exception ignored) {
return false;
}
}
public String getModuleName(){
return moduleName;
}
public void setModuleName(String moduleName){
if(moduleName == null){
throw new NullPointerException();
}
this.moduleName = moduleName;
this.zipEntryMap.setModuleName(moduleName);
}
public void writeApk(File file) throws IOException {
writeApk(file, null);
}
public void writeApk(File file, WriteProgress progress) throws IOException {
ApkFileWriter writer = createApkFileWriter(file);
writer.setWriteProgress(progress);
writer.write();
}
public byte[] writeApkBytes() throws IOException {
ApkByteWriter writer = createApkByteWriter();
writer.write();
return writer.toByteArray();
}
public void writeApk(OutputStream outputStream) throws IOException {
createApkStreamWriter(outputStream).write();
}
public ApkFileWriter createApkFileWriter(File file) throws IOException {
ZipEntryMap zipEntryMap = getZipEntryMap();
UncompressedFiles uf = getUncompressedFiles();
uf.apply(zipEntryMap);
ApkFileWriter writer = new ApkFileWriter(file, zipEntryMap.toArray(true));
writer.setAPKLogger(getApkLogger());
writer.setApkSignatureBlock(getApkSignatureBlock());
writer.setArchiveInfo(zipEntryMap.getArchiveInfo());
return writer;
}
public ApkByteWriter createApkByteWriter() {
ZipEntryMap zipEntryMap = getZipEntryMap();
UncompressedFiles uf = getUncompressedFiles();
uf.apply(zipEntryMap);
ApkByteWriter writer = new ApkByteWriter(zipEntryMap.toArray(true));
writer.setAPKLogger(getApkLogger());
writer.setApkSignatureBlock(getApkSignatureBlock());
writer.setArchiveInfo(zipEntryMap.getArchiveInfo());
return writer;
}
public ApkStreamWriter createApkStreamWriter(OutputStream outputStream) {
ZipEntryMap zipEntryMap = getZipEntryMap();
UncompressedFiles uf = getUncompressedFiles();
uf.apply(zipEntryMap);
ApkStreamWriter writer = new ApkStreamWriter(outputStream,
zipEntryMap.toArray(true));
writer.setAPKLogger(getApkLogger());
writer.setApkSignatureBlock(getApkSignatureBlock());
writer.setArchiveInfo(zipEntryMap.getArchiveInfo());
return writer;
}
public void uncompressNonXmlResFiles() {
for(ResFile resFile:listResFiles()){
if(resFile.isBinaryXml()){
continue;
}
resFile.getInputSource().setMethod(ZipEntry.STORED);
}
}
public UncompressedFiles getUncompressedFiles(){
return mUncompressedFiles;
}
public void removeDir(String dirName){
getZipEntryMap().removeDir(dirName);
}
public void validateResourcesDir() {
List<ResFile> resFileList = listResFiles();
Set<String> existPaths=new HashSet<>();
InputSource[] sourceList = getInputSources();
for(InputSource inputSource:sourceList){
existPaths.add(inputSource.getAlias());
}
for(ResFile resFile:resFileList){
String path = resFile.getFilePath();
String pathNew = resFile.validateTypeDirectoryName();
if(pathNew == null || pathNew.equals(path)){
continue;
}
if(existPaths.contains(pathNew)){
continue;
}
existPaths.remove(path);
existPaths.add(pathNew);
resFile.setFilePath(pathNew);
if(resFile.getInputSource().getMethod() == ZipEntry.STORED){
getUncompressedFiles().replacePath(path, pathNew);
}
logVerbose("Dir validated: '"+path+"' -> '"+pathNew+"'");
}
getTableBlock().refresh();
}
public void setResourcesRootDir(String dirName) {
List<ResFile> resFileList = listResFiles();
Set<String> existPaths=new HashSet<>();
InputSource[] sourceList = getInputSources();
for(InputSource inputSource:sourceList){
existPaths.add(inputSource.getAlias());
}
for(ResFile resFile:resFileList){
String path=resFile.getFilePath();
String pathNew=ApkUtil.replaceRootDir(path, dirName);
if(existPaths.contains(pathNew)){
continue;
}
existPaths.remove(path);
existPaths.add(pathNew);
resFile.setFilePath(pathNew);
if(resFile.getInputSource().getMethod() == ZipEntry.STORED){
getUncompressedFiles().replacePath(path, pathNew);
}
logVerbose("Root changed: '"+path+"' -> '"+pathNew+"'");
}
getTableBlock().refresh();
}
public List<ResFile> listResFiles() {
return listResFiles(0, null);
}
public List<ResFile> listResFiles(int resourceId, ResConfig resConfig) {
List<ResFile> results = new ArrayCollection<>();
TableBlock tableBlock = getTableBlock();
if (tableBlock == null){
return results;
}
TableStringPool stringPool= tableBlock.getStringPool();
for(InputSource inputSource : getInputSources()){
String name = inputSource.getAlias();
Iterator<TableString> iterator = stringPool.getAll(name);
while (iterator.hasNext()){
TableString tableString = iterator.next();
List<Entry> entryList = filterResFileEntries(tableString, resourceId, resConfig);
if(!entryList.isEmpty()) {
ResFile resFile = new ResFile(inputSource, entryList);
results.add(resFile);
}
}
}
return results;
}
public boolean removeResFile(String path) {
return removeResFile(path, true);
}
public boolean removeResFile(String path, boolean keepResourceId) {
InputSource inputSource = getInputSource(path);
if(inputSource == null) {
return false;
}
ResFile resFile = getResFile(path);
if(resFile == null) {
return false;
}
resFile.delete(keepResourceId);
removeInputSource(path);
return true;
}
public ResFile getResFile(String path) {
InputSource inputSource = getInputSource(path);
if(inputSource == null) {
return null;
}
List<Entry> entryList = listReferencedEntries(path);
if(entryList.isEmpty()) {
return null;
}
return new ResFile(inputSource, entryList);
}
public List<Entry> listReferencedEntries(String path) {
ArrayCollection<Entry> results = new ArrayCollection<>();
TableBlock tableBlock = getTableBlock();
if (tableBlock != null) {
TableStringPool stringPool = tableBlock.getStringPool();
Iterator<TableString> iterator = stringPool.getAll(path);
Predicate<Entry> filter = entry -> entry.isScalar() &&
TypeBlock.canHaveResourceFile(entry.getTypeName());
while (iterator.hasNext()) {
results.addAll(iterator.next().getEntries(filter));
}
}
return results;
}
private List<Entry> filterResFileEntries(TableString tableString, int resourceId, ResConfig resConfig){
Iterator<Entry> itr = tableString.getEntries(item -> {
if(!item.isScalar() ||
!TypeBlock.canHaveResourceFile(item.getTypeName())){
return false;
}
if(resourceId != 0 && resourceId != item.getResourceId()){
return false;
}
return resConfig == null || resConfig.equals(item.getResConfig());
});
return CollectionUtil.toList(itr);
}
public String getPackageName(){
if(hasAndroidManifest()){
return getAndroidManifest().getPackageName();
}
if(!hasTableBlock()){
return null;
}
TableBlock tableBlock=getTableBlock();
PackageArray pkgArray = tableBlock.getPackageArray();
PackageBlock pkg = pkgArray.get(0);
if(pkg==null){
return null;
}
return pkg.getName();
}
public void setPackageName(String name) {
String old=getPackageName();
if(hasAndroidManifest()){
getAndroidManifest().setPackageName(name);
}
if(!hasTableBlock()){
return;
}
TableBlock tableBlock=getTableBlock();
PackageArray pkgArray = tableBlock.getPackageArray();
for(PackageBlock pkg:pkgArray.listItems()){
if(pkgArray.size()==1){
pkg.setName(name);
continue;
}
String pkgName=pkg.getName();
if(pkgName.startsWith(old)){
pkgName=pkgName.replace(old, name);
pkg.setName(pkgName);
}
}
}
// Use hasAndroidManifest
@Deprecated
public boolean hasAndroidManifestBlock(){
return hasAndroidManifest();
}
public boolean hasAndroidManifest(){
return mManifestBlock!=null
|| getZipEntryMap().getInputSource(AndroidManifestBlock.FILE_NAME)!=null;
}
public boolean hasTableBlock(){
return mTableBlock!=null
|| getZipEntryMap().getInputSource(TableBlock.FILE_NAME)!=null;
}
public void destroy(){
getZipEntryMap().clear();
AndroidManifestBlock manifestBlock = this.mManifestBlock;
if(manifestBlock!=null){
manifestBlock.destroy();
this.mManifestBlock = null;
}
TableBlock tableBlock = this.mTableBlock;
if(tableBlock!=null){
mExternalFrameworks.clear();
tableBlock.clear();
this.mTableBlock = null;
}
try {
close();
} catch (IOException ignored) {
}
}
public void setManifest(AndroidManifestBlock manifestBlock){
ZipEntryMap archive = getZipEntryMap();
if(manifestBlock==null){
mManifestBlock = null;
mManifestOriginalSource = null;
archive.remove(AndroidManifestBlock.FILE_NAME);
return;
}
manifestBlock.setApkFile(this);
BlockInputSource<AndroidManifestBlock> source =
new BlockInputSource<>(AndroidManifestBlock.FILE_NAME, manifestBlock);
source.setMethod(ZipEntry.STORED);
source.setSort(0);
archive.add(source);
mManifestBlock = manifestBlock;
}
public void setTableBlock(TableBlock tableBlock){
ZipEntryMap archive = getZipEntryMap();
if(tableBlock == null){
mTableBlock = null;
mTableOriginalSource = null;
archive.remove(TableBlock.FILE_NAME);
unlinkLoadedManifest();
return;
}
tableBlock.setApkFile(this);
BlockInputSource<TableBlock> source =
new BlockInputSource<>(TableBlock.FILE_NAME, tableBlock);
archive.add(source);
source.setMethod(ZipEntry.STORED);
source.setSort(1);
getUncompressedFiles().addPath(source);
mTableBlock = tableBlock;
updateExternalFramework();
ensureLoadedManifestLinked();
}
/**
* Use getAndroidManifest()
* */
@Deprecated
public AndroidManifestBlock getAndroidManifestBlock(){
return getAndroidManifest();
}
@Override
public AndroidManifestBlock getAndroidManifest() {
if(mManifestBlock!=null){
return mManifestBlock;
}
InputSource inputSource = getInputSource(AndroidManifestBlock.FILE_NAME);
if(inputSource == null){
return null;
}
setManifestOriginalSource(inputSource);
InputStream inputStream;
try {
inputStream = inputSource.openStream();
AndroidManifestBlock manifestBlock = AndroidManifestBlock.load(inputStream);
inputStream.close();
this.mManifestBlock = manifestBlock;
BlockInputSource<AndroidManifestBlock> blockInputSource = new BlockInputSource<>(
inputSource.getName(),manifestBlock);
blockInputSource.copyAttributes(inputSource);
addInputSource(blockInputSource);
ensureLoadedManifestLinked();
onManifestBlockLoaded(manifestBlock);
} catch (IOException exception) {
throw new IllegalArgumentException(exception);
}
return mManifestBlock;
}
private void onManifestBlockLoaded(AndroidManifestBlock manifestBlock){
initializeApkType(manifestBlock);
}
public TableBlock getTableBlock(boolean initFramework) {
TableBlock tableBlock = this.mTableBlock;
if(tableBlock == null){
if(!hasTableBlock()){
return null;
}
try {
tableBlock = loadTableBlock();
this.mTableBlock = tableBlock;
if(initFramework && loadDefaultFramework){
Integer version = getAndroidFrameworkVersion();
initializeAndroidFramework(tableBlock, version);
}
updateExternalFramework();
} catch (IOException exception) {
throw new IllegalArgumentException(exception);
}
ensureLoadedManifestLinked();
}
return tableBlock;
}
private void ensureLoadedManifestLinked() {
TableBlock tableBlock = this.mTableBlock;
if(tableBlock == null) {
return;
}
AndroidManifestBlock manifestBlock = this.mManifestBlock;
if(manifestBlock == null) {
return;
}
PackageBlock packageBlock = manifestBlock.getPackageBlock();
if(packageBlock != null) {
TableBlock linkedTable = packageBlock.getTableBlock();
if(linkedTable == tableBlock) {
return;
}
}
packageBlock = tableBlock.pickOne(manifestBlock.guessCurrentPackageId());
if(packageBlock == null) {
packageBlock = tableBlock.pickOrEmptyPackage();
}
if(packageBlock != null) {
manifestBlock.setPackageBlock(packageBlock);
manifestBlock.setApkFile(this);
}
}
private void unlinkLoadedManifest() {
AndroidManifestBlock manifestBlock = this.mManifestBlock;
if(manifestBlock == null) {
return;
}
manifestBlock.setPackageBlock(null);
manifestBlock.setApkFile(null);
}
private void updateExternalFramework(){
TableBlock tableBlock = mTableBlock;
if(tableBlock == null){
return;
}
for(TableBlock framework : mExternalFrameworks){
tableBlock.addFramework(framework);
}
}
public void discardManifestChanges(){
getZipEntryMap().add(getManifestOriginalSource());
}
public void keepManifestChanges(){
mManifestOriginalSource = null;
}
public InputSource getManifestOriginalSource(){
InputSource inputSource = this.mManifestOriginalSource;
if(inputSource == null){
inputSource = getInputSource(AndroidManifestBlock.FILE_NAME);
mManifestOriginalSource = inputSource;
}
return inputSource;
}
private void setManifestOriginalSource(InputSource inputSource){
if(mManifestOriginalSource == null
&& !(inputSource instanceof BlockInputSource)){
mManifestOriginalSource = inputSource;
}
}
public void discardTableBlockChanges(){
getZipEntryMap().add(getTableOriginalSource());
}
public void keepTableBlockChanges(){
mTableOriginalSource = null;
}
public InputSource getTableOriginalSource(){
InputSource inputSource = this.mTableOriginalSource;
if(inputSource == null){
inputSource = getInputSource(TableBlock.FILE_NAME);
mTableOriginalSource = inputSource;
}
return inputSource;
}
private void setTableOriginalSource(InputSource inputSource){
if(mTableOriginalSource == null
&& !(inputSource instanceof BlockInputSource)){
mTableOriginalSource = inputSource;
}
}
@Override
public TableBlock getTableBlock() {
if(mTableBlock != null){
return mTableBlock;
}
checkExternalFramework();
checkSelfFramework();
return getTableBlock(!mDisableLoadFramework);
}
@Override
public TableBlock getLoadedTableBlock(){
return mTableBlock;
}
private void checkExternalFramework(){
if(mDisableLoadFramework || preferredFramework != null){
return;
}
if(mExternalFrameworks.size() == 0){
return;
}
mDisableLoadFramework = true;
}
private void checkSelfFramework(){
if(mDisableLoadFramework || preferredFramework != null){
return;
}
AndroidManifestBlock manifest = getAndroidManifest();
if(manifest == null){
return;
}
if(manifest.isCoreApp() == null
|| !"android".equals(manifest.getPackageName())){
return;
}
if(manifest.guessCurrentPackageId() != 0x01){
return;
}
logMessage("Looks like framework apk, skip loading framework");
mDisableLoadFramework = true;
}
@Override
public ResXmlDocument getResXmlDocument(String path) {
InputSource inputSource = getInputSource(path);
if(inputSource != null){
try {
return loadResXmlDocument(inputSource);
} catch (IOException ignored) {
}
}
return null;
}
@Override
public ResXmlDocument loadResXmlDocument(String path) throws IOException{
InputSource inputSource = getInputSource(path);
if(inputSource == null){
throw new FileNotFoundException("No such file in apk: " + path);
}
return loadResXmlDocument(inputSource);
}
public ResXmlDocument loadResXmlDocument(InputSource inputSource) throws IOException{
ResXmlDocument resXmlDocument = null;
if(inputSource instanceof BlockInputSource){
Block block = ((BlockInputSource<?>) inputSource).getBlock();
if(block instanceof ResXmlDocument){
resXmlDocument = (ResXmlDocument) block;
}
}
if(resXmlDocument == null){
resXmlDocument = new ResXmlDocument();
resXmlDocument.readBytes(inputSource.openStream());
}
resXmlDocument.setApkFile(this);
if(resXmlDocument.getPackageBlock() == null){
resXmlDocument.setPackageBlock(findPackageForPath(inputSource.getAlias()));
}
return resXmlDocument;
}
private PackageBlock findPackageForPath(String path) {
TableBlock tableBlock = getTableBlock();
if(tableBlock == null){
return null;
}
if(tableBlock.size() == 1){
return tableBlock.get(0);
}
PackageBlock packageBlock = CollectionUtil.getFirst(
tableBlock.getStringPool().getUsers(PackageBlock.class, path));
if(packageBlock == null){
packageBlock = tableBlock.pickOne();
}
return packageBlock;
}