forked from facebook/redex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DexOutput.cpp
3191 lines (2928 loc) · 115 KB
/
DexOutput.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 "DexOutput.h"
#include <algorithm>
#include <assert.h>
#include <bitset>
#include <boost/filesystem.hpp>
#include <exception>
#include <fcntl.h>
#include <fstream>
#include <functional>
#include <inttypes.h>
#include <list>
#include <memory>
#include <stdlib.h>
#include <sys/stat.h>
#include <unordered_set>
#ifdef _MSC_VER
// TODO: Rewrite open/write/close with C/C++ standards. But it works for now.
#include <io.h>
#define open _open
#define write _write
#define close _close
#define fstat _fstat64i32
#define stat _stat64i32
#define O_CREAT _O_CREAT
#define O_TRUNC _O_TRUNC
#define O_WRONLY _O_WRONLY
#endif
#include "Debug.h"
#include "DexCallSite.h"
#include "DexClass.h"
#include "DexInstruction.h"
#include "DexLimits.h"
#include "DexMethodHandle.h"
#include "DexPosition.h"
#include "DexUtil.h"
#include "GlobalConfig.h"
#include "IODIMetadata.h"
#include "IRCode.h"
#include "Macros.h"
#include "MethodProfiles.h"
#include "MethodSimilarityCompressionConsciousOrderer.h"
#include "MethodSimilarityGreedyOrderer.h"
#include "Pass.h"
#include "RedexOptions.h" // For DebugInfoKind
#include "Resolver.h"
#include "Sha1.h"
#include "Show.h"
#include "StlUtil.h"
#include "Trace.h"
#include "Walkers.h"
#include "WorkQueue.h"
/*
* For adler32...
*/
#include <zlib.h>
template <class T, class U>
class CustomSort {
private:
const std::unordered_map<const T*, unsigned int>& m_map;
U m_cmp;
public:
CustomSort(const std::unordered_map<const T*, unsigned int>& input_map, U cmp)
: m_map(input_map) {
m_cmp = cmp;
}
bool operator()(const T* a, const T* b) const {
const auto end_it = m_map.end();
const auto a_it = m_map.find(a);
const auto b_it = m_map.find(b);
if (a_it == end_it && b_it == end_it) {
return m_cmp(a, b);
}
if (a_it != end_it && b_it != end_it) {
const auto a_idx = a_it->second;
const auto b_idx = b_it->second;
if (a_idx != b_idx) {
return a_idx < b_idx;
}
return m_cmp(a, b);
}
if (a_it != end_it) {
return true;
}
return false;
}
};
GatheredTypes::GatheredTypes(DexClasses* classes) : m_classes(classes) {
// ensure that the string id table contains the empty string, which is used
// for the DexPosition mapping
m_lstring.push_back(DexString::make_string(""));
// build maps for the different custom sorting options
build_cls_load_map();
build_cls_map();
build_method_map();
gather_components(m_lstring, m_ltype, m_lfield, m_lmethod, m_lcallsite,
m_lmethodhandle, *m_classes);
}
std::unordered_set<const DexString*> GatheredTypes::index_type_names() {
std::unordered_set<const DexString*> type_names;
for (auto it = m_ltype.begin(); it != m_ltype.end(); ++it) {
type_names.insert((*it)->get_name());
}
return type_names;
}
std::vector<const DexString*>
GatheredTypes::get_cls_order_dexstring_emitlist() {
return get_dexstring_emitlist(CustomSort<DexString, cmp_dstring>(
m_cls_load_strings, compare_dexstrings));
}
std::vector<const DexString*>
GatheredTypes::keep_cls_strings_together_emitlist() {
return get_dexstring_emitlist(
CustomSort<DexString, cmp_dstring>(m_cls_strings, compare_dexstrings));
}
std::vector<DexMethodHandle*> GatheredTypes::get_dexmethodhandle_emitlist() {
return m_lmethodhandle;
}
std::vector<DexCallSite*> GatheredTypes::get_dexcallsite_emitlist() {
return m_lcallsite;
}
std::vector<DexMethod*> GatheredTypes::get_dexmethod_emitlist() {
std::vector<DexMethod*> methlist;
for (auto cls : *m_classes) {
TRACE(OPUT, 3, "[dexmethod_emitlist][class] %s", cls->c_str());
auto const& dmethods = cls->get_dmethods();
auto const& vmethods = cls->get_vmethods();
if (traceEnabled(OPUT, 3)) {
for (const auto& dmeth : dmethods) {
TRACE(OPUT, 3, " [dexmethod_emitlist][dmethod] %s", dmeth->c_str());
}
for (const auto& vmeth : vmethods) {
TRACE(OPUT, 3, " [dexmethod_emitlist][dmethod] %s", vmeth->c_str());
}
}
methlist.insert(methlist.end(), dmethods.begin(), dmethods.end());
methlist.insert(methlist.end(), vmethods.begin(), vmethods.end());
}
return methlist;
}
void GatheredTypes::sort_dexmethod_emitlist_method_similarity_order(
std::vector<DexMethod*>& lmeth) {
// We keep "perf sensitive methods" together in front, and only order by
// similarity the remaining methods. Here, we consider as "perf sensitive
// methods" any methods in a class that...
// - is perf sensitive, which in particular includes all classes that are
// ordered by beta maps
// - contains methods that contain any profiled methods with a very
// conservative min-appear cut-off.
//
// This is similar to the exclusions that the InterDex pass applies when
// sorting remaining classes for better compression.
redex_assert(m_config != nullptr);
std::unordered_set<DexType*> perf_sensitive_classes;
auto& global_config = m_config->get_global_config();
MethodProfileOrderingConfig* profiles_config{nullptr};
if (global_config.has_config_by_name("method_profile_order")) {
profiles_config =
global_config.get_config_by_name<MethodProfileOrderingConfig>(
"method_profile_order");
}
if (profiles_config != nullptr &&
profiles_config->skip_similarity_reordering) {
auto& method_profiles = m_config->get_method_profiles();
// Some builds might not have method profiles information.
if (method_profiles.is_initialized()) {
method_profiles::dexmethods_profiled_comparator comparator(
lmeth,
/*method_profiles=*/&method_profiles,
profiles_config);
for (auto meth : lmeth) {
auto method_sort_num = comparator.get_overall_method_sort_num(meth);
if (method_sort_num <
method_profiles::dexmethods_profiled_comparator::VERY_END) {
perf_sensitive_classes.insert(meth->get_class());
}
}
}
}
bool use_compression_conscious_order{false};
MethodSimilarityOrderingConfig* similarity_config{nullptr};
if (global_config.has_config_by_name("method_similarity_order")) {
similarity_config =
global_config.get_config_by_name<MethodSimilarityOrderingConfig>(
"method_similarity_order");
use_compression_conscious_order =
similarity_config->use_compression_conscious_order;
}
if (similarity_config != nullptr &&
similarity_config->use_class_level_perf_sensitivity) {
for (auto meth : lmeth) {
auto cls = type_class(meth->get_class());
if (!cls->is_perf_sensitive()) {
continue;
}
perf_sensitive_classes.insert(meth->get_class());
}
}
std::vector<DexMethod*> perf_sensitive_methods;
std::vector<DexMethod*> remaining_methods;
for (auto meth : lmeth) {
if (perf_sensitive_classes.count(meth->get_class())) {
perf_sensitive_methods.push_back(meth);
} else {
remaining_methods.push_back(meth);
}
}
TRACE(
OPUT, 2,
"Skipping %zu perf sensitive methods, ordering %zu methods by similarity",
perf_sensitive_methods.size(), remaining_methods.size());
if (use_compression_conscious_order) {
MethodSimilarityCompressionConsciousOrderer method_orderer;
method_orderer.order(remaining_methods, this);
} else {
MethodSimilarityGreedyOrderer method_orderer;
method_orderer.order(remaining_methods);
}
lmeth.clear();
lmeth.insert(lmeth.end(), perf_sensitive_methods.begin(),
perf_sensitive_methods.end());
lmeth.insert(lmeth.end(), remaining_methods.begin(), remaining_methods.end());
}
void GatheredTypes::sort_dexmethod_emitlist_default_order(
std::vector<DexMethod*>& lmeth) {
std::stable_sort(lmeth.begin(), lmeth.end(), compare_dexmethods);
}
void GatheredTypes::sort_dexmethod_emitlist_cls_order(
std::vector<DexMethod*>& lmeth) {
std::stable_sort(lmeth.begin(), lmeth.end(),
CustomSort<DexMethod, cmp_dmethod>(m_methods_in_cls_order,
compare_dexmethods));
}
void GatheredTypes::sort_dexmethod_emitlist_coldstart_order(
std::vector<DexMethod*>& lmeth) {
const auto& coldstart_methods = m_config->get_coldstart_methods();
if (coldstart_methods.empty()) {
return;
}
std::unordered_map<const DexMethod*, unsigned int> coldstart_method_ordering;
for (auto& method : coldstart_methods) {
DexMethodRef* method_ref = DexMethod::get_method(method);
if (method_ref == nullptr || !method_ref->is_def()) {
continue;
}
auto* meth = method_ref->as_def();
always_assert_log(coldstart_method_ordering.count(meth) == 0,
"%s already found at position %u", SHOW(meth),
coldstart_method_ordering.at(meth));
coldstart_method_ordering[meth] = coldstart_method_ordering.size();
}
std::unordered_map<const DexMethodRef*, size_t> initial_ordering;
for (auto* m : lmeth) {
initial_ordering[m] = initial_ordering.size();
}
auto coldstart_cmp = [&initial_ordering, &coldstart_method_ordering](
const DexMethod* a, const DexMethod* b) {
const auto end_it = coldstart_method_ordering.end();
const auto a_it = coldstart_method_ordering.find(a);
const auto b_it = coldstart_method_ordering.find(b);
if (a_it == end_it && b_it == end_it) {
return initial_ordering.at(a) < initial_ordering.at(b);
}
if (a_it != end_it && b_it != end_it) {
const auto a_idx = a_it->second;
const auto b_idx = b_it->second;
if (a_idx != b_idx) {
return a_idx < b_idx;
}
return initial_ordering.at(a) < initial_ordering.at(b);
}
if (a_it != end_it) {
return true;
}
return false;
};
std::stable_sort(lmeth.begin(), lmeth.end(), coldstart_cmp);
}
void GatheredTypes::sort_dexmethod_emitlist_profiled_order(
std::vector<DexMethod*>& lmeth) {
// Use std::ref to avoid comparator copies.
redex_assert(m_config != nullptr);
MethodProfileOrderingConfig* config =
m_config->get_global_config()
.get_config_by_name<MethodProfileOrderingConfig>(
"method_profile_order");
method_profiles::dexmethods_profiled_comparator comparator(
lmeth,
/*method_profiles=*/&m_config->get_method_profiles(),
config);
std::stable_sort(lmeth.begin(), lmeth.end(), std::ref(comparator));
}
void GatheredTypes::sort_dexmethod_emitlist_clinit_order(
std::vector<DexMethod*>& lmeth) {
std::stable_sort(lmeth.begin(), lmeth.end(),
[](const DexMethod* a, const DexMethod* b) {
if (method::is_clinit(a) && !method::is_clinit(b)) {
return true;
} else {
return false;
}
});
}
DexOutputIdx GatheredTypes::get_dodx(const uint8_t* base) {
/*
* These are symbol table indices. Symbols which are used
* should be bunched together. We will pass a different
* sort routine here to optimize. Doing so does violate
* the dex spec. However, that aspect of the spec is only
* used in certain scenarios. For strings, types, and protos
* that aspect of the spec has no runtime dependency. For
* methods and fields, only dexes with annotations have a
* dependency on ordering.
*/
auto proto = get_proto_index();
auto typelist = get_typelist_list(&proto);
return DexOutputIdx(get_string_index(),
get_type_index(),
std::move(proto),
get_field_index(),
get_method_index(),
std::move(typelist),
get_callsite_index(),
get_methodhandle_index(),
base);
}
namespace {
template <typename Cout, typename Cin, typename Cmp>
Cout create_index(Cin& in, const Cmp& cmp) {
std::sort(in.begin(), in.end(), cmp);
Cout sidx{};
sidx.reserve(in.size());
uint32_t idx = 0;
for (auto it = in.begin(); it != in.end(); it++) {
sidx.insert(std::make_pair(*it, idx++));
}
return sidx;
}
} // namespace
dexstring_to_idx GatheredTypes::get_string_index(cmp_dstring cmp) {
return create_index<dexstring_to_idx>(m_lstring, cmp);
}
dextype_to_idx GatheredTypes::get_type_index(cmp_dtype cmp) {
return create_index<dextype_to_idx>(m_ltype, cmp);
}
dexfield_to_idx GatheredTypes::get_field_index(cmp_dfield cmp) {
return create_index<dexfield_to_idx>(m_lfield, cmp);
}
dexmethod_to_idx GatheredTypes::get_method_index(cmp_dmethod cmp) {
return create_index<dexmethod_to_idx>(m_lmethod, cmp);
}
dexproto_to_idx GatheredTypes::get_proto_index(cmp_dproto cmp) {
// TODO: Profile and see whether a set first would be more efficient.
std::vector<DexProto*> protos;
protos.reserve(m_lmethod.size() + m_lcallsite.size());
for (auto const& m : m_lmethod) {
protos.push_back(m->get_proto());
}
for (auto const& c : m_lcallsite) {
protos.push_back(c->method_type());
for (auto& arg : c->args()) {
// n.b. how deep could this recursion go? what if there was a method
// handle here?
if (arg->evtype() == DEVT_METHOD_TYPE) {
protos.push_back(((DexEncodedValueMethodType*)arg.get())->proto());
}
}
}
std::sort(protos.begin(), protos.end());
protos.erase(std::unique(protos.begin(), protos.end()), protos.end());
return create_index<dexproto_to_idx>(protos, cmp);
}
std::vector<DexTypeList*> GatheredTypes::get_typelist_list(
dexproto_to_idx* protos, cmp_dtypelist cmp) {
std::vector<DexTypeList*> typel{};
auto class_defs_size = (uint32_t)m_classes->size();
typel.reserve(protos->size() + class_defs_size);
for (auto& it : *protos) {
auto proto = it.first;
typel.push_back(proto->get_args());
}
for (uint32_t i = 0; i < class_defs_size; i++) {
DexClass* clz = m_classes->at(i);
typel.push_back(clz->get_interfaces());
}
sort_unique(typel, compare_dextypelists);
return typel;
}
dexcallsite_to_idx GatheredTypes::get_callsite_index(cmp_callsite cmp) {
return create_index<dexcallsite_to_idx>(m_lcallsite, cmp);
}
dexmethodhandle_to_idx GatheredTypes::get_methodhandle_index(
cmp_methodhandle cmp) {
return create_index<dexmethodhandle_to_idx>(m_lmethodhandle, cmp);
}
void GatheredTypes::build_cls_load_map() {
unsigned int index = 0;
int type_strings = 0;
int init_strings = 0;
int total_strings = 0;
for (const auto& cls : *m_classes) {
// gather type first, assuming class load will check all components of a
// class first
std::vector<DexType*> cls_types;
cls->gather_types(cls_types);
std::sort(cls_types.begin(), cls_types.end(), compare_dextypes);
for (const auto& t : cls_types) {
if (!m_cls_load_strings.count(t->get_name())) {
m_cls_load_strings[t->get_name()] = index;
index++;
type_strings++;
}
}
// now add in any strings found in <clinit>
// since they are likely to be accessed during class load
for (const auto& m : cls->get_dmethods()) {
if (method::is_clinit(m)) {
std::vector<const DexString*> method_strings;
m->gather_strings(method_strings);
for (const auto& s : method_strings) {
if (!m_cls_load_strings.count(s)) {
m_cls_load_strings[s] = index;
index++;
init_strings++;
}
}
}
}
}
total_strings += type_strings + init_strings;
for (const auto& cls : *m_classes) {
// now add all other strings in class order. This way we get some
// locality if a random class in a dex is loaded and then executes some
// methods
std::vector<const DexClass*> v;
v.push_back(cls);
walk::methods(v, [&](DexMethod* m) {
std::vector<const DexString*> method_strings;
m->gather_strings(method_strings);
for (const auto& s : method_strings) {
if (!m_cls_load_strings.count(s)) {
m_cls_load_strings[s] = index;
index++;
total_strings++;
}
}
});
}
TRACE(CUSTOMSORT, 1,
"found %d strings from types, %d from strings in init methods, %d "
"total strings",
type_strings, init_strings, total_strings);
}
void GatheredTypes::build_cls_map() {
int index = 0;
for (const auto& cls : *m_classes) {
if (!m_cls_strings.count(cls->get_name())) {
m_cls_strings[cls->get_name()] = index++;
}
}
}
void GatheredTypes::build_method_map() {
unsigned int index = 0;
for (const auto& cls : *m_classes) {
for (const auto& m : cls->get_dmethods()) {
if (!m_methods_in_cls_order.count(m)) {
m_methods_in_cls_order[m] = index;
}
}
for (const auto& m : cls->get_vmethods()) {
if (!m_methods_in_cls_order.count(m)) {
m_methods_in_cls_order[m] = index;
}
}
index++;
}
}
namespace {
// Leave 250K empty as a margin to not overrun.
constexpr uint32_t k_output_red_zone = 250000;
constexpr uint32_t k_default_max_dex_size = 32 * 1024 * 1024;
uint32_t get_dex_output_size(const ConfigFiles& conf) {
size_t output_size;
conf.get_json_config().get("dex_output_buffer_size", k_default_max_dex_size,
output_size);
return (uint32_t)output_size;
}
} // namespace
CodeItemEmit::CodeItemEmit(DexMethod* meth, DexCode* c, dex_code_item* ci)
: method(meth), code(c), code_item(ci) {}
namespace {
// DO NOT CHANGE THESE VALUES! Many services will break if you do.
constexpr const char* METHOD_MAPPING = "redex-method-id-map.txt";
constexpr const char* CLASS_MAPPING = "redex-class-id-map.txt";
constexpr const char* BYTECODE_OFFSET_MAPPING = "redex-bytecode-offset-map.txt";
constexpr const char* REDEX_PG_MAPPING = "redex-class-rename-map.txt";
constexpr const char* REDEX_FULL_MAPPING = "redex-full-rename-map.txt";
} // namespace
DexOutput::DexOutput(
const char* path,
DexClasses* classes,
std::shared_ptr<GatheredTypes> gtypes,
LocatorIndex* locator_index,
bool normal_primary_dex,
size_t store_number,
const std::string* store_name,
size_t dex_number,
DebugInfoKind debug_info_kind,
IODIMetadata* iodi_metadata,
const ConfigFiles& config_files,
PositionMapper* pos_mapper,
std::unordered_map<DexMethod*, uint64_t>* method_to_id,
std::unordered_map<DexCode*, std::vector<DebugLineItem>>* code_debug_lines,
const DexOutputConfig& dex_output_config,
int min_sdk)
: m_classes(classes),
m_output_size((debug_info_kind == DebugInfoKind::BytecodeDebugger
? get_dex_output_size(config_files) * 2
: get_dex_output_size(config_files)) +
k_output_red_zone),
m_output(std::make_unique<uint8_t[]>(m_output_size)),
m_gtypes(std::move(gtypes)),
m_dodx(m_gtypes->get_dodx(m_output.get())),
// Required because the BytecodeDebugger setting creates huge amounts
// of debug information (multiple dex debug entries per instruction)
m_offset(0),
m_iodi_metadata(iodi_metadata),
m_config_files(config_files),
m_min_sdk(min_sdk),
m_dex_output_config(dex_output_config) {
// Ensure a clean slate.
memset(m_output.get(), 0, m_output_size);
always_assert_log(
m_dodx.method_to_idx().size() <= kMaxMethodRefs,
"Trying to encode too many method refs in dex %s: %zu (limit: %zu). Run "
"with check_properties_deep turned on.",
boost::filesystem::path(path).filename().c_str(),
m_dodx.method_to_idx().size(),
kMaxMethodRefs);
always_assert_log(
m_dodx.field_to_idx().size() <= kMaxFieldRefs,
"Trying to encode too many field refs in dex %s: %zu (limit: %zu). Run "
"with check_properties_deep turned on.",
boost::filesystem::path(path).filename().c_str(),
m_dodx.field_to_idx().size(),
kMaxFieldRefs);
m_filename = path;
m_pos_mapper = pos_mapper;
m_method_to_id = method_to_id;
m_code_debug_lines = code_debug_lines;
m_method_mapping_filename = config_files.metafile(METHOD_MAPPING);
m_class_mapping_filename = config_files.metafile(CLASS_MAPPING);
m_pg_mapping_filename = config_files.metafile(REDEX_PG_MAPPING);
m_full_mapping_filename = config_files.metafile(REDEX_FULL_MAPPING);
m_bytecode_offset_filename = config_files.metafile(BYTECODE_OFFSET_MAPPING);
m_store_number = store_number;
m_store_name = store_name;
m_dex_number = dex_number;
m_locator_index = locator_index;
m_normal_primary_dex = normal_primary_dex;
m_debug_info_kind = debug_info_kind;
}
void DexOutput::insert_map_item(uint16_t maptype,
uint32_t size,
uint32_t offset,
uint32_t bytes) {
if (size == 0) return;
dex_map_item item{};
item.type = maptype;
item.size = size;
item.offset = offset;
m_map_items.emplace_back(item);
switch (maptype) {
case TYPE_HEADER_ITEM:
m_stats.header_item_count += size;
m_stats.header_item_bytes += bytes;
break;
case TYPE_STRING_ID_ITEM:
m_stats.string_id_count += size;
m_stats.string_id_bytes += bytes;
break;
case TYPE_TYPE_ID_ITEM:
m_stats.type_id_count += size;
m_stats.type_id_bytes += bytes;
break;
case TYPE_PROTO_ID_ITEM:
m_stats.proto_id_count += size;
m_stats.proto_id_bytes += bytes;
break;
case TYPE_FIELD_ID_ITEM:
m_stats.field_id_count += size;
m_stats.field_id_bytes += bytes;
break;
case TYPE_METHOD_ID_ITEM:
m_stats.method_id_count += size;
m_stats.method_id_bytes += bytes;
break;
case TYPE_CLASS_DEF_ITEM:
m_stats.class_def_count += size;
m_stats.class_def_bytes += bytes;
break;
case TYPE_CALL_SITE_ID_ITEM:
m_stats.call_site_id_count += size;
m_stats.call_site_id_bytes += bytes;
break;
case TYPE_METHOD_HANDLE_ITEM:
m_stats.method_handle_count += size;
m_stats.method_handle_bytes += bytes;
break;
case TYPE_MAP_LIST:
m_stats.map_list_count += size;
m_stats.map_list_bytes += bytes;
break;
case TYPE_TYPE_LIST:
m_stats.type_list_count += size;
m_stats.type_list_bytes += bytes;
break;
case TYPE_ANNOTATION_SET_REF_LIST:
m_stats.annotation_set_ref_list_count += size;
m_stats.annotation_set_ref_list_bytes += bytes;
break;
case TYPE_ANNOTATION_SET_ITEM:
m_stats.annotation_set_count += size;
m_stats.annotation_set_bytes += bytes;
break;
case TYPE_CLASS_DATA_ITEM:
m_stats.class_data_count += size;
m_stats.class_data_bytes += bytes;
break;
case TYPE_CODE_ITEM:
m_stats.code_count += size;
m_stats.code_bytes += bytes;
break;
case TYPE_STRING_DATA_ITEM:
m_stats.string_data_count += size;
m_stats.string_data_bytes += bytes;
break;
case TYPE_DEBUG_INFO_ITEM:
m_stats.debug_info_count += size;
m_stats.debug_info_bytes += bytes;
break;
case TYPE_ANNOTATION_ITEM:
m_stats.annotation_count += size;
m_stats.annotation_bytes += bytes;
break;
case TYPE_ENCODED_ARRAY_ITEM:
m_stats.encoded_array_count += size;
m_stats.encoded_array_bytes += bytes;
break;
case TYPE_ANNOTATIONS_DIR_ITEM:
m_stats.annotations_directory_count += size;
m_stats.annotations_directory_bytes += bytes;
break;
}
}
void DexOutput::emit_locator(Locator locator) {
char buf[Locator::encoded_max];
size_t locator_length = locator.encode(buf);
write_uleb128(m_output.get() + m_offset, (uint32_t)locator_length);
inc_offset(uleb128_encoding_size((uint32_t)locator_length));
memcpy(m_output.get() + m_offset, buf, locator_length + 1);
inc_offset(locator_length + 1);
}
std::unique_ptr<Locator> DexOutput::locator_for_descriptor(
const std::unordered_set<const DexString*>& type_names,
const DexString* descriptor) {
LocatorIndex* locator_index = m_locator_index;
if (locator_index != nullptr) {
const char* s = descriptor->c_str();
uint32_t global_clsnr = Locator::decodeGlobalClassIndex(s);
if (global_clsnr != Locator::invalid_global_class_index) {
// We don't need locators for renamed classes since
// name-based-locators are enabled.
return nullptr;
}
auto locator_it = locator_index->find(descriptor);
if (locator_it != locator_index->end()) {
// This string is the name of a type we define in one of our
// dex files.
return std::unique_ptr<Locator>(new Locator(locator_it->second));
}
if (type_names.count(descriptor)) {
// If we're emitting an array name, see whether the element
// type is one of ours; if so, emit a locator for that type.
if (s[0] == '[') {
while (*s == '[') {
++s;
}
auto elementDescriptor = DexString::get_string(s);
if (elementDescriptor != nullptr) {
locator_it = locator_index->find(elementDescriptor);
if (locator_it != locator_index->end()) {
return std::unique_ptr<Locator>(new Locator(locator_it->second));
}
}
}
// We have the name of a type, but it's not a type we define.
// Emit the special locator that indicates we should look in the
// system classloader.
return std::unique_ptr<Locator>(new Locator(Locator::make(0, 0, 0)));
}
}
return nullptr;
}
void DexOutput::generate_string_data(SortMode mode) {
/*
* This is a index to position within the string data. There
* is no specific ordering specified here for the dex spec.
* The optimized sort here would be different than the one
* for the symbol table. The symbol table should be packed
* for strings that are used by the opcode const-string. Whereas
* this should be ordered by access for page-cache efficiency.
*/
std::vector<const DexString*> string_order;
if (mode == SortMode::CLASS_ORDER) {
TRACE(CUSTOMSORT, 2, "using class order for string pool sorting");
string_order = m_gtypes->get_cls_order_dexstring_emitlist();
} else if (mode == SortMode::CLASS_STRINGS) {
TRACE(CUSTOMSORT, 2, "using class names pack for string pool sorting");
string_order = m_gtypes->keep_cls_strings_together_emitlist();
} else {
TRACE(CUSTOMSORT, 2, "using default string pool sorting");
string_order = m_gtypes->get_dexstring_emitlist();
}
dex_string_id* stringids =
(dex_string_id*)(m_output.get() + hdr.string_ids_off);
std::unordered_set<const DexString*> type_names =
m_gtypes->index_type_names();
unsigned locator_size = 0;
// If we're generating locator strings, we need to include them in
// the total count of strings in this section.
size_t locators = 0;
for (auto* str : string_order) {
if (locator_for_descriptor(type_names, str)) {
++locators;
}
}
if (m_locator_index != nullptr) {
locators += 3;
always_assert(m_dodx.stringidx(DexString::make_string("")) == 0);
}
size_t nrstr = string_order.size() + locators;
const uint32_t str_data_start = m_offset;
for (auto* str : string_order) {
// Emit lookup acceleration string if requested
std::unique_ptr<Locator> locator = locator_for_descriptor(type_names, str);
if (locator) {
unsigned orig_offset = m_offset;
emit_locator(*locator);
locator_size += m_offset - orig_offset;
}
// Emit name-based lookup acceleration information for string with index 0
// if requested
uint32_t idx = m_dodx.stringidx(str);
if (idx == 0 && m_locator_index != nullptr) {
always_assert(!locator);
unsigned orig_offset = m_offset;
emit_magic_locators();
locator_size += m_offset - orig_offset;
}
// Emit the string itself
TRACE(CUSTOMSORT, 3, "str emit %s", SHOW(str));
stringids[idx].offset = m_offset;
str->encode(m_output.get() + m_offset);
inc_offset(str->get_entry_size());
m_stats.num_strings++;
}
insert_map_item(TYPE_STRING_DATA_ITEM, (uint32_t)nrstr, str_data_start,
m_offset - str_data_start);
if (m_locator_index != nullptr) {
TRACE(LOC, 2, "Used %u bytes for %zu locator strings", locator_size,
locators);
}
}
void DexOutput::emit_magic_locators() {
uint32_t global_class_indices_first = Locator::invalid_global_class_index;
uint32_t global_class_indices_last = Locator::invalid_global_class_index;
// We decode all class names --- to find the first and last renamed one,
// and also check that all renamed names are indeed in the right place.
for (uint32_t i = 0; i < hdr.class_defs_size; i++) {
DexClass* clz = m_classes->at(i);
const char* str = clz->get_name()->c_str();
uint32_t global_clsnr = Locator::decodeGlobalClassIndex(str);
TRACE(LOC, 3, "Class %s has global class index %u", str, global_clsnr);
if (global_clsnr != Locator::invalid_global_class_index) {
global_class_indices_last = global_clsnr;
if (global_class_indices_first == Locator::invalid_global_class_index) {
// First time we come across a properly renamed class - let's store the
// global_class_indices_first.
// Note that the first class in this dex might not actually be a renamed
// class. But we want our class loaders to be able to determine a the
// actual class table index of a class by simply subtracting a number.
// So we set global_class_indices_first to be the global class index of
// the actual first class the dex, which was the class i iterations
// earlier.
global_class_indices_first = global_clsnr - i;
} else {
always_assert_log(
global_clsnr == global_class_indices_first + i,
"Out of order global class index: got %u, expected %u\n",
global_clsnr, global_class_indices_first + i);
}
}
}
TRACE(LOC, 2,
"Global class indices for store %zu, dex %zu: first %u, last %u",
m_store_number, m_dex_number, global_class_indices_first,
global_class_indices_last);
// Emit three locator strings
if (global_class_indices_first == Locator::invalid_global_class_index) {
// This dex defines no renamed classes. We encode this with a special
// otherwise illegal convention:
global_class_indices_first = 1;
global_class_indices_last = 0;
}
// 1. Locator for the last renamed class in this Dex
emit_locator(
Locator(m_store_number, m_dex_number + 1, global_class_indices_last));
// 2. Locator for what would be the first class in this Dex
// (see comment for computation of global_class_indices_first above)
emit_locator(
Locator(m_store_number, m_dex_number + 1, global_class_indices_first));
// magic locator
emit_locator(Locator(Locator::magic_strnr, Locator::magic_dexnr,
Locator::magic_clsnr));
}
void DexOutput::generate_type_data() {
always_assert_log(
m_dodx.type_to_idx().size() < get_max_type_refs(m_min_sdk),
"Trying to encode too many type refs in dex %zu: %zu (limit: %zu).\n"
"NOTE: Please check InterDexPass config flags and set: "
"`reserved_trefs: %zu` (or larger, until the issue goes away)",
m_dex_number,
m_dodx.type_to_idx().size(),
get_max_type_refs(m_min_sdk),
m_dodx.type_to_idx().size() - get_max_type_refs(m_min_sdk));
dex_type_id* typeids = (dex_type_id*)(m_output.get() + hdr.type_ids_off);
for (auto& p : m_dodx.type_to_idx()) {
auto t = p.first;
auto idx = p.second;
typeids[idx].string_idx = m_dodx.stringidx(t->get_name());
m_stats.num_types++;
}
}
void DexOutput::generate_typelist_data() {
const auto& typel = m_dodx.typelist_list();
uint32_t tl_start = align(m_offset);
size_t num_tls = 0;
for (DexTypeList* tl : typel) {
if (tl->empty()) {
m_tl_emit_offsets[tl] = 0;
continue;
}
++num_tls;
align_output();
m_tl_emit_offsets[tl] = m_offset;
int size = tl->encode(&m_dodx, (uint32_t*)(m_output.get() + m_offset));
inc_offset(size);
m_stats.num_type_lists++;
}
/// insert_map_item returns early if num_tls is zero
insert_map_item(TYPE_TYPE_LIST, (uint32_t)num_tls, tl_start,
m_offset - tl_start);
}
void DexOutput::generate_proto_data() {
auto protoids = (dex_proto_id*)(m_output.get() + hdr.proto_ids_off);
for (auto& it : m_dodx.proto_to_idx()) {
auto proto = it.first;
auto idx = it.second;
protoids[idx].shortyidx = m_dodx.stringidx(proto->get_shorty());
protoids[idx].rtypeidx = m_dodx.typeidx(proto->get_rtype());
protoids[idx].param_off = m_tl_emit_offsets.at(proto->get_args());
m_stats.num_protos++;
}
}
void DexOutput::generate_field_data() {
auto fieldids = (dex_field_id*)(m_output.get() + hdr.field_ids_off);
for (auto& it : m_dodx.field_to_idx()) {
auto field = it.first;
auto idx = it.second;
fieldids[idx].classidx = m_dodx.typeidx(field->get_class());
fieldids[idx].typeidx = m_dodx.typeidx(field->get_type());
fieldids[idx].nameidx = m_dodx.stringidx(field->get_name());
m_stats.num_field_refs++;
}
}
void DexOutput::generate_method_data() {
auto methodids = (dex_method_id*)(m_output.get() + hdr.method_ids_off);
for (auto& it : m_dodx.method_to_idx()) {
auto method = it.first;
auto idx = it.second;
methodids[idx].classidx = m_dodx.typeidx(method->get_class());
methodids[idx].protoidx = m_dodx.protoidx(method->get_proto());
methodids[idx].nameidx = m_dodx.stringidx(method->get_name());
m_stats.num_method_refs++;
}
}