This repository was archived by the owner on Jun 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathdex2oat.cc
More file actions
2270 lines (2059 loc) · 91.3 KB
/
dex2oat.cc
File metadata and controls
2270 lines (2059 loc) · 91.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <valgrind.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>
#if defined(__linux__) && defined(__arm__)
#include <sys/personality.h>
#include <sys/utsname.h>
#endif
#define ATRACE_TAG ATRACE_TAG_DALVIK
#include <cutils/trace.h>
#include "art_method-inl.h"
#include "arch/instruction_set_features.h"
#include "arch/mips/instruction_set_features_mips.h"
#include "base/dumpable.h"
#include "base/macros.h"
#include "base/stl_util.h"
#include "base/stringpiece.h"
#include "base/time_utils.h"
#include "base/timing_logger.h"
#include "base/unix_file/fd_file.h"
#include "class_linker.h"
#include "compiler.h"
#include "compiler_callbacks.h"
#include "dex_file-inl.h"
#include "dex/pass_manager.h"
#include "dex/verification_results.h"
#include "dex/quick_compiler_callbacks.h"
#include "dex/quick/dex_file_to_method_inliner_map.h"
#include "driver/compiler_driver.h"
#include "driver/compiler_options.h"
#include "elf_file.h"
#include "elf_writer.h"
#include "gc/space/image_space.h"
#include "gc/space/space-inl.h"
#include "image_writer.h"
#include "interpreter/unstarted_runtime.h"
#include "leb128.h"
#include "mirror/class-inl.h"
#include "mirror/class_loader.h"
#include "mirror/object-inl.h"
#include "mirror/object_array-inl.h"
#include "oat_file_assistant.h"
#include "oat_writer.h"
#include "os.h"
#include "runtime.h"
#include "ScopedLocalRef.h"
#include "scoped_thread_state_change.h"
#include "utils.h"
#include "vector_output_stream.h"
#include "well_known_classes.h"
#include "zip_archive.h"
#ifdef HAVE_ANDROID_OS
#include "cutils/properties.h"
#endif
#include "xz_config.h"
#include "xz.h"
#include "xz_private.h"
namespace art {
static int original_argc;
static char** original_argv;
static std::string CommandLine() {
std::vector<std::string> command;
for (int i = 0; i < original_argc; ++i) {
command.push_back(original_argv[i]);
}
return Join(command, ' ');
}
// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
// locations are all staged).
static std::string StrippedCommandLine() {
std::vector<std::string> command;
// Do a pre-pass to look for zip-fd.
bool saw_zip_fd = false;
for (int i = 0; i < original_argc; ++i) {
if (StartsWith(original_argv[i], "--zip-fd=")) {
saw_zip_fd = true;
break;
}
}
// Now filter out things.
for (int i = 0; i < original_argc; ++i) {
// All runtime-arg parameters are dropped.
if (strcmp(original_argv[i], "--runtime-arg") == 0) {
i++; // Drop the next part, too.
continue;
}
// Any instruction-setXXX is dropped.
if (StartsWith(original_argv[i], "--instruction-set")) {
continue;
}
// The boot image is dropped.
if (StartsWith(original_argv[i], "--boot-image=")) {
continue;
}
// This should leave any dex-file and oat-file options, describing what we compiled.
// However, we prefer to drop this when we saw --zip-fd.
if (saw_zip_fd) {
// Drop anything --zip-X, --dex-X, --oat-X, --swap-X.
if (StartsWith(original_argv[i], "--zip-") ||
StartsWith(original_argv[i], "--dex-") ||
StartsWith(original_argv[i], "--oat-") ||
StartsWith(original_argv[i], "--swap-")) {
continue;
}
}
command.push_back(original_argv[i]);
}
// Construct the final output.
if (command.size() <= 1U) {
// It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
return "Starting dex2oat.";
}
return Join(command, ' ');
}
static void UsageErrorV(const char* fmt, va_list ap) {
std::string error;
StringAppendV(&error, fmt, ap);
LOG(ERROR) << error;
}
static void UsageError(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
UsageErrorV(fmt, ap);
va_end(ap);
}
NO_RETURN static void Usage(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
UsageErrorV(fmt, ap);
va_end(ap);
UsageError("Command: %s", CommandLine().c_str());
UsageError("Usage: dex2oat [options]...");
UsageError("");
UsageError(" -j<number>: specifies the number of threads used for compilation.");
UsageError(" Default is the number of detected hardware threads available on the");
UsageError(" host system.");
UsageError(" Example: -j12");
UsageError("");
UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
UsageError(" Example: --dex-file=/system/framework/core.jar");
UsageError("");
UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
UsageError(" encode in the oat file for the corresponding --dex-file argument.");
UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
UsageError(" --dex-location=/system/framework/core.jar");
UsageError("");
UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
UsageError(" containing a classes.dex file to compile.");
UsageError(" Example: --zip-fd=5");
UsageError("");
UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
UsageError(" corresponding to the file descriptor specified by --zip-fd.");
UsageError(" Example: --zip-location=/system/app/Calculator.apk");
UsageError("");
UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
UsageError(" Example: --oat-file=/system/framework/boot.oat");
UsageError("");
UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
UsageError(" Example: --oat-fd=6");
UsageError("");
UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
UsageError(" to the file descriptor specified by --oat-fd.");
UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
UsageError("");
UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
UsageError("");
UsageError(" --image=<file.art>: specifies the output image filename.");
UsageError(" Example: --image=/system/framework/boot.art");
UsageError("");
UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
UsageError(" Example: --image=frameworks/base/preloaded-classes");
UsageError("");
UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
UsageError(" Example: --base=0x50000000");
UsageError("");
UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
UsageError(" Example: --boot-image=/system/framework/boot.art");
UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
UsageError("");
UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
UsageError(" Example: --android-root=out/host/linux-x86");
UsageError(" Default: $ANDROID_ROOT");
UsageError("");
UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
UsageError(" instruction set.");
UsageError(" Example: --instruction-set=x86");
UsageError(" Default: arm");
UsageError("");
UsageError(" --instruction-set-features=...,: Specify instruction set features");
UsageError(" Example: --instruction-set-features=div");
UsageError(" Default: default");
UsageError("");
UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
UsageError(" Default: disabled");
UsageError("");
UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
UsageError(" set.");
UsageError(" Example: --compiler-backend=Optimizing");
if (kUseOptimizingCompiler) {
UsageError(" Default: Optimizing");
} else {
UsageError(" Default: Quick");
}
UsageError("");
UsageError(" --compiler-filter="
"(verify-none"
"|interpret-only"
"|space"
"|balanced"
"|speed"
"|everything"
"|time):");
UsageError(" select compiler filter.");
UsageError(" Example: --compiler-filter=everything");
UsageError(" Default: speed");
UsageError("");
UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
UsageError(" method for compiler filter tuning.");
UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
UsageError("");
UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
UsageError(" method for compiler filter tuning.");
UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
UsageError("");
UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
UsageError(" method for compiler filter tuning.");
UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
UsageError("");
UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
UsageError(" method for compiler filter tuning.");
UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
UsageError("");
UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
UsageError(" compiler filter tuning. If the input has fewer than this many methods");
UsageError(" and the filter is not interpret-only or verify-none, overrides the");
UsageError(" filter to use speed");
UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
UsageError("");
UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
UsageError(" Has priority over the --compiler-filter option. Intended for ");
UsageError(" development/experimental use.");
UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
UsageError("");
UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
UsageError(" Intended for development/experimental use.");
UsageError(" Example: --inline-max-code-units=%d",
CompilerOptions::kDefaultInlineMaxCodeUnits);
UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
UsageError("");
UsageError(" --dump-timing: display a breakdown of where time was spent");
UsageError("");
UsageError(" --include-patch-information: Include patching information so the generated code");
UsageError(" can have its base address moved without full recompilation.");
UsageError("");
UsageError(" --no-include-patch-information: Do not include patching information.");
UsageError("");
UsageError(" -g");
UsageError(" --generate-debug-info: Generate debug information for native debugging,");
UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
UsageError(" This generates all the available information. Unneeded parts can be");
UsageError(" stripped using standard command line tools such as strip or objcopy.");
UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
UsageError("");
UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
UsageError("");
UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
UsageError(" such as initial heap size, maximum heap size, and verbose output.");
UsageError(" Use a separate --runtime-arg switch for each argument.");
UsageError(" Example: --runtime-arg -Xms256m");
UsageError("");
UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
UsageError("");
UsageError(" --print-pass-names: print a list of pass names");
UsageError("");
UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
UsageError("");
UsageError(" --print-pass-options: print a list of passes that have configurable options along "
"with the setting.");
UsageError(" Will print default if no overridden setting exists.");
UsageError("");
UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
"Pass2Name:Pass2OptionName:Pass2Option#");
UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
UsageError(" Separator used between options is a comma.");
UsageError("");
UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
UsageError(" Example: --swap-file=/data/tmp/swap.001");
UsageError("");
UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
UsageError(" Example: --swap-fd=10");
UsageError("");
std::cerr << "See log for usage error information\n";
exit(EXIT_FAILURE);
}
// The primary goal of the watchdog is to prevent stuck build servers
// during development when fatal aborts lead to a cascade of failures
// that result in a deadlock.
class WatchDog {
// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
#undef CHECK_PTHREAD_CALL
#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
do { \
int rc = call args; \
if (rc != 0) { \
errno = rc; \
std::string message(# call); \
message += " failed for "; \
message += reason; \
Fatal(message); \
} \
} while (false)
public:
explicit WatchDog(bool is_watch_dog_enabled) {
is_watch_dog_enabled_ = is_watch_dog_enabled;
if (!is_watch_dog_enabled_) {
return;
}
shutting_down_ = false;
const char* reason = "dex2oat watch dog thread startup";
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
}
~WatchDog() {
if (!is_watch_dog_enabled_) {
return;
}
const char* reason = "dex2oat watch dog thread shutdown";
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
shutting_down_ = true;
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
}
private:
static void* CallBack(void* arg) {
WatchDog* self = reinterpret_cast<WatchDog*>(arg);
::art::SetThreadName("dex2oat watch dog");
self->Wait();
return nullptr;
}
NO_RETURN static void Fatal(const std::string& message) {
// TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
// it's rather easy to hang in unwinding.
// LogLine also avoids ART logging lock issues, as it's really only a wrapper around
// logcat logging or stderr output.
LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
exit(1);
}
void Wait() {
// TODO: tune the multiplier for GC verification, the following is just to make the timeout
// large.
constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
timespec timeout_ts;
InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
const char* reason = "dex2oat watch dog thread waiting";
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
while (!shutting_down_) {
int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
if (rc == ETIMEDOUT) {
Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
kWatchDogTimeoutSeconds));
} else if (rc != 0) {
std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
strerror(errno)));
Fatal(message.c_str());
}
}
CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
}
// When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
// Debug builds are slower so they have larger timeouts.
static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
// 59.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
// watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 60 minutes), so that dex2oat will abort
// itself before that watchdog would take down the system server.
static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (59 * 60 + 30);
bool is_watch_dog_enabled_;
bool shutting_down_;
// TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
pthread_mutex_t mutex_;
pthread_cond_t cond_;
pthread_attr_t attr_;
pthread_t pthread_;
};
static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
std::string::size_type colon = s.find(c);
if (colon == std::string::npos) {
Usage("Missing char %c in option %s\n", c, s.c_str());
}
// Add one to remove the char we were trimming until.
*parsed_value = s.substr(colon + 1);
}
static void ParseDouble(const std::string& option, char after_char, double min, double max,
double* parsed_value) {
std::string substring;
ParseStringAfterChar(option, after_char, &substring);
bool sane_val = true;
double value;
if (false) {
// TODO: this doesn't seem to work on the emulator. b/15114595
std::stringstream iss(substring);
iss >> value;
// Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
sane_val = iss.eof() && (value >= min) && (value <= max);
} else {
char* end = nullptr;
value = strtod(substring.c_str(), &end);
sane_val = *end == '\0' && value >= min && value <= max;
}
if (!sane_val) {
Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
}
*parsed_value = value;
}
static constexpr size_t kMinDexFilesForSwap = 2;
static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
if (is_image) {
// Don't use swap, we know generation should succeed, and we don't want to slow it down.
return false;
}
if (dex_files.size() < kMinDexFilesForSwap) {
// If there are less dex files than the threshold, assume it's gonna be fine.
return false;
}
size_t dex_files_size = 0;
for (const auto* dex_file : dex_files) {
dex_files_size += dex_file->GetHeader().file_size_;
}
return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
}
class Dex2Oat FINAL {
public:
explicit Dex2Oat(TimingLogger* timings) :
compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
instruction_set_(kRuntimeISA),
// Take the default set of instruction features from the build.
verification_results_(nullptr),
method_inliner_map_(),
runtime_(nullptr),
thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
start_ns_(NanoTime()),
oat_fd_(-1),
zip_fd_(-1),
image_base_(0U),
image_classes_zip_filename_(nullptr),
image_classes_filename_(nullptr),
compiled_classes_zip_filename_(nullptr),
compiled_classes_filename_(nullptr),
compiled_methods_zip_filename_(nullptr),
compiled_methods_filename_(nullptr),
image_(false),
is_host_(false),
driver_(nullptr),
dump_stats_(false),
dump_passes_(false),
dump_timing_(false),
dump_slow_timing_(kIsDebugBuild),
swap_fd_(-1),
timings_(timings) {}
~Dex2Oat() {
// Free opened dex files before deleting the runtime_, because ~DexFile
// uses MemMap, which is shut down by ~Runtime.
class_path_files_.clear();
opened_dex_files_.clear();
// Log completion time before deleting the runtime_, because this accesses
// the runtime.
LogCompletionTime();
if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
delete runtime_; // See field declaration for why this is manual.
delete driver_;
delete verification_results_;
}
}
// Parse the arguments from the command line. In case of an unrecognized option or impossible
// values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
// returns, arguments have been successfully parsed.
void ParseArgs(int argc, char** argv) {
original_argc = argc;
original_argv = argv;
InitLogging(argv);
// Skip over argv[0].
argv++;
argc--;
if (argc == 0) {
Usage("No arguments specified");
}
std::string oat_symbols;
std::string boot_image_filename;
const char* compiler_filter_string = nullptr;
bool compile_pic = false;
int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
static constexpr int kUnsetInlineDepthLimit = -1;
int inline_depth_limit = kUnsetInlineDepthLimit;
static constexpr int kUnsetInlineMaxCodeUnits = -1;
int inline_max_code_units = kUnsetInlineMaxCodeUnits;
// Profile file to use
double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
bool debuggable = false;
bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
bool generate_debug_info = kIsDebugBuild;
bool watch_dog_enabled = true;
bool abort_on_hard_verifier_error = false;
bool requested_specific_compiler = false;
PassManagerOptions pass_manager_options;
std::string error_msg;
for (int i = 0; i < argc; i++) {
const StringPiece option(argv[i]);
const bool log_options = false;
if (log_options) {
LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
}
if (option.starts_with("--dex-file=")) {
dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
} else if (option.starts_with("--dex-location=")) {
dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
} else if (option.starts_with("--zip-fd=")) {
const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
if (!ParseInt(zip_fd_str, &zip_fd_)) {
Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
}
if (zip_fd_ < 0) {
Usage("--zip-fd passed a negative value %d", zip_fd_);
}
} else if (option.starts_with("--zip-location=")) {
zip_location_ = option.substr(strlen("--zip-location=")).data();
} else if (option.starts_with("--oat-file=")) {
oat_filename_ = option.substr(strlen("--oat-file=")).data();
} else if (option.starts_with("--oat-symbols=")) {
oat_symbols = option.substr(strlen("--oat-symbols=")).data();
} else if (option.starts_with("--oat-fd=")) {
const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
if (!ParseInt(oat_fd_str, &oat_fd_)) {
Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
}
if (oat_fd_ < 0) {
Usage("--oat-fd passed a negative value %d", oat_fd_);
}
} else if (option == "--watch-dog") {
watch_dog_enabled = true;
} else if (option == "--no-watch-dog") {
watch_dog_enabled = false;
} else if (option.starts_with("-j")) {
const char* thread_count_str = option.substr(strlen("-j")).data();
if (!ParseUint(thread_count_str, &thread_count_)) {
Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
}
} else if (option.starts_with("--oat-location=")) {
oat_location_ = option.substr(strlen("--oat-location=")).data();
} else if (option.starts_with("--image=")) {
image_filename_ = option.substr(strlen("--image=")).data();
} else if (option.starts_with("--image-classes=")) {
image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
} else if (option.starts_with("--image-classes-zip=")) {
image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
} else if (option.starts_with("--compiled-classes=")) {
compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
} else if (option.starts_with("--compiled-classes-zip=")) {
compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
} else if (option.starts_with("--compiled-methods=")) {
compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
} else if (option.starts_with("--compiled-methods-zip=")) {
compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
} else if (option.starts_with("--base=")) {
const char* image_base_str = option.substr(strlen("--base=")).data();
char* end;
image_base_ = strtoul(image_base_str, &end, 16);
if (end == image_base_str || *end != '\0') {
Usage("Failed to parse hexadecimal value for option %s", option.data());
}
} else if (option.starts_with("--boot-image=")) {
boot_image_filename = option.substr(strlen("--boot-image=")).data();
} else if (option.starts_with("--android-root=")) {
android_root_ = option.substr(strlen("--android-root=")).data();
} else if (option.starts_with("--instruction-set=")) {
StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
// StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
buf.get()[instruction_set_str.length()] = 0;
instruction_set_ = GetInstructionSetFromString(buf.get());
// arm actually means thumb2.
if (instruction_set_ == InstructionSet::kArm) {
instruction_set_ = InstructionSet::kThumb2;
}
} else if (option.starts_with("--instruction-set-variant=")) {
StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
instruction_set_features_.reset(
InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
if (instruction_set_features_.get() == nullptr) {
Usage("%s", error_msg.c_str());
}
} else if (option.starts_with("--instruction-set-features=")) {
StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
if (instruction_set_features_.get() == nullptr) {
instruction_set_features_.reset(
InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
if (instruction_set_features_.get() == nullptr) {
Usage("Problem initializing default instruction set features variant: %s",
error_msg.c_str());
}
}
instruction_set_features_.reset(
instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
if (instruction_set_features_.get() == nullptr) {
Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
}
} else if (option.starts_with("--compiler-backend=")) {
requested_specific_compiler = true;
StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
if (backend_str == "Quick") {
compiler_kind_ = Compiler::kQuick;
} else if (backend_str == "Optimizing") {
compiler_kind_ = Compiler::kOptimizing;
} else {
Usage("Unknown compiler backend: %s", backend_str.data());
}
} else if (option.starts_with("--compiler-filter=")) {
compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
} else if (option == "--compile-pic") {
compile_pic = true;
} else if (option.starts_with("--huge-method-max=")) {
const char* threshold = option.substr(strlen("--huge-method-max=")).data();
if (!ParseInt(threshold, &huge_method_threshold)) {
Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
}
if (huge_method_threshold < 0) {
Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
}
} else if (option.starts_with("--large-method-max=")) {
const char* threshold = option.substr(strlen("--large-method-max=")).data();
if (!ParseInt(threshold, &large_method_threshold)) {
Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
}
if (large_method_threshold < 0) {
Usage("--large-method-max passed a negative value %s", large_method_threshold);
}
} else if (option.starts_with("--small-method-max=")) {
const char* threshold = option.substr(strlen("--small-method-max=")).data();
if (!ParseInt(threshold, &small_method_threshold)) {
Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
}
if (small_method_threshold < 0) {
Usage("--small-method-max passed a negative value %s", small_method_threshold);
}
} else if (option.starts_with("--tiny-method-max=")) {
const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
if (!ParseInt(threshold, &tiny_method_threshold)) {
Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
}
if (tiny_method_threshold < 0) {
Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
}
} else if (option.starts_with("--num-dex-methods=")) {
const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
if (!ParseInt(threshold, &num_dex_methods_threshold)) {
Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
}
if (num_dex_methods_threshold < 0) {
Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
}
} else if (option.starts_with("--inline-depth-limit=")) {
const char* limit = option.substr(strlen("--inline-depth-limit=")).data();
if (!ParseInt(limit, &inline_depth_limit)) {
Usage("Failed to parse --inline-depth-limit '%s' as an integer", limit);
}
if (inline_depth_limit < 0) {
Usage("--inline-depth-limit passed a negative value %s", inline_depth_limit);
}
} else if (option.starts_with("--inline-max-code-units=")) {
const char* code_units = option.substr(strlen("--inline-max-code-units=")).data();
if (!ParseInt(code_units, &inline_max_code_units)) {
Usage("Failed to parse --inline-max-code-units '%s' as an integer", code_units);
}
if (inline_max_code_units < 0) {
Usage("--inline-max-code-units passed a negative value %s", inline_max_code_units);
}
} else if (option == "--host") {
is_host_ = true;
} else if (option == "--runtime-arg") {
if (++i >= argc) {
Usage("Missing required argument for --runtime-arg");
}
if (log_options) {
LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
}
runtime_args_.push_back(argv[i]);
} else if (option == "--dump-timing") {
dump_timing_ = true;
} else if (option == "--dump-passes") {
dump_passes_ = true;
} else if (option.starts_with("--dump-cfg=")) {
dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
} else if (option == "--dump-stats") {
dump_stats_ = true;
} else if (option == "--generate-debug-info" || option == "-g") {
generate_debug_info = true;
} else if (option == "--no-generate-debug-info") {
generate_debug_info = false;
} else if (option == "--debuggable") {
debuggable = true;
generate_debug_info = true;
} else if (option.starts_with("--profile-file=")) {
profile_file_ = option.substr(strlen("--profile-file=")).data();
VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
} else if (option == "--no-profile-file") {
// No profile
} else if (option.starts_with("--top-k-profile-threshold=")) {
ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
} else if (option == "--print-pass-names") {
pass_manager_options.SetPrintPassNames(true);
} else if (option.starts_with("--disable-passes=")) {
const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
pass_manager_options.SetDisablePassList(disable_passes);
} else if (option.starts_with("--print-passes=")) {
const std::string print_passes = option.substr(strlen("--print-passes=")).data();
pass_manager_options.SetPrintPassList(print_passes);
} else if (option == "--print-all-passes") {
pass_manager_options.SetPrintAllPasses();
} else if (option.starts_with("--dump-cfg-passes=")) {
const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
pass_manager_options.SetDumpPassList(dump_passes_string);
} else if (option == "--print-pass-options") {
pass_manager_options.SetPrintPassOptions(true);
} else if (option.starts_with("--pass-options=")) {
const std::string options = option.substr(strlen("--pass-options=")).data();
pass_manager_options.SetOverriddenPassOptions(options);
} else if (option == "--include-patch-information") {
include_patch_information = true;
} else if (option == "--no-include-patch-information") {
include_patch_information = false;
} else if (option.starts_with("--verbose-methods=")) {
// TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
// conditional on having verbost methods.
gLogVerbosity.compiler = false;
Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
} else if (option.starts_with("--dump-init-failures=")) {
std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
init_failure_output_.reset(new std::ofstream(file_name));
if (init_failure_output_.get() == nullptr) {
LOG(ERROR) << "Failed to allocate ofstream";
} else if (init_failure_output_->fail()) {
LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
<< "failures.";
init_failure_output_.reset();
}
} else if (option.starts_with("--swap-file=")) {
swap_file_name_ = option.substr(strlen("--swap-file=")).data();
} else if (option.starts_with("--swap-fd=")) {
const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
if (!ParseInt(swap_fd_str, &swap_fd_)) {
Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
}
if (swap_fd_ < 0) {
Usage("--swap-fd passed a negative value %d", swap_fd_);
}
} else if (option == "--abort-on-hard-verifier-error") {
abort_on_hard_verifier_error = true;
} else {
LOG(WARNING) << StringPrintf("Unknown argument %s", option.data());
}
}
// Override the number of compiler threads with optimal value (thru system property)
#ifdef HAVE_ANDROID_OS
const char* propertyName = "ro.sys.fw.dex2oat_thread_count";
char thread_count_str[PROPERTY_VALUE_MAX];
if (property_get(propertyName, thread_count_str, "") > 0) {
if (ParseUint(thread_count_str, &thread_count_)) {
LOG(INFO) << "Adjusted thread count (for runtime dex2oat): " << thread_count_ << ", " << thread_count_str;
}
}
#endif
image_ = (!image_filename_.empty());
if (!requested_specific_compiler && !kUseOptimizingCompiler) {
// If no specific compiler is requested, the current behavior is
// to compile the boot image with Quick, and the rest with Optimizing.
compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing;
}
if (compiler_kind_ == Compiler::kOptimizing) {
// Optimizing only supports PIC mode.
compile_pic = true;
}
if (oat_filename_.empty() && oat_fd_ == -1) {
Usage("Output must be supplied with either --oat-file or --oat-fd");
}
if (!oat_filename_.empty() && oat_fd_ != -1) {
Usage("--oat-file should not be used with --oat-fd");
}
if (!oat_symbols.empty() && oat_fd_ != -1) {
Usage("--oat-symbols should not be used with --oat-fd");
}
if (!oat_symbols.empty() && is_host_) {
Usage("--oat-symbols should not be used with --host");
}
if (oat_fd_ != -1 && !image_filename_.empty()) {
Usage("--oat-fd should not be used with --image");
}
if (android_root_.empty()) {
const char* android_root_env_var = getenv("ANDROID_ROOT");
if (android_root_env_var == nullptr) {
Usage("--android-root unspecified and ANDROID_ROOT not set");
}
android_root_ += android_root_env_var;
}
if (!image_ && boot_image_filename.empty()) {
boot_image_filename += android_root_;
boot_image_filename += "/framework/boot.art";
}
if (!boot_image_filename.empty()) {
boot_image_option_ += "-Ximage:";
boot_image_option_ += boot_image_filename;
}
if (image_classes_filename_ != nullptr && !image_) {
Usage("--image-classes should only be used with --image");
}
if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
Usage("--image-classes should not be used with --boot-image");
}
if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
Usage("--image-classes-zip should be used with --image-classes");
}
if (compiled_classes_filename_ != nullptr && !image_) {
Usage("--compiled-classes should only be used with --image");
}
if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
Usage("--compiled-classes should not be used with --boot-image");
}
if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
Usage("--compiled-classes-zip should be used with --compiled-classes");
}
if (dex_filenames_.empty() && zip_fd_ == -1) {
Usage("Input must be supplied with either --dex-file or --zip-fd");
}
if (!dex_filenames_.empty() && zip_fd_ != -1) {
Usage("--dex-file should not be used with --zip-fd");
}
if (!dex_filenames_.empty() && !zip_location_.empty()) {
Usage("--dex-file should not be used with --zip-location");
}
if (dex_locations_.empty()) {
for (const char* dex_file_name : dex_filenames_) {
dex_locations_.push_back(dex_file_name);
}
} else if (dex_locations_.size() != dex_filenames_.size()) {
Usage("--dex-location arguments do not match --dex-file arguments");
}
if (zip_fd_ != -1 && zip_location_.empty()) {
Usage("--zip-location should be supplied with --zip-fd");
}
if (boot_image_option_.empty()) {
if (image_base_ == 0) {
Usage("Non-zero --base not specified");
}
}
oat_stripped_ = oat_filename_;
if (!oat_symbols.empty()) {
oat_unstripped_ = oat_symbols;
} else {
oat_unstripped_ = oat_filename_;
}
// If no instruction set feature was given, use the default one for the target
// instruction set.
if (instruction_set_features_.get() == nullptr) {
instruction_set_features_.reset(
InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
if (instruction_set_features_.get() == nullptr) {
Usage("Problem initializing default instruction set features variant: %s",
error_msg.c_str());
}
}
if (instruction_set_ == kRuntimeISA) {
std::unique_ptr<const InstructionSetFeatures> runtime_features(
InstructionSetFeatures::FromCppDefines());
if (!instruction_set_features_->Equals(runtime_features.get())) {
LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
<< *instruction_set_features_ << ") and those of dex2oat executable ("
<< *runtime_features <<") for the command line:\n"
<< CommandLine();
}
}