-
Notifications
You must be signed in to change notification settings - Fork 4
/
Resource.cpp
3251 lines (2907 loc) · 120 KB
/
Resource.cpp
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 2006 The Android Open Source Project
//
// Build resource files from raw assets.
//
#include "AaptAssets.h"
#include "AaptUtil.h"
#include "AaptXml.h"
#include "CacheUpdater.h"
#include "CrunchCache.h"
#include "FileFinder.h"
#include "Images.h"
#include "IndentPrinter.h"
#include "Main.h"
#include "ResourceTable.h"
#include "StringPool.h"
#include "Symbol.h"
#include "WorkQueue.h"
#include "XMLNode.h"
#include <map>
#include <algorithm>
// STATUST: mingw does seem to redefine UNKNOWN_ERROR from our enum value, so a cast is necessary.
#if !defined(_WIN32)
# define ZD "%zd"
# define ZD_TYPE ssize_t
# define STATUST(x) x
#else
# define ZD "%ld"
# define ZD_TYPE long
# define STATUST(x) (status_t)x
#endif
// Set to true for noisy debug output.
static const bool kIsDebug = false;
// Number of threads to use for preprocessing images.
static const size_t MAX_THREADS = 4;
// ==========================================================================
// ==========================================================================
// ==========================================================================
class PackageInfo
{
public:
PackageInfo()
{
}
~PackageInfo()
{
}
status_t parsePackage(const sp<AaptGroup>& grp);
};
// ==========================================================================
// ==========================================================================
// ==========================================================================
String8 parseResourceName(const String8& leaf)
{
const char* firstDot = strchr(leaf.string(), '.');
const char* str = leaf.string();
if (firstDot) {
return String8(str, firstDot-str);
} else {
return String8(str);
}
}
ResourceTypeSet::ResourceTypeSet()
:RefBase(),
KeyedVector<String8,sp<AaptGroup> >()
{
}
FilePathStore::FilePathStore()
:RefBase(),
Vector<String8>()
{
}
class ResourceDirIterator
{
public:
ResourceDirIterator(const sp<ResourceTypeSet>& set, const String8& resType)
: mResType(resType), mSet(set), mSetPos(0), mGroupPos(0)
{
memset(&mParams, 0, sizeof(ResTable_config));
}
inline const sp<AaptGroup>& getGroup() const { return mGroup; }
inline const sp<AaptFile>& getFile() const { return mFile; }
inline const String8& getBaseName() const { return mBaseName; }
inline const String8& getLeafName() const { return mLeafName; }
inline String8 getPath() const { return mPath; }
inline const ResTable_config& getParams() const { return mParams; }
enum {
EOD = 1
};
ssize_t next()
{
while (true) {
sp<AaptGroup> group;
sp<AaptFile> file;
// Try to get next file in this current group.
if (mGroup != NULL && mGroupPos < mGroup->getFiles().size()) {
group = mGroup;
file = group->getFiles().valueAt(mGroupPos++);
// Try to get the next group/file in this directory
} else if (mSetPos < mSet->size()) {
mGroup = group = mSet->valueAt(mSetPos++);
if (group->getFiles().size() < 1) {
continue;
}
file = group->getFiles().valueAt(0);
mGroupPos = 1;
// All done!
} else {
return EOD;
}
mFile = file;
String8 leaf(group->getLeaf());
mLeafName = String8(leaf);
mParams = file->getGroupEntry().toParams();
if (kIsDebug) {
printf("Dir %s: mcc=%d mnc=%d lang=%c%c cnt=%c%c orient=%d ui=%d density=%d touch=%d key=%d inp=%d nav=%d\n",
group->getPath().string(), mParams.mcc, mParams.mnc,
mParams.language[0] ? mParams.language[0] : '-',
mParams.language[1] ? mParams.language[1] : '-',
mParams.country[0] ? mParams.country[0] : '-',
mParams.country[1] ? mParams.country[1] : '-',
mParams.orientation, mParams.uiMode,
mParams.density, mParams.touchscreen, mParams.keyboard,
mParams.inputFlags, mParams.navigation);
}
mPath = "res";
mPath.appendPath(file->getGroupEntry().toDirName(mResType));
mPath.appendPath(leaf);
mBaseName = parseResourceName(leaf);
if (mBaseName == "") {
fprintf(stderr, "Error: malformed resource filename %s\n",
file->getPrintableSource().string());
return UNKNOWN_ERROR;
}
if (kIsDebug) {
printf("file name=%s\n", mBaseName.string());
}
return NO_ERROR;
}
}
private:
String8 mResType;
const sp<ResourceTypeSet> mSet;
size_t mSetPos;
sp<AaptGroup> mGroup;
size_t mGroupPos;
sp<AaptFile> mFile;
String8 mBaseName;
String8 mLeafName;
String8 mPath;
ResTable_config mParams;
};
class AnnotationProcessor {
public:
AnnotationProcessor() : mDeprecated(false), mSystemApi(false) { }
void preprocessComment(String8& comment) {
if (comment.size() > 0) {
if (comment.contains("@deprecated")) {
mDeprecated = true;
}
if (comment.removeAll("@SystemApi")) {
mSystemApi = true;
}
}
}
void printAnnotations(FILE* fp, const char* indentStr) {
if (mDeprecated) {
fprintf(fp, "%s@Deprecated\n", indentStr);
}
if (mSystemApi) {
fprintf(fp, "%[email protected]\n", indentStr);
}
}
private:
bool mDeprecated;
bool mSystemApi;
};
// ==========================================================================
// ==========================================================================
// ==========================================================================
bool isValidResourceType(const String8& type)
{
return type == "anim" || type == "animator" || type == "interpolator"
|| type == "transition"
|| type == "drawable" || type == "layout"
|| type == "values" || type == "xml" || type == "raw"
|| type == "color" || type == "menu" || type == "mipmap";
}
static status_t parsePackage(Bundle* bundle, const sp<AaptAssets>& assets,
const sp<AaptGroup>& grp)
{
if (grp->getFiles().size() != 1) {
fprintf(stderr, "warning: Multiple AndroidManifest.xml files found, using %s\n",
grp->getFiles().valueAt(0)->getPrintableSource().string());
}
sp<AaptFile> file = grp->getFiles().valueAt(0);
ResXMLTree block;
status_t err = parseXMLResource(file, &block);
if (err != NO_ERROR) {
return err;
}
//printXMLBlock(&block);
ResXMLTree::event_code_t code;
while ((code=block.next()) != ResXMLTree::START_TAG
&& code != ResXMLTree::END_DOCUMENT
&& code != ResXMLTree::BAD_DOCUMENT) {
}
size_t len;
if (code != ResXMLTree::START_TAG) {
fprintf(stderr, "%s:%d: No start tag found\n",
file->getPrintableSource().string(), block.getLineNumber());
return UNKNOWN_ERROR;
}
if (strcmp16(block.getElementName(&len), String16("manifest").string()) != 0) {
fprintf(stderr, "%s:%d: Invalid start tag %s, expected <manifest>\n",
file->getPrintableSource().string(), block.getLineNumber(),
String8(block.getElementName(&len)).string());
return UNKNOWN_ERROR;
}
ssize_t nameIndex = block.indexOfAttribute(NULL, "package");
if (nameIndex < 0) {
fprintf(stderr, "%s:%d: <manifest> does not have package attribute.\n",
file->getPrintableSource().string(), block.getLineNumber());
return UNKNOWN_ERROR;
}
assets->setPackage(String8(block.getAttributeStringValue(nameIndex, &len)));
ssize_t revisionCodeIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE, "revisionCode");
if (revisionCodeIndex >= 0) {
bundle->setRevisionCode(String8(block.getAttributeStringValue(revisionCodeIndex, &len)).string());
}
String16 uses_sdk16("uses-sdk");
while ((code=block.next()) != ResXMLTree::END_DOCUMENT
&& code != ResXMLTree::BAD_DOCUMENT) {
if (code == ResXMLTree::START_TAG) {
if (strcmp16(block.getElementName(&len), uses_sdk16.string()) == 0) {
ssize_t minSdkIndex = block.indexOfAttribute(RESOURCES_ANDROID_NAMESPACE,
"minSdkVersion");
if (minSdkIndex >= 0) {
const char16_t* minSdk16 = block.getAttributeStringValue(minSdkIndex, &len);
const char* minSdk8 = strdup(String8(minSdk16).string());
bundle->setManifestMinSdkVersion(minSdk8);
}
}
}
}
return NO_ERROR;
}
// ==========================================================================
// ==========================================================================
// ==========================================================================
// ============ Res Obfuscation begin ============
// Set to true for noisy debug output.
static const bool kIsResObfDebug = true;
// Res Obfuscation switch
static const bool kIsResObfEnable = true;
// resource path description
class ResPathDesc
{
public:
int size;
String8 path;
};
static std::map<String8, ResPathDesc> sMap;
// obtain file extension name
String8 parseExtensionName(const String8& leaf)
{
const char* firstDot = strchr(leaf.string(), '.');
if (firstDot) {
return String8(firstDot);
} else {
return String8("");
}
}
// index to path, eg: 0->a, 1->b
void index2path(String8& sb, int index) {
int r = index / 37;
if (r > 0) {
index2path(sb, r - 1);
}
int offset = index % 37;
if (offset < 10) {
offset = offset + 48;
} else if (offset == 10) {
offset = 95;
} else {
offset = offset + 86;
}
char c[1] = {(char) offset};
sb.append(c, 1);
}
// originalPath -> obfuscationPath
String8 getObfuscationPath(String8 originalPath) {
String8 obfuscationPath("r/");
String8 originalPathDir = originalPath.getPathDir();
int curIndex;
std::map<String8, ResPathDesc>::iterator item = sMap.find(originalPathDir);
if (item != sMap.end()) {
ResPathDesc& desc = item->second;
obfuscationPath = desc.path;
curIndex = desc.size++;
} else {
index2path(obfuscationPath, sMap.size());
ResPathDesc desc;
desc.size = 0;
desc.path = obfuscationPath;
curIndex = desc.size++;
sMap[originalPathDir] = desc;
}
obfuscationPath.append("/");
index2path(obfuscationPath, curIndex);
obfuscationPath.append(parseExtensionName(originalPath));
if (kIsResObfDebug) {
fprintf(stderr, "[RESOBF] original: %s, obfuscation: %s \n"
, originalPath.string()
, obfuscationPath.string()
/*, parseExtensionName(originalPath).string()
, originalPath.getPathDir().string()*/);
}
return obfuscationPath;
}
// ============ Res Obfuscation end ============
static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
ResourceTable* table,
const sp<ResourceTypeSet>& set,
const char* resType)
{
String8 type8(resType);
String16 type16(resType);
bool hasErrors = false;
ResourceDirIterator it(set, String8(resType));
ssize_t res;
while ((res=it.next()) == NO_ERROR) {
if (bundle->getVerbose()) {
printf(" (new resource id %s from %s)\n",
it.getBaseName().string(), it.getFile()->getPrintableSource().string());
}
String16 baseName(it.getBaseName());
const char16_t* str = baseName.string();
const char16_t* const end = str + baseName.size();
while (str < end) {
if (!((*str >= 'a' && *str <= 'z')
|| (*str >= '0' && *str <= '9')
|| *str == '_' || *str == '.')) {
fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]\n",
it.getPath().string());
hasErrors = true;
}
str++;
}
String8 resPath = it.getPath();
resPath.convertToResPath();
///////// Res Obfuscation begin
String8 obfuscationPath = kIsResObfEnable ? getObfuscationPath(resPath) : resPath;
///////// Res Obfuscation end
table->addEntry(SourcePos(it.getPath(), 0), String16(assets->getPackage()),
type16,
baseName,
String16(obfuscationPath),// String16(resPath),
NULL,
&it.getParams());
assets->addResource(it.getLeafName(), obfuscationPath/*resPath*/, it.getFile(), type8);
}
return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
}
class PreProcessImageWorkUnit : public WorkQueue::WorkUnit {
public:
PreProcessImageWorkUnit(const Bundle* bundle, const sp<AaptAssets>& assets,
const sp<AaptFile>& file, volatile bool* hasErrors) :
mBundle(bundle), mAssets(assets), mFile(file), mHasErrors(hasErrors) {
}
virtual bool run() {
status_t status = preProcessImage(mBundle, mAssets, mFile, NULL);
if (status) {
*mHasErrors = true;
}
return true; // continue even if there are errors
}
private:
const Bundle* mBundle;
sp<AaptAssets> mAssets;
sp<AaptFile> mFile;
volatile bool* mHasErrors;
};
static status_t preProcessImages(const Bundle* bundle, const sp<AaptAssets>& assets,
const sp<ResourceTypeSet>& set, const char* type)
{
volatile bool hasErrors = false;
ssize_t res = NO_ERROR;
if (bundle->getUseCrunchCache() == false) {
WorkQueue wq(MAX_THREADS, false);
ResourceDirIterator it(set, String8(type));
while ((res=it.next()) == NO_ERROR) {
PreProcessImageWorkUnit* w = new PreProcessImageWorkUnit(
bundle, assets, it.getFile(), &hasErrors);
status_t status = wq.schedule(w);
if (status) {
fprintf(stderr, "preProcessImages failed: schedule() returned %d\n", status);
hasErrors = true;
delete w;
break;
}
}
status_t status = wq.finish();
if (status) {
fprintf(stderr, "preProcessImages failed: finish() returned %d\n", status);
hasErrors = true;
}
}
return (hasErrors || (res < NO_ERROR)) ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
}
static void collect_files(const sp<AaptDir>& dir,
KeyedVector<String8, sp<ResourceTypeSet> >* resources)
{
const DefaultKeyedVector<String8, sp<AaptGroup> >& groups = dir->getFiles();
int N = groups.size();
for (int i=0; i<N; i++) {
String8 leafName = groups.keyAt(i);
const sp<AaptGroup>& group = groups.valueAt(i);
const DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> >& files
= group->getFiles();
if (files.size() == 0) {
continue;
}
String8 resType = files.valueAt(0)->getResourceType();
ssize_t index = resources->indexOfKey(resType);
if (index < 0) {
sp<ResourceTypeSet> set = new ResourceTypeSet();
if (kIsDebug) {
printf("Creating new resource type set for leaf %s with group %s (%p)\n",
leafName.string(), group->getPath().string(), group.get());
}
set->add(leafName, group);
resources->add(resType, set);
} else {
sp<ResourceTypeSet> set = resources->valueAt(index);
index = set->indexOfKey(leafName);
if (index < 0) {
if (kIsDebug) {
printf("Adding to resource type set for leaf %s group %s (%p)\n",
leafName.string(), group->getPath().string(), group.get());
}
set->add(leafName, group);
} else {
sp<AaptGroup> existingGroup = set->valueAt(index);
if (kIsDebug) {
printf("Extending to resource type set for leaf %s group %s (%p)\n",
leafName.string(), group->getPath().string(), group.get());
}
for (size_t j=0; j<files.size(); j++) {
if (kIsDebug) {
printf("Adding file %s in group %s resType %s\n",
files.valueAt(j)->getSourceFile().string(),
files.keyAt(j).toDirName(String8()).string(),
resType.string());
}
existingGroup->addFile(files.valueAt(j));
}
}
}
}
}
static void collect_files(const sp<AaptAssets>& ass,
KeyedVector<String8, sp<ResourceTypeSet> >* resources)
{
const Vector<sp<AaptDir> >& dirs = ass->resDirs();
int N = dirs.size();
for (int i=0; i<N; i++) {
sp<AaptDir> d = dirs.itemAt(i);
if (kIsDebug) {
printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
d->getLeaf().string());
}
collect_files(d, resources);
// don't try to include the res dir
if (kIsDebug) {
printf("Removing dir leaf %s\n", d->getLeaf().string());
}
ass->removeDir(d->getLeaf());
}
}
enum {
ATTR_OKAY = -1,
ATTR_NOT_FOUND = -2,
ATTR_LEADING_SPACES = -3,
ATTR_TRAILING_SPACES = -4
};
static int validateAttr(const String8& path, const ResTable& table,
const ResXMLParser& parser,
const char* ns, const char* attr, const char* validChars, bool required)
{
size_t len;
ssize_t index = parser.indexOfAttribute(ns, attr);
const char16_t* str;
Res_value value;
if (index >= 0 && parser.getAttributeValue(index, &value) >= 0) {
const ResStringPool* pool = &parser.getStrings();
if (value.dataType == Res_value::TYPE_REFERENCE) {
uint32_t specFlags = 0;
int strIdx;
if ((strIdx=table.resolveReference(&value, 0x10000000, NULL, &specFlags)) < 0) {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s references unknown resid 0x%08x.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr,
value.data);
return ATTR_NOT_FOUND;
}
pool = table.getTableStringBlock(strIdx);
#if 0
if (pool != NULL) {
str = pool->stringAt(value.data, &len);
}
printf("***** RES ATTR: %s specFlags=0x%x strIdx=%d: %s\n", attr,
specFlags, strIdx, str != NULL ? String8(str).string() : "???");
#endif
if ((specFlags&~ResTable_typeSpec::SPEC_PUBLIC) != 0 && false) {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s varies by configurations 0x%x.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr,
specFlags);
return ATTR_NOT_FOUND;
}
}
if (value.dataType == Res_value::TYPE_STRING) {
if (pool == NULL) {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s has no string block.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr);
return ATTR_NOT_FOUND;
}
if ((str=pool->stringAt(value.data, &len)) == NULL) {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s has corrupt string value.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr);
return ATTR_NOT_FOUND;
}
} else {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid type %d.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr,
value.dataType);
return ATTR_NOT_FOUND;
}
if (validChars) {
for (size_t i=0; i<len; i++) {
char16_t c = str[i];
const char* p = validChars;
bool okay = false;
while (*p) {
if (c == *p) {
okay = true;
break;
}
p++;
}
if (!okay) {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s has invalid character '%c'.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr, (char)str[i]);
return (int)i;
}
}
}
if (*str == ' ') {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not start with a space.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr);
return ATTR_LEADING_SPACES;
}
if (len != 0 && str[len-1] == ' ') {
fprintf(stderr, "%s:%d: Tag <%s> attribute %s can not end with a space.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr);
return ATTR_TRAILING_SPACES;
}
return ATTR_OKAY;
}
if (required) {
fprintf(stderr, "%s:%d: Tag <%s> missing required attribute %s.\n",
path.string(), parser.getLineNumber(),
String8(parser.getElementName(&len)).string(), attr);
return ATTR_NOT_FOUND;
}
return ATTR_OKAY;
}
static void checkForIds(const String8& path, ResXMLParser& parser)
{
ResXMLTree::event_code_t code;
while ((code=parser.next()) != ResXMLTree::END_DOCUMENT
&& code > ResXMLTree::BAD_DOCUMENT) {
if (code == ResXMLTree::START_TAG) {
ssize_t index = parser.indexOfAttribute(NULL, "id");
if (index >= 0) {
fprintf(stderr, "%s:%d: warning: found plain 'id' attribute; did you mean the new 'android:id' name?\n",
path.string(), parser.getLineNumber());
}
}
}
}
static bool applyFileOverlay(Bundle *bundle,
const sp<AaptAssets>& assets,
sp<ResourceTypeSet> *baseSet,
const char *resType)
{
if (bundle->getVerbose()) {
printf("applyFileOverlay for %s\n", resType);
}
// Replace any base level files in this category with any found from the overlay
// Also add any found only in the overlay.
sp<AaptAssets> overlay = assets->getOverlay();
String8 resTypeString(resType);
// work through the linked list of overlays
while (overlay.get()) {
KeyedVector<String8, sp<ResourceTypeSet> >* overlayRes = overlay->getResources();
// get the overlay resources of the requested type
ssize_t index = overlayRes->indexOfKey(resTypeString);
if (index >= 0) {
sp<ResourceTypeSet> overlaySet = overlayRes->valueAt(index);
// for each of the resources, check for a match in the previously built
// non-overlay "baseset".
size_t overlayCount = overlaySet->size();
for (size_t overlayIndex=0; overlayIndex<overlayCount; overlayIndex++) {
if (bundle->getVerbose()) {
printf("trying overlaySet Key=%s\n",overlaySet->keyAt(overlayIndex).string());
}
ssize_t baseIndex = -1;
if (baseSet->get() != NULL) {
baseIndex = (*baseSet)->indexOfKey(overlaySet->keyAt(overlayIndex));
}
if (baseIndex >= 0) {
// look for same flavor. For a given file (strings.xml, for example)
// there may be a locale specific or other flavors - we want to match
// the same flavor.
sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
sp<AaptGroup> baseGroup = (*baseSet)->valueAt(baseIndex);
DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
overlayGroup->getFiles();
if (bundle->getVerbose()) {
DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > baseFiles =
baseGroup->getFiles();
for (size_t i=0; i < baseFiles.size(); i++) {
printf("baseFile " ZD " has flavor %s\n", (ZD_TYPE) i,
baseFiles.keyAt(i).toString().string());
}
for (size_t i=0; i < overlayFiles.size(); i++) {
printf("overlayFile " ZD " has flavor %s\n", (ZD_TYPE) i,
overlayFiles.keyAt(i).toString().string());
}
}
size_t overlayGroupSize = overlayFiles.size();
for (size_t overlayGroupIndex = 0;
overlayGroupIndex<overlayGroupSize;
overlayGroupIndex++) {
ssize_t baseFileIndex =
baseGroup->getFiles().indexOfKey(overlayFiles.
keyAt(overlayGroupIndex));
if (baseFileIndex >= 0) {
if (bundle->getVerbose()) {
printf("found a match (" ZD ") for overlay file %s, for flavor %s\n",
(ZD_TYPE) baseFileIndex,
overlayGroup->getLeaf().string(),
overlayFiles.keyAt(overlayGroupIndex).toString().string());
}
baseGroup->removeFile(baseFileIndex);
} else {
// didn't find a match fall through and add it..
if (true || bundle->getVerbose()) {
printf("nothing matches overlay file %s, for flavor %s\n",
overlayGroup->getLeaf().string(),
overlayFiles.keyAt(overlayGroupIndex).toString().string());
}
}
baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
}
} else {
if (baseSet->get() == NULL) {
*baseSet = new ResourceTypeSet();
assets->getResources()->add(String8(resType), *baseSet);
}
// this group doesn't exist (a file that's only in the overlay)
(*baseSet)->add(overlaySet->keyAt(overlayIndex),
overlaySet->valueAt(overlayIndex));
// make sure all flavors are defined in the resources.
sp<AaptGroup> overlayGroup = overlaySet->valueAt(overlayIndex);
DefaultKeyedVector<AaptGroupEntry, sp<AaptFile> > overlayFiles =
overlayGroup->getFiles();
size_t overlayGroupSize = overlayFiles.size();
for (size_t overlayGroupIndex = 0;
overlayGroupIndex<overlayGroupSize;
overlayGroupIndex++) {
assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
}
}
}
// this overlay didn't have resources for this type
}
// try next overlay
overlay = overlay->getOverlay();
}
return true;
}
/*
* Inserts an attribute in a given node.
* If errorOnFailedInsert is true, and the attribute already exists, returns false.
* If replaceExisting is true, the attribute will be updated if it already exists.
* Returns true otherwise, even if the attribute already exists, and does not modify
* the existing attribute's value.
*/
bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
const char* attr8, const char* value, bool errorOnFailedInsert,
bool replaceExisting)
{
if (value == NULL) {
return true;
}
const String16 ns(ns8);
const String16 attr(attr8);
XMLNode::attribute_entry* existingEntry = node->editAttribute(ns, attr);
if (existingEntry != NULL) {
if (replaceExisting) {
if (kIsDebug) {
printf("Info: AndroidManifest.xml already defines %s (in %s);"
" overwriting existing value from manifest.\n",
String8(attr).string(), String8(ns).string());
}
existingEntry->string = String16(value);
return true;
}
if (errorOnFailedInsert) {
fprintf(stderr, "Error: AndroidManifest.xml already defines %s (in %s);"
" cannot insert new value %s.\n",
String8(attr).string(), String8(ns).string(), value);
return false;
}
fprintf(stderr, "Warning: AndroidManifest.xml already defines %s (in %s);"
" using existing value in manifest.\n",
String8(attr).string(), String8(ns).string());
// don't stop the build.
return true;
}
node->addAttribute(ns, attr, String16(value));
return true;
}
/*
* Inserts an attribute in a given node, only if the attribute does not
* exist.
* If errorOnFailedInsert is true, and the attribute already exists, returns false.
* Returns true otherwise, even if the attribute already exists.
*/
bool addTagAttribute(const sp<XMLNode>& node, const char* ns8,
const char* attr8, const char* value, bool errorOnFailedInsert)
{
return addTagAttribute(node, ns8, attr8, value, errorOnFailedInsert, false);
}
static void fullyQualifyClassName(const String8& package, sp<XMLNode> node,
const String16& attrName) {
XMLNode::attribute_entry* attr = node->editAttribute(
String16("http://schemas.android.com/apk/res/android"), attrName);
if (attr != NULL) {
String8 name(attr->string);
// asdf --> package.asdf
// .asdf .a.b --> package.asdf package.a.b
// asdf.adsf --> asdf.asdf
String8 className;
const char* p = name.string();
const char* q = strchr(p, '.');
if (p == q) {
className += package;
className += name;
} else if (q == NULL) {
className += package;
className += ".";
className += name;
} else {
className += name;
}
if (kIsDebug) {
printf("Qualifying class '%s' to '%s'", name.string(), className.string());
}
attr->string.setTo(String16(className));
}
}
status_t massageManifest(Bundle* bundle, sp<XMLNode> root)
{
root = root->searchElement(String16(), String16("manifest"));
if (root == NULL) {
fprintf(stderr, "No <manifest> tag.\n");
return UNKNOWN_ERROR;
}
bool errorOnFailedInsert = bundle->getErrorOnFailedInsert();
bool replaceVersion = bundle->getReplaceVersion();
if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionCode",
bundle->getVersionCode(), errorOnFailedInsert, replaceVersion)) {
return UNKNOWN_ERROR;
} else {
const XMLNode::attribute_entry* attr = root->getAttribute(
String16(RESOURCES_ANDROID_NAMESPACE), String16("versionCode"));
if (attr != NULL) {
bundle->setVersionCode(strdup(String8(attr->string).string()));
}
}
if (!addTagAttribute(root, RESOURCES_ANDROID_NAMESPACE, "versionName",
bundle->getVersionName(), errorOnFailedInsert, replaceVersion)) {
return UNKNOWN_ERROR;
} else {
const XMLNode::attribute_entry* attr = root->getAttribute(
String16(RESOURCES_ANDROID_NAMESPACE), String16("versionName"));
if (attr != NULL) {
bundle->setVersionName(strdup(String8(attr->string).string()));
}
}
sp<XMLNode> vers = root->getChildElement(String16(), String16("uses-sdk"));
if (bundle->getMinSdkVersion() != NULL
|| bundle->getTargetSdkVersion() != NULL
|| bundle->getMaxSdkVersion() != NULL) {
if (vers == NULL) {
vers = XMLNode::newElement(root->getFilename(), String16(), String16("uses-sdk"));
root->insertChildAt(vers, 0);
}
if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "minSdkVersion",
bundle->getMinSdkVersion(), errorOnFailedInsert)) {
return UNKNOWN_ERROR;
}
if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "targetSdkVersion",
bundle->getTargetSdkVersion(), errorOnFailedInsert)) {
return UNKNOWN_ERROR;
}
if (!addTagAttribute(vers, RESOURCES_ANDROID_NAMESPACE, "maxSdkVersion",
bundle->getMaxSdkVersion(), errorOnFailedInsert)) {
return UNKNOWN_ERROR;
}
}
if (vers != NULL) {
const XMLNode::attribute_entry* attr = vers->getAttribute(
String16(RESOURCES_ANDROID_NAMESPACE), String16("minSdkVersion"));
if (attr != NULL) {
bundle->setMinSdkVersion(strdup(String8(attr->string).string()));
}
}
if (bundle->getPlatformBuildVersionCode() != "") {
if (!addTagAttribute(root, "", "platformBuildVersionCode",
bundle->getPlatformBuildVersionCode(), errorOnFailedInsert, true)) {
return UNKNOWN_ERROR;
}
}
if (bundle->getPlatformBuildVersionName() != "") {
if (!addTagAttribute(root, "", "platformBuildVersionName",
bundle->getPlatformBuildVersionName(), errorOnFailedInsert, true)) {
return UNKNOWN_ERROR;
}
}
if (bundle->getDebugMode()) {
sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
if (application != NULL) {
if (!addTagAttribute(application, RESOURCES_ANDROID_NAMESPACE, "debuggable", "true",
errorOnFailedInsert)) {
return UNKNOWN_ERROR;
}
}
}
// Deal with manifest package name overrides
const char* manifestPackageNameOverride = bundle->getManifestPackageNameOverride();
if (manifestPackageNameOverride != NULL) {
// Update the actual package name
XMLNode::attribute_entry* attr = root->editAttribute(String16(), String16("package"));
if (attr == NULL) {
fprintf(stderr, "package name is required with --rename-manifest-package.\n");
return UNKNOWN_ERROR;
}
String8 origPackage(attr->string);
attr->string.setTo(String16(manifestPackageNameOverride));
if (kIsDebug) {
printf("Overriding package '%s' to be '%s'\n", origPackage.string(),
manifestPackageNameOverride);
}
// Make class names fully qualified
sp<XMLNode> application = root->getChildElement(String16(), String16("application"));
if (application != NULL) {
fullyQualifyClassName(origPackage, application, String16("name"));
fullyQualifyClassName(origPackage, application, String16("backupAgent"));
Vector<sp<XMLNode> >& children = const_cast<Vector<sp<XMLNode> >&>(application->getChildren());
for (size_t i = 0; i < children.size(); i++) {
sp<XMLNode> child = children.editItemAt(i);
String8 tag(child->getElementName());
if (tag == "activity" || tag == "service" || tag == "receiver" || tag == "provider") {
fullyQualifyClassName(origPackage, child, String16("name"));
} else if (tag == "activity-alias") {
fullyQualifyClassName(origPackage, child, String16("name"));
fullyQualifyClassName(origPackage, child, String16("targetActivity"));
}
}