forked from facebook/redex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApkResources.cpp
2781 lines (2532 loc) · 102 KB
/
ApkResources.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 (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ApkResources.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/optional.hpp>
#include <boost/regex.hpp>
#include <cstdint>
#include <fcntl.h>
#include <fstream>
#include <istream>
#include <map>
#include <string>
#include <string_view>
#include "Macros.h"
#if IS_WINDOWS
#include "CompatWindows.h"
#include <io.h>
#include <share.h>
#endif
#include "androidfw/ResourceTypes.h"
#include "androidfw/TypeWrappers.h"
#include "utils/ByteOrder.h"
#include "utils/Errors.h"
#include "utils/Log.h"
#include "utils/Serialize.h"
#include "utils/String16.h"
#include "utils/String8.h"
#include "utils/TypeHelpers.h"
#include "utils/Unicode.h"
#include "utils/Visitor.h"
#include "Debug.h"
#include "DexUtil.h"
#include "GlobalConfig.h"
#include "IOUtil.h"
#include "ReadMaybeMapped.h"
#include "RedexMappedFile.h"
#include "RedexResources.h"
#include "Trace.h"
#include "WorkQueue.h"
// Workaround for inclusion order, when compiling on Windows (#defines NO_ERROR
// as 0).
#ifdef NO_ERROR
#undef NO_ERROR
#endif
namespace apk {
bool TableParser::visit_global_strings(android::ResStringPool_header* pool) {
m_global_pool_header = pool;
arsc::StringPoolRefVisitor::visit_global_strings(pool);
return true;
}
bool TableParser::visit_package(android::ResTable_package* package) {
m_packages.emplace(package);
std::vector<android::ResChunk_header*> headers;
m_package_unknown_chunks.emplace(package, std::move(headers));
arsc::StringPoolRefVisitor::visit_package(package);
return true;
}
bool TableParser::visit_key_strings(android::ResTable_package* package,
android::ResStringPool_header* pool) {
m_package_key_string_headers.emplace(package, pool);
arsc::StringPoolRefVisitor::visit_key_strings(package, pool);
return true;
}
bool TableParser::visit_type_strings(android::ResTable_package* package,
android::ResStringPool_header* pool) {
m_package_type_string_headers.emplace(package, pool);
arsc::StringPoolRefVisitor::visit_type_strings(package, pool);
return true;
}
bool TableParser::visit_type_spec(android::ResTable_package* package,
android::ResTable_typeSpec* type_spec) {
arsc::TypeInfo info{type_spec, {}};
auto search = m_package_types.find(package);
if (search == m_package_types.end()) {
std::vector<arsc::TypeInfo> infos;
infos.emplace_back(info);
m_package_types.emplace(package, infos);
} else {
search->second.emplace_back(info);
}
arsc::StringPoolRefVisitor::visit_type_spec(package, type_spec);
return true;
}
bool TableParser::visit_type(android::ResTable_package* package,
android::ResTable_typeSpec* type_spec,
android::ResTable_type* type) {
auto& infos = m_package_types.at(package);
for (auto& info : infos) {
if (info.spec->id == type_spec->id) {
info.configs.emplace_back(type);
}
}
arsc::StringPoolRefVisitor::visit_type(package, type_spec, type);
return true;
}
bool TableParser::visit_unknown_chunk(android::ResTable_package* package,
android::ResChunk_header* header) {
auto& chunks = m_package_unknown_chunks.at(package);
chunks.emplace_back(header);
return true;
}
bool TableEntryParser::visit_type_spec(android::ResTable_package* package,
android::ResTable_typeSpec* type_spec) {
TableParser::visit_type_spec(package, type_spec);
auto package_type_id = make_package_type_id(package, type_spec->id);
m_types.emplace(package_type_id, type_spec);
TypeToEntries map;
m_types_to_entries.emplace(package, std::move(map));
std::vector<android::ResTable_type*> vec;
m_types_to_configs.emplace(package_type_id, std::move(vec));
return true;
}
void TableEntryParser::put_entry_data(uint32_t res_id,
android::ResTable_package* package,
android::ResTable_type* type,
arsc::EntryValueData& data) {
{
auto search = m_res_id_to_entries.find(res_id);
if (search == m_res_id_to_entries.end()) {
ConfigToEntry c;
m_res_id_to_entries.emplace(res_id, std::move(c));
}
auto& c = m_res_id_to_entries.at(res_id);
c.emplace(&type->config, data);
}
{
auto& map = m_types_to_entries.at(package);
auto search = map.find(type);
if (search == map.end()) {
std::vector<arsc::EntryValueData> vec;
map.emplace(type, std::move(vec));
}
auto& vec = map.at(type);
vec.emplace_back(data);
}
}
bool TableEntryParser::visit_type(android::ResTable_package* package,
android::ResTable_typeSpec* type_spec,
android::ResTable_type* type) {
TableParser::visit_type(package, type_spec, type);
auto package_type_id = make_package_type_id(package, type_spec->id);
auto& types = m_types_to_configs.at(package_type_id);
types.emplace_back(type);
android::TypeVariant tv(type);
uint16_t entry_id = 0;
for (auto it = tv.beginEntries(); it != tv.endEntries(); ++it, ++entry_id) {
android::ResTable_entry* entry = const_cast<android::ResTable_entry*>(*it);
uint32_t res_id = package_type_id << 16 | entry_id;
if (entry == nullptr) {
arsc::EntryValueData data(nullptr, 0);
put_entry_data(res_id, package, type, data);
} else {
auto size = arsc::compute_entry_value_length(entry);
arsc::EntryValueData data((uint8_t*)entry, size);
put_entry_data(res_id, package, type, data);
}
m_res_id_to_flags.emplace(res_id,
arsc::get_spec_flags(type_spec, entry_id));
}
return true;
}
bool XmlFileEditor::visit_global_strings(android::ResStringPool_header* pool) {
m_string_pool_header = pool;
return true;
}
bool XmlFileEditor::visit_attribute_ids(android::ResChunk_header* header,
uint32_t* id,
size_t count) {
arsc::XmlFileVisitor::visit_attribute_ids(header, id, count);
m_attribute_ids_start = id;
m_attribute_id_count = count;
return true;
}
bool XmlFileEditor::visit_typed_data(android::Res_value* value) {
m_typed_data.emplace_back(value);
return true;
}
size_t XmlFileEditor::remap(const std::map<uint32_t, uint32_t>& old_to_new) {
size_t changes = 0;
if (m_attribute_id_count > 0 && m_attribute_ids_start != nullptr) {
uint32_t* id = m_attribute_ids_start;
for (size_t i = 0; i < m_attribute_id_count; i++, id++) {
uint32_t old_value = dtohl(*id);
auto search = old_to_new.find(old_value);
if (search != old_to_new.end()) {
auto new_value = htodl(search->second);
if (old_value != new_value) {
TRACE(RES, 9, "Remapping attribute ID 0x%x -> 0x%x at offset %ld",
old_value, new_value, get_file_offset(id));
*id = new_value;
changes++;
}
}
}
}
for (auto& value : m_typed_data) {
if (value->dataType == android::Res_value::TYPE_REFERENCE ||
value->dataType == android::Res_value::TYPE_ATTRIBUTE) {
auto old_value = dtohl(value->data);
auto search = old_to_new.find(old_value);
if (search != old_to_new.end()) {
auto new_value = htodl(search->second);
if (old_value != new_value) {
TRACE(RES, 9, "Remapping attribute value 0x%x -> 0x%x at offset %ld",
old_value, new_value, get_file_offset(value));
value->data = new_value;
changes++;
}
}
}
}
return changes;
}
#define GET_ID(ptr) (dtohl((ptr)->id))
#define CHUNK_SIZE(chunk) (dtohl((chunk)->header.size))
TableSnapshot::TableSnapshot(RedexMappedFile& mapped_file, size_t len) {
auto data = mapped_file.read_only ? (void*)mapped_file.const_data()
: mapped_file.data();
always_assert_log(m_table_parser.visit(data, len),
"Failed to parse .arsc file");
always_assert_log(
m_global_strings.setTo(m_table_parser.m_global_pool_header,
CHUNK_SIZE(m_table_parser.m_global_pool_header),
true) == android::NO_ERROR,
"Failed to parse global strings!");
for (const auto& pair : m_table_parser.m_package_key_string_headers) {
auto package_id = GET_ID(pair.first);
always_assert_log(
m_key_strings[package_id].setTo(pair.second, CHUNK_SIZE(pair.second),
true) == android::NO_ERROR,
"Failed to parse key strings for package 0x%x", package_id);
}
for (const auto& pair : m_table_parser.m_package_type_string_headers) {
auto package_id = GET_ID(pair.first);
always_assert_log(
m_type_strings[package_id].setTo(pair.second, CHUNK_SIZE(pair.second),
true) == android::NO_ERROR,
"Failed to parse type strings for package 0x%x", package_id);
}
}
void TableSnapshot::gather_non_empty_resource_ids(std::vector<uint32_t>* ids) {
for (const auto& pair : m_table_parser.m_res_id_to_entries) {
auto id = pair.first;
for (const auto& config_entry : pair.second) {
if (!arsc::is_empty(config_entry.second)) {
ids->emplace_back(id);
break;
}
}
}
}
std::string TableSnapshot::get_resource_name(uint32_t id) {
uint32_t package_id = (id >> PACKAGE_INDEX_BIT_SHIFT) & 0xFF;
auto search = m_table_parser.m_res_id_to_entries.find(id);
if (search == m_table_parser.m_res_id_to_entries.end()) {
return "";
}
auto& entries = search->second;
ssize_t result = -1;
for (const auto& pair : entries) {
auto entry_data = pair.second.getKey();
if (entry_data != nullptr) {
auto entry = (android::ResTable_entry*)entry_data;
auto index = dtohl(entry->key.index);
always_assert_log(result < 0 || result == index,
"Malformed entry data for ID 0x%x", id);
result = index;
}
}
if (result < 0) {
return "";
}
auto& pool = m_key_strings.at(package_id);
return arsc::get_string_from_pool(pool, result);
}
size_t TableSnapshot::package_count() {
return m_table_parser.m_packages.size();
}
void TableSnapshot::get_type_names(uint32_t package_id,
std::vector<std::string>* out) {
auto search = m_type_strings.find(package_id);
if (search == m_type_strings.end()) {
return;
}
auto& pool = search->second;
for (size_t i = 0; i < pool.size(); i++) {
out->emplace_back(arsc::get_string_from_pool(pool, i));
}
}
void TableSnapshot::get_configurations(
uint32_t package_id,
const std::string& type_name,
std::vector<android::ResTable_config>* out) {
uint8_t type_id = 0;
auto search = m_type_strings.find(package_id);
if (search == m_type_strings.end()) {
return;
}
auto& pool = search->second;
for (size_t i = 0; i < pool.size(); i++) {
if (type_name == arsc::get_string_from_pool(pool, i)) {
type_id = i + 1;
break;
}
}
if (type_id > 0) {
auto configs = m_table_parser.get_configs(package_id, type_id);
for (const auto& c : configs) {
always_assert_log(sizeof(android::ResTable_config) >= dtohl(c->size),
"Config at %p has unexpected size %d", c,
dtohl(c->size));
android::ResTable_config swapped;
swapped.copyFromDtoH(*c);
out->emplace_back(swapped);
}
}
}
std::set<android::ResTable_config> TableSnapshot::get_configs_with_values(
uint32_t id) {
std::set<android::ResTable_config> configs;
auto& config_entries = m_table_parser.m_res_id_to_entries.at(id);
for (auto& pair : config_entries) {
if (!arsc::is_empty(pair.second)) {
android::ResTable_config swapped;
swapped.copyFromDtoH(*(pair.first));
configs.emplace(swapped);
}
}
return configs;
}
bool TableSnapshot::are_values_identical(uint32_t a, uint32_t b) {
uint32_t upper = PACKAGE_MASK_BIT | TYPE_MASK_BIT;
if ((a & upper) != (b & upper)) {
return false;
}
if (m_table_parser.m_res_id_to_flags.at(a) !=
m_table_parser.m_res_id_to_flags.at(b)) {
return false;
}
auto a_entries = m_table_parser.m_res_id_to_entries.at(a);
auto b_entries = m_table_parser.m_res_id_to_entries.at(b);
always_assert_log(a_entries.size() == b_entries.size(),
"Parsed table representation does not have the same set of "
"configs for ids 0x%x, 0x%x",
a, b);
for (auto& pair : a_entries) {
auto& a_entry = pair.second;
auto& b_entry = b_entries.at(pair.first);
auto empty_entry = arsc::is_empty(a_entry);
if (empty_entry != arsc::is_empty(b_entry)) {
return false;
}
// Total length of entry + value data
if (a_entry.getValue() != b_entry.getValue()) {
return false;
}
if (!empty_entry) {
auto a_data = arsc::get_value_data(a_entry);
auto b_data = arsc::get_value_data(b_entry);
auto empty_data = arsc::is_empty(a_data);
auto data_len = a_data.getValue();
if (data_len != b_data.getValue()) {
return false;
}
if (empty_data != arsc::is_empty(b_data)) {
return false;
}
if (!empty_data &&
memcmp(a_data.getKey(), b_data.getKey(), data_len) != 0) {
return false;
}
}
}
return true;
}
namespace {
// Parse the entry data (which could be in many forms) and emit a flattened list
// of Res_value objects for callers to easily consume (by legacy convention,
// this will do byte swapping).
class EntryFlattener : public arsc::ResourceTableVisitor {
public:
void emit(android::Res_value* source) {
android::Res_value value;
value.size = dtohs(source->size);
value.res0 = source->res0;
value.dataType = source->dataType;
value.data = dtohl(source->data);
m_values.emplace_back(value);
}
void emit_shim(uint8_t data_type, uint32_t data) {
android::Res_value shim;
shim.dataType = data_type;
shim.data = data;
m_values.emplace_back(shim);
}
bool visit_entry(android::ResTable_package* /* unused */,
android::ResTable_typeSpec* /* unused */,
android::ResTable_type* /* unused */,
android::ResTable_entry* /* unused */,
android::Res_value* value) override {
emit(value);
return true;
}
bool visit_map_entry(android::ResTable_package* /* unused */,
android::ResTable_typeSpec* /* unused */,
android::ResTable_type* /* unused */,
android::ResTable_map_entry* entry) override {
// API QUIRK: Old code that served this purpose left size intentionally as 0
// to denote this is a "conceptual" value that is encompassed by the
// resource ID we are being asked to traverse. This is useful for
// reachability purposes but a bit misleading otherwise.
emit_shim(android::Res_value::TYPE_REFERENCE, dtohl(entry->parent.ident));
return true;
}
bool visit_map_value(android::ResTable_package* /* unused */,
android::ResTable_typeSpec* /* unused */,
android::ResTable_type* /* unused */,
android::ResTable_map_entry* /* unused */,
android::ResTable_map* value) override {
emit(&value->value);
// API QUIRK: Same rationale as above.
emit_shim(android::Res_value::TYPE_ATTRIBUTE, dtohl(value->name.ident));
return true;
}
std::vector<android::Res_value> m_values;
};
} // namespace
void TableSnapshot::collect_resource_values(
uint32_t id, std::vector<android::Res_value>* out) {
collect_resource_values(id, {}, out);
}
void TableSnapshot::collect_resource_values(
uint32_t id,
std::vector<android::ResTable_config> include_configs,
std::vector<android::Res_value>* out) {
auto should_include_config = [&](android::ResTable_config* maybe) {
if (include_configs.empty()) {
return true;
}
for (auto& c : include_configs) {
if (arsc::are_configs_equivalent(maybe, &c)) {
return true;
}
}
return false;
};
auto& config_entries = m_table_parser.m_res_id_to_entries.at(id);
for (auto& pair : config_entries) {
if (should_include_config(pair.first)) {
auto ev = pair.second;
auto entry = (android::ResTable_entry*)ev.getKey();
EntryFlattener flattener;
flattener.begin_visit_entry(nullptr, nullptr, nullptr, entry);
for (auto& v : flattener.m_values) {
out->push_back(v);
}
}
}
}
bool TableSnapshot::is_valid_global_string_idx(size_t idx) const {
return arsc::is_valid_string_idx(m_global_strings, idx);
}
// Note: this method should be used for printing values, or for giving a unified
// API with BundleResources, which will use standard UTF-8 encoding. Do not
// forward the return values on to a new string pool.
std::string TableSnapshot::get_global_string_utf8s(size_t idx) const {
return arsc::get_string_from_pool(m_global_strings, idx);
}
} // namespace apk
namespace {
#define MAKE_RES_ID(package, type, entry) \
((PACKAGE_MASK_BIT & ((package) << PACKAGE_INDEX_BIT_SHIFT)) | \
(TYPE_MASK_BIT & ((type) << TYPE_INDEX_BIT_SHIFT)) | \
(ENTRY_MASK_BIT & (entry)))
/**
* write_serialized_data don't support growing arsc file, so use
* ofstream to write to arsc file for input bigger than original
* file size.
*/
size_t write_serialized_data_with_expansion(const android::Vector<char>& vector,
RedexMappedFile f) {
size_t vec_size = vector.size();
auto filename = f.filename.c_str();
// Close current opened file.
f.file.reset();
// Write to arsc through ofstream
arsc::write_bytes_to_file(vector, filename);
return vec_size;
}
size_t write_serialized_data(const android::Vector<char>& vector,
RedexMappedFile f) {
size_t vec_size = vector.size();
size_t f_size = f.size();
always_assert_log(vec_size <= f_size, "Growing file not supported");
if (vec_size > 0) {
memcpy(f.data(), vector.array(), vec_size);
}
f.file.reset(); // Close the map.
#if IS_WINDOWS
int fd;
auto open_res =
_sopen_s(&fd, f.filename.c_str(), _O_BINARY | _O_RDWR, _SH_DENYRW, 0);
redex_assert(open_res == 0);
auto trunc_res = _chsize_s(fd, vec_size);
_close(fd);
#else
auto trunc_res = truncate(f.filename.c_str(), vec_size);
#endif
redex_assert(trunc_res == 0);
return vec_size > 0 ? vec_size : f_size;
}
/*
* skip a tag including its nested tags
*/
void skip_nested_tags(android::ResXMLTree* parser) {
size_t depth{1};
while (depth) {
auto type = parser->next();
switch (type) {
case android::ResXMLParser::START_TAG: {
++depth;
break;
}
case android::ResXMLParser::END_TAG: {
--depth;
break;
}
case android::ResXMLParser::BAD_DOCUMENT: {
not_reached();
}
default: {
break;
}
}
}
}
/*
* Look for <search_tag> within the descendants of the current node in the XML
* tree.
*/
bool find_nested_tag(const android::String16& search_tag,
android::ResXMLTree* parser) {
size_t depth{1};
while (depth) {
auto type = parser->next();
switch (type) {
case android::ResXMLParser::START_TAG: {
++depth;
size_t len;
android::String16 tag(parser->getElementName(&len));
if (tag == search_tag) {
return true;
}
break;
}
case android::ResXMLParser::END_TAG: {
--depth;
break;
}
case android::ResXMLParser::BAD_DOCUMENT: {
not_reached();
}
default: {
break;
}
}
}
return false;
}
/*
* Parse AndroidManifest from buffer, return a list of class names that are
* referenced
*/
ManifestClassInfo extract_classes_from_manifest(const char* data, size_t size) {
// Tags
android::String16 activity("activity");
android::String16 activity_alias("activity-alias");
android::String16 application("application");
android::String16 provider("provider");
android::String16 receiver("receiver");
android::String16 service("service");
android::String16 instrumentation("instrumentation");
android::String16 queries("queries");
android::String16 intent_filter("intent-filter");
// This is not an unordered_map because String16 doesn't define a hash
std::map<android::String16, ComponentTag> string_to_tag{
{activity, ComponentTag::Activity},
{activity_alias, ComponentTag::ActivityAlias},
{provider, ComponentTag::Provider},
{receiver, ComponentTag::Receiver},
{service, ComponentTag::Service},
};
// Attributes
android::String16 authorities("authorities");
android::String16 exported("exported");
android::String16 protection_level("protectionLevel");
android::String16 permission("permission");
android::String16 name("name");
android::String16 target_activity("targetActivity");
android::String16 app_component_factory("appComponentFactory");
android::ResXMLTree parser;
parser.setTo(data, size);
ManifestClassInfo manifest_classes;
if (parser.getError() != android::NO_ERROR) {
return manifest_classes;
}
android::ResXMLParser::event_code_t type;
do {
type = parser.next();
if (type == android::ResXMLParser::START_TAG) {
size_t len;
android::String16 tag(parser.getElementName(&len));
if (tag == application) {
std::string classname = get_string_attribute_value(parser, name);
// android:name is an optional attribute for <application>
if (!classname.empty()) {
manifest_classes.application_classes.emplace(
java_names::external_to_internal(classname));
}
std::string app_factory_cls =
get_string_attribute_value(parser, app_component_factory);
if (!app_factory_cls.empty()) {
manifest_classes.application_classes.emplace(
java_names::external_to_internal(app_factory_cls));
}
} else if (tag == instrumentation) {
std::string classname = get_string_attribute_value(parser, name);
always_assert(!classname.empty());
manifest_classes.instrumentation_classes.emplace(
java_names::external_to_internal(classname));
} else if (tag == queries) {
// queries break the logic to find providers below because they don't
// declare a name
skip_nested_tags(&parser);
} else if (string_to_tag.count(tag)) {
std::string classname = get_string_attribute_value(
parser, tag != activity_alias ? name : target_activity);
always_assert(!classname.empty());
bool has_exported_attribute = has_bool_attribute(parser, exported);
android::Res_value ignore_output;
bool has_permission_attribute =
has_raw_attribute_value(parser, permission, ignore_output);
bool has_protection_level_attribute =
has_raw_attribute_value(parser, protection_level, ignore_output);
bool is_exported = get_bool_attribute_value(parser, exported,
/* default_value */ false);
BooleanXMLAttribute export_attribute;
if (has_exported_attribute) {
if (is_exported) {
export_attribute = BooleanXMLAttribute::True;
} else {
export_attribute = BooleanXMLAttribute::False;
}
} else {
export_attribute = BooleanXMLAttribute::Undefined;
}
std::string permission_attribute;
std::string protection_level_attribute;
if (has_permission_attribute) {
permission_attribute = get_string_attribute_value(parser, permission);
}
if (has_protection_level_attribute) {
protection_level_attribute =
get_string_attribute_value(parser, protection_level);
}
ComponentTagInfo tag_info(string_to_tag.at(tag),
java_names::external_to_internal(classname),
export_attribute,
permission_attribute,
protection_level_attribute);
if (tag == provider) {
std::string text = get_string_attribute_value(parser, authorities);
parse_authorities(text, &tag_info.authority_classes);
} else {
tag_info.has_intent_filters = find_nested_tag(intent_filter, &parser);
}
manifest_classes.component_tags.emplace_back(tag_info);
}
}
} while (type != android::ResXMLParser::BAD_DOCUMENT &&
type != android::ResXMLParser::END_DOCUMENT);
return manifest_classes;
}
} // namespace
std::string convert_from_string16(const android::String16& string16) {
android::String8 string8(string16);
std::string converted(string8.string());
return converted;
}
// Returns the attribute with the given name for the current XML element
std::string get_string_attribute_value(
const android::ResXMLTree& parser,
const android::String16& attribute_name) {
const size_t attr_count = parser.getAttributeCount();
for (size_t i = 0; i < attr_count; ++i) {
size_t len;
android::String16 key(parser.getAttributeName(i, &len));
if (key == attribute_name) {
const char16_t* p = parser.getAttributeStringValue(i, &len);
if (p != nullptr) {
android::String16 target(p, len);
std::string converted = convert_from_string16(target);
return converted;
}
}
}
return std::string("");
}
boost::optional<resources::StringOrReference>
get_attribute_string_or_reference_value(const android::ResXMLTree& parser,
size_t idx) {
auto data_type = parser.getAttributeDataType(idx);
if (data_type == android::Res_value::TYPE_REFERENCE) {
return resources::StringOrReference(parser.getAttributeData(idx));
} else if (data_type == android::Res_value::TYPE_STRING) {
size_t len;
const char16_t* p = parser.getAttributeStringValue(idx, &len);
if (p != nullptr) {
android::String16 target(p, len);
std::string converted = convert_from_string16(target);
return resources::StringOrReference(converted);
}
}
return boost::none;
}
bool has_raw_attribute_value(const android::ResXMLTree& parser,
const android::String16& attribute_name,
android::Res_value& out_value) {
const size_t attr_count = parser.getAttributeCount();
for (size_t i = 0; i < attr_count; ++i) {
size_t len;
android::String16 key(parser.getAttributeName(i, &len));
if (key == attribute_name) {
parser.getAttributeValue(i, &out_value);
return true;
}
}
return false;
}
bool has_bool_attribute(const android::ResXMLTree& parser,
const android::String16& attribute_name) {
android::Res_value raw_value;
if (has_raw_attribute_value(parser, attribute_name, raw_value)) {
return raw_value.dataType == android::Res_value::TYPE_INT_BOOLEAN;
}
return false;
}
bool get_bool_attribute_value(const android::ResXMLTree& parser,
const android::String16& attribute_name,
bool default_value) {
android::Res_value raw_value;
if (has_raw_attribute_value(parser, attribute_name, raw_value)) {
if (raw_value.dataType == android::Res_value::TYPE_INT_BOOLEAN) {
return static_cast<bool>(raw_value.data);
}
}
return default_value;
}
int get_int_attribute_or_default_value(const android::ResXMLTree& parser,
const android::String16& attribute_name,
int32_t default_value) {
android::Res_value raw_value;
if (has_raw_attribute_value(parser, attribute_name, raw_value)) {
if (raw_value.dataType == android::Res_value::TYPE_INT_DEC) {
return static_cast<int>(raw_value.data);
}
}
return default_value;
}
std::vector<std::string> ApkResources::find_res_directories() {
return {m_directory + "/res"};
}
std::vector<std::string> ApkResources::find_lib_directories() {
return {m_directory + "/lib", m_directory + "/assets"};
}
std::string ApkResources::get_base_assets_dir() {
return m_directory + "/assets";
}
namespace {
std::string read_attribute_name_at_idx(const android::ResXMLTree& parser,
size_t idx) {
size_t len;
auto name_chars = parser.getAttributeName8(idx, &len);
if (name_chars != nullptr) {
return std::string(name_chars);
} else {
auto wide_chars = parser.getAttributeName(idx, &len);
android::String16 s16(wide_chars, len);
auto converted = convert_from_string16(s16);
return converted;
}
}
void extract_classes_from_layout(
const char* data,
size_t size,
const std::unordered_set<std::string>& attributes_to_read,
resources::StringOrReferenceSet* out_classes,
std::unordered_multimap<std::string, resources::StringOrReference>*
out_attributes) {
if (!arsc::is_binary_xml(data, size)) {
return;
}
android::ResXMLTree parser;
parser.setTo(data, size);
if (parser.getError() != android::NO_ERROR) {
return;
}
std::unordered_map<int, std::string> namespace_prefix_map;
android::ResXMLParser::event_code_t type;
do {
type = parser.next();
if (type == android::ResXMLParser::START_TAG) {
size_t len;
android::String16 tag(parser.getElementName(&len));
std::string element_name = convert_from_string16(tag);
const size_t attr_count = parser.getAttributeCount();
for (size_t i = 0; i < attr_count; ++i) {
auto data_type = parser.getAttributeDataType(i);
if (data_type == android::Res_value::TYPE_STRING ||
data_type == android::Res_value::TYPE_REFERENCE) {
std::string attr_name = read_attribute_name_at_idx(parser, i);
if (resources::POSSIBLE_CLASS_ATTRIBUTES.count(attr_name) > 0) {
auto value = get_attribute_string_or_reference_value(parser, i);
if (value && value->possible_java_identifier()) {
out_classes->emplace(*value);
}
}
}
}
// NOTE: xml elements that refer to application classes must have a
// package name; elements without a package are assumed to be SDK classes
// and will have various "android." packages prepended before
// instantiation.
if (resources::valid_xml_element(element_name)) {
TRACE(RES, 9, "Considering %s as possible class in XML resource",
element_name.c_str());
out_classes->emplace(element_name);
}
if (!attributes_to_read.empty()) {
for (size_t i = 0; i < parser.getAttributeCount(); i++) {
auto ns_id = parser.getAttributeNamespaceID(i);
std::string attr_name = read_attribute_name_at_idx(parser, i);
std::string fully_qualified;
if (ns_id >= 0) {
fully_qualified = namespace_prefix_map[ns_id] + ":" + attr_name;
} else {
fully_qualified = attr_name;
}
if (attributes_to_read.count(fully_qualified) != 0) {
auto value = get_attribute_string_or_reference_value(parser, i);
if (value) {
out_attributes->emplace(fully_qualified, *value);
}
}
}
}
} else if (type == android::ResXMLParser::START_NAMESPACE) {
auto id = parser.getNamespaceUriID();
size_t len;
auto prefix = parser.getNamespacePrefix(&len);
namespace_prefix_map.emplace(
id, convert_from_string16(android::String16(prefix, len)));
}
} while (type != android::ResXMLParser::BAD_DOCUMENT &&
type != android::ResXMLParser::END_DOCUMENT);
}
} // namespace
void ApkResources::collect_layout_classes_and_attributes_for_file(
const std::string& file_path,
const std::unordered_set<std::string>& attributes_to_read,
resources::StringOrReferenceSet* out_classes,
std::unordered_multimap<std::string, resources::StringOrReference>*
out_attributes) {
redex::read_file_with_contents(file_path, [&](const char* data, size_t size) {
extract_classes_from_layout(data, size, attributes_to_read, out_classes,
out_attributes);
});
}
namespace {
class XmlStringAttributeCollector : public arsc::SimpleXmlParser {
public:
~XmlStringAttributeCollector() override {}
bool visit_typed_data(android::Res_value* value) override {
if (value->dataType == android::Res_value::TYPE_STRING) {
auto idx = dtohl(value->data);
auto& pool = global_strings();
if (arsc::is_valid_string_idx(pool, idx)) {
auto s = arsc::get_string_from_pool(pool, idx);
m_utf8s_values.emplace(s);
}
}
return true;
}
std::unordered_set<std::string> m_utf8s_values;
};
class XmlElementCollector : public arsc::SimpleXmlParser {
public:
~XmlElementCollector() override {}
boost::optional<std::string> get_element_name(
android::ResXMLTree_attrExt* extension) {
auto ns = dtohl(extension->ns.index);
auto name_idx = dtohl(extension->name.index);
auto& string_pool = global_strings();
if (arsc::is_valid_string_idx(string_pool, name_idx)) {
auto element_name = arsc::get_string_from_pool(string_pool, name_idx);