forked from LineageOS/android_art
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathodrefresh.cc
1856 lines (1623 loc) · 73.2 KB
/
odrefresh.cc
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) 2020 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 "odrefresh.h"
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sysexits.h>
#include <time.h>
#include <unistd.h>
#include <algorithm>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <iosfwd>
#include <iostream>
#include <iterator>
#include <memory>
#include <optional>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "android-base/file.h"
#include "android-base/logging.h"
#include "android-base/macros.h"
#include "android-base/parseint.h"
#include "android-base/properties.h"
#include "android-base/result.h"
#include "android-base/scopeguard.h"
#include "android-base/stringprintf.h"
#include "android-base/strings.h"
#include "android/log.h"
#include "arch/instruction_set.h"
#include "base/file_utils.h"
#include "base/globals.h"
#include "base/macros.h"
#include "base/os.h"
#include "base/stl_util.h"
#include "base/string_view_cpp20.h"
#include "base/unix_file/fd_file.h"
#include "com_android_apex.h"
#include "com_android_art.h"
#include "dex/art_dex_file_loader.h"
#include "dexoptanalyzer.h"
#include "exec_utils.h"
#include "log/log.h"
#include "odr_artifacts.h"
#include "odr_common.h"
#include "odr_compilation_log.h"
#include "odr_config.h"
#include "odr_fs_utils.h"
#include "odr_metrics.h"
#include "odrefresh/odrefresh.h"
#include "palette/palette.h"
#include "palette/palette_types.h"
namespace art {
namespace odrefresh {
namespace apex = com::android::apex;
namespace art_apex = com::android::art;
using android::base::Result;
namespace {
// Name of cache info file in the ART Apex artifact cache.
constexpr const char* kCacheInfoFile = "cache-info.xml";
// Maximum execution time for odrefresh from start to end.
constexpr time_t kMaximumExecutionSeconds = 300;
// Maximum execution time for any child process spawned.
constexpr time_t kMaxChildProcessSeconds = 90;
constexpr mode_t kFileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
constexpr const char* kFirstBootImageBasename = "boot.art";
constexpr const char* kMinimalBootImageBasename = "boot_minimal.art";
void EraseFiles(const std::vector<std::unique_ptr<File>>& files) {
for (auto& file : files) {
file->Erase(/*unlink=*/true);
}
}
// Moves `files` to the directory `output_directory_path`.
//
// If any of the files cannot be moved, then all copies of the files are removed from both
// the original location and the output location.
//
// Returns true if all files are moved, false otherwise.
bool MoveOrEraseFiles(const std::vector<std::unique_ptr<File>>& files,
std::string_view output_directory_path) {
std::vector<std::unique_ptr<File>> output_files;
for (auto& file : files) {
const std::string file_basename(android::base::Basename(file->GetPath()));
const std::string output_file_path = Concatenate({output_directory_path, "/", file_basename});
const std::string input_file_path = file->GetPath();
output_files.emplace_back(OS::CreateEmptyFileWriteOnly(output_file_path.c_str()));
if (output_files.back() == nullptr) {
PLOG(ERROR) << "Failed to open " << QuotePath(output_file_path);
output_files.pop_back();
EraseFiles(output_files);
EraseFiles(files);
return false;
}
if (fchmod(output_files.back()->Fd(), kFileMode) != 0) {
PLOG(ERROR) << "Could not set file mode on " << QuotePath(output_file_path);
EraseFiles(output_files);
EraseFiles(files);
return false;
}
const size_t file_bytes = file->GetLength();
if (!output_files.back()->Copy(file.get(), /*offset=*/0, file_bytes)) {
PLOG(ERROR) << "Failed to copy " << QuotePath(file->GetPath()) << " to "
<< QuotePath(output_file_path);
EraseFiles(output_files);
EraseFiles(files);
return false;
}
if (!file->Erase(/*unlink=*/true)) {
PLOG(ERROR) << "Failed to erase " << QuotePath(file->GetPath());
EraseFiles(output_files);
EraseFiles(files);
return false;
}
if (output_files.back()->FlushCloseOrErase() != 0) {
PLOG(ERROR) << "Failed to flush and close file " << QuotePath(output_file_path);
EraseFiles(output_files);
EraseFiles(files);
return false;
}
}
return true;
}
// Gets the `ApexInfo` associated with the currently active ART APEX.
std::optional<apex::ApexInfo> GetArtApexInfo(const std::vector<apex::ApexInfo>& info_list) {
auto it = std::find_if(info_list.begin(), info_list.end(), [](const apex::ApexInfo& info) {
return info.getModuleName() == "com.android.art";
});
return it != info_list.end() ? std::make_optional(*it) : std::nullopt;
}
// Returns cache provenance information based on the current APEX version and filesystem
// information.
art_apex::ModuleInfo GenerateModuleInfo(const apex::ApexInfo& apex_info) {
// The lastUpdateMillis is an addition to ApexInfoList.xsd to support samegrade installs.
int64_t last_update_millis =
apex_info.hasLastUpdateMillis() ? apex_info.getLastUpdateMillis() : 0;
return art_apex::ModuleInfo{apex_info.getModuleName(),
apex_info.getVersionCode(),
apex_info.getVersionName(),
last_update_millis};
}
// Returns cache provenance information for all APEXes.
std::vector<art_apex::ModuleInfo> GenerateModuleInfoList(
const std::vector<apex::ApexInfo>& apex_info_list) {
std::vector<art_apex::ModuleInfo> module_info_list;
std::transform(apex_info_list.begin(),
apex_info_list.end(),
std::back_inserter(module_info_list),
GenerateModuleInfo);
return module_info_list;
}
// Returns a rewritten path based on ANDROID_ROOT if the path starts with "/system/".
std::string AndroidRootRewrite(const std::string& path) {
if (StartsWith(path, "/system/")) {
return Concatenate({GetAndroidRoot(), path.substr(7)});
} else {
return path;
}
}
template <typename T>
Result<void> CheckComponents(
const std::vector<T>& expected_components,
const std::vector<T>& actual_components,
const std::function<Result<void>(const T& expected, const T& actual)>& custom_checker =
[](const T&, const T&) -> Result<void> { return {}; }) {
if (expected_components.size() != actual_components.size()) {
return Errorf(
"Component count differs ({} != {})", expected_components.size(), actual_components.size());
}
for (size_t i = 0; i < expected_components.size(); ++i) {
const T& expected = expected_components[i];
const T& actual = actual_components[i];
if (expected.getFile() != actual.getFile()) {
return Errorf(
"Component {} file differs ('{}' != '{}')", i, expected.getFile(), actual.getFile());
}
if (expected.getSize() != actual.getSize()) {
return Errorf(
"Component {} size differs ({} != {})", i, expected.getSize(), actual.getSize());
}
if (expected.getChecksums() != actual.getChecksums()) {
return Errorf("Component {} checksums differ ('{}' != '{}')",
i,
expected.getChecksums(),
actual.getChecksums());
}
Result<void> result = custom_checker(expected, actual);
if (!result.ok()) {
return Errorf("Component {} {}", i, result.error().message());
}
}
return {};
}
Result<void> CheckSystemServerComponents(
const std::vector<art_apex::SystemServerComponent>& expected_components,
const std::vector<art_apex::SystemServerComponent>& actual_components) {
return CheckComponents<art_apex::SystemServerComponent>(
expected_components,
actual_components,
[](const art_apex::SystemServerComponent& expected,
const art_apex::SystemServerComponent& actual) -> Result<void> {
if (expected.getIsInClasspath() != actual.getIsInClasspath()) {
return Errorf("isInClasspath differs ({} != {})",
expected.getIsInClasspath(),
actual.getIsInClasspath());
}
return {};
});
}
template <typename T>
std::vector<T> GenerateComponents(
const std::vector<std::string>& jars,
const std::function<T(const std::string& path, uint64_t size, const std::string& checksum)>&
custom_generator) {
std::vector<T> components;
ArtDexFileLoader loader;
for (const std::string& path : jars) {
std::string actual_path = AndroidRootRewrite(path);
struct stat sb;
if (stat(actual_path.c_str(), &sb) == -1) {
PLOG(ERROR) << "Failed to stat component: " << QuotePath(actual_path);
return {};
}
std::vector<uint32_t> checksums;
std::vector<std::string> dex_locations;
std::string error_msg;
if (!loader.GetMultiDexChecksums(actual_path.c_str(), &checksums, &dex_locations, &error_msg)) {
LOG(ERROR) << "Failed to get multi-dex checksums: " << error_msg;
return {};
}
std::ostringstream oss;
for (size_t i = 0; i < checksums.size(); ++i) {
if (i != 0) {
oss << ';';
}
oss << android::base::StringPrintf("%08x", checksums[i]);
}
const std::string checksum = oss.str();
Result<T> component = custom_generator(path, static_cast<uint64_t>(sb.st_size), checksum);
if (!component.ok()) {
LOG(ERROR) << "Failed to generate component: " << component.error();
return {};
}
components.push_back(*std::move(component));
}
return components;
}
std::vector<art_apex::Component> GenerateComponents(const std::vector<std::string>& jars) {
return GenerateComponents<art_apex::Component>(
jars, [](const std::string& path, uint64_t size, const std::string& checksum) {
return art_apex::Component{path, size, checksum};
});
}
// Checks whether a group of artifacts exists. Returns true if all are present, false otherwise.
// If `checked_artifacts` is present, adds checked artifacts to `checked_artifacts`.
bool ArtifactsExist(const OdrArtifacts& artifacts,
bool check_art_file,
/*out*/ std::string* error_msg,
/*out*/ std::vector<std::string>* checked_artifacts = nullptr) {
std::vector<const char*> paths{artifacts.OatPath().c_str(), artifacts.VdexPath().c_str()};
if (check_art_file) {
paths.push_back(artifacts.ImagePath().c_str());
}
for (const char* path : paths) {
if (!OS::FileExists(path)) {
if (errno == EACCES) {
PLOG(ERROR) << "Failed to stat() " << path;
}
*error_msg = "Missing file: " + QuotePath(path);
return false;
}
}
// This should be done after checking all artifacts because either all of them are valid or none
// of them is valid.
if (checked_artifacts != nullptr) {
for (const char* path : paths) {
checked_artifacts->emplace_back(path);
}
}
return true;
}
void AddDex2OatCommonOptions(/*inout*/ std::vector<std::string>& args) {
args.emplace_back("--android-root=out/empty");
args.emplace_back("--abort-on-hard-verifier-error");
args.emplace_back("--no-abort-on-soft-verifier-error");
args.emplace_back("--compilation-reason=boot");
args.emplace_back("--image-format=lz4");
args.emplace_back("--force-determinism");
args.emplace_back("--resolve-startup-const-strings=true");
// Avoid storing dex2oat cmdline in oat header. We want to be sure that the compiled artifacts
// are identical regardless of where the compilation happened. But some of the cmdline flags tends
// to be unstable, e.g. those contains FD numbers. To avoid the problem, the whole cmdline is not
// added to the oat header.
args.emplace_back("--avoid-storing-invocation");
}
bool IsCpuSetSpecValid(const std::string& cpu_set) {
for (auto& str : android::base::Split(cpu_set, ",")) {
int id;
if (!android::base::ParseInt(str, &id, 0)) {
return false;
}
}
return true;
}
bool AddDex2OatConcurrencyArguments(/*inout*/ std::vector<std::string>& args) {
std::string threads = android::base::GetProperty("dalvik.vm.boot-dex2oat-threads", "");
if (!threads.empty()) {
args.push_back("-j" + threads);
}
std::string cpu_set = android::base::GetProperty("dalvik.vm.boot-dex2oat-cpu-set", "");
if (cpu_set.empty()) {
return true;
}
if (!IsCpuSetSpecValid(cpu_set)) {
LOG(ERROR) << "Invalid CPU set spec: " << cpu_set;
return false;
}
args.push_back("--cpu-set=" + cpu_set);
return true;
}
void AddDex2OatDebugInfo(/*inout*/ std::vector<std::string>& args) {
args.emplace_back("--generate-mini-debug-info");
args.emplace_back("--strip");
}
void AddDex2OatInstructionSet(/*inout*/ std::vector<std::string>& args, InstructionSet isa) {
const char* isa_str = GetInstructionSetString(isa);
args.emplace_back(Concatenate({"--instruction-set=", isa_str}));
}
void AddDex2OatProfileAndCompilerFilter(
/*inout*/ std::vector<std::string>& args,
/*inout*/ std::vector<std::unique_ptr<File>>& output_files,
const std::vector<std::string>& profile_paths) {
bool has_any_profile = false;
for (auto& path : profile_paths) {
std::unique_ptr<File> profile_file(OS::OpenFileForReading(path.c_str()));
if (profile_file && profile_file->IsOpened()) {
args.emplace_back(android::base::StringPrintf("--profile-file-fd=%d", profile_file->Fd()));
output_files.emplace_back(std::move(profile_file));
has_any_profile = true;
}
}
if (has_any_profile) {
args.emplace_back("--compiler-filter=speed-profile");
} else {
args.emplace_back("--compiler-filter=speed");
}
}
bool AddBootClasspathFds(/*inout*/ std::vector<std::string>& args,
/*inout*/ std::vector<std::unique_ptr<File>>& output_files,
const std::vector<std::string>& bcp_jars) {
std::vector<std::string> bcp_fds;
for (const std::string& jar : bcp_jars) {
// Special treatment for Compilation OS. JARs in staged APEX may not be visible to Android, and
// may only be visible in the VM where the staged APEX is mounted. On the contrary, JARs in
// /system is not available by path in the VM, and can only made available via (remote) FDs.
if (StartsWith(jar, "/apex/")) {
bcp_fds.emplace_back("-1");
} else {
std::string actual_path = AndroidRootRewrite(jar);
std::unique_ptr<File> jar_file(OS::OpenFileForReading(actual_path.c_str()));
if (!jar_file || !jar_file->IsValid()) {
LOG(ERROR) << "Failed to open a BCP jar " << actual_path;
return false;
}
bcp_fds.push_back(std::to_string(jar_file->Fd()));
output_files.push_back(std::move(jar_file));
}
}
args.emplace_back("--runtime-arg");
args.emplace_back(Concatenate({"-Xbootclasspathfds:", android::base::Join(bcp_fds, ':')}));
return true;
}
std::string GetBootImageComponentBasename(const std::string& jar_path, bool is_first_jar) {
if (is_first_jar) {
return kFirstBootImageBasename;
}
const std::string jar_name = android::base::Basename(jar_path);
return "boot-" + ReplaceFileExtension(jar_name, "art");
}
void AddCompiledBootClasspathFdsIfAny(
/*inout*/ std::vector<std::string>& args,
/*inout*/ std::vector<std::unique_ptr<File>>& output_files,
const std::vector<std::string>& bcp_jars,
const InstructionSet isa,
const std::string& artifact_dir) {
std::vector<std::string> bcp_image_fds;
std::vector<std::string> bcp_oat_fds;
std::vector<std::string> bcp_vdex_fds;
std::vector<std::unique_ptr<File>> opened_files;
bool added_any = false;
for (size_t i = 0; i < bcp_jars.size(); i++) {
const std::string& jar = bcp_jars[i];
std::string image_path =
artifact_dir + "/" + GetBootImageComponentBasename(jar, /*is_first_jar=*/i == 0);
image_path = GetSystemImageFilename(image_path.c_str(), isa);
std::unique_ptr<File> image_file(OS::OpenFileForReading(image_path.c_str()));
if (image_file && image_file->IsValid()) {
bcp_image_fds.push_back(std::to_string(image_file->Fd()));
opened_files.push_back(std::move(image_file));
added_any = true;
} else {
bcp_image_fds.push_back("-1");
}
std::string oat_path = ReplaceFileExtension(image_path, "oat");
std::unique_ptr<File> oat_file(OS::OpenFileForReading(oat_path.c_str()));
if (oat_file && oat_file->IsValid()) {
bcp_oat_fds.push_back(std::to_string(oat_file->Fd()));
opened_files.push_back(std::move(oat_file));
added_any = true;
} else {
bcp_oat_fds.push_back("-1");
}
std::string vdex_path = ReplaceFileExtension(image_path, "vdex");
std::unique_ptr<File> vdex_file(OS::OpenFileForReading(vdex_path.c_str()));
if (vdex_file && vdex_file->IsValid()) {
bcp_vdex_fds.push_back(std::to_string(vdex_file->Fd()));
opened_files.push_back(std::move(vdex_file));
added_any = true;
} else {
bcp_vdex_fds.push_back("-1");
}
}
// Add same amount of FDs as BCP JARs, or none.
if (added_any) {
std::move(opened_files.begin(), opened_files.end(), std::back_inserter(output_files));
args.emplace_back("--runtime-arg");
args.emplace_back(
Concatenate({"-Xbootclasspathimagefds:", android::base::Join(bcp_image_fds, ':')}));
args.emplace_back("--runtime-arg");
args.emplace_back(
Concatenate({"-Xbootclasspathoatfds:", android::base::Join(bcp_oat_fds, ':')}));
args.emplace_back("--runtime-arg");
args.emplace_back(
Concatenate({"-Xbootclasspathvdexfds:", android::base::Join(bcp_vdex_fds, ':')}));
}
}
std::string GetStagingLocation(const std::string& staging_dir, const std::string& path) {
return Concatenate({staging_dir, "/", android::base::Basename(path)});
}
WARN_UNUSED bool CheckCompilationSpace() {
// Check the available storage space against an arbitrary threshold because dex2oat does not
// report when it runs out of storage space and we do not want to completely fill
// the users data partition.
//
// We do not have a good way of pre-computing the required space for a compilation step, but
// typically observe no more than 48MiB as the largest total size of AOT artifacts for a single
// dex2oat invocation, which includes an image file, an executable file, and a verification data
// file.
static constexpr uint64_t kMinimumSpaceForCompilation = 48 * 1024 * 1024;
uint64_t bytes_available;
const std::string& art_apex_data_path = GetArtApexData();
if (!GetFreeSpace(art_apex_data_path, &bytes_available)) {
return false;
}
if (bytes_available < kMinimumSpaceForCompilation) {
LOG(WARNING) << "Low space for " << QuotePath(art_apex_data_path) << " (" << bytes_available
<< " bytes)";
return false;
}
return true;
}
std::string GetSystemBootImageDir() { return GetAndroidRoot() + "/framework"; }
} // namespace
OnDeviceRefresh::OnDeviceRefresh(const OdrConfig& config)
: OnDeviceRefresh(config,
Concatenate({config.GetArtifactDirectory(), "/", kCacheInfoFile}),
std::make_unique<ExecUtils>()) {}
OnDeviceRefresh::OnDeviceRefresh(const OdrConfig& config,
const std::string& cache_info_filename,
std::unique_ptr<ExecUtils> exec_utils)
: config_{config},
cache_info_filename_{cache_info_filename},
start_time_{time(nullptr)},
exec_utils_{std::move(exec_utils)} {
for (const std::string& jar : android::base::Split(config_.GetDex2oatBootClasspath(), ":")) {
// Updatable APEXes should not have DEX files in the DEX2OATBOOTCLASSPATH. At the time of
// writing i18n is a non-updatable APEX and so does appear in the DEX2OATBOOTCLASSPATH.
boot_classpath_compilable_jars_.emplace_back(jar);
}
all_systemserver_jars_ = android::base::Split(config_.GetSystemServerClasspath(), ":");
systemserver_classpath_jars_ = {all_systemserver_jars_.begin(), all_systemserver_jars_.end()};
boot_classpath_jars_ = android::base::Split(config_.GetBootClasspath(), ":");
std::string standalone_system_server_jars_str = config_.GetStandaloneSystemServerJars();
if (!standalone_system_server_jars_str.empty()) {
std::vector<std::string> standalone_systemserver_jars =
android::base::Split(standalone_system_server_jars_str, ":");
std::move(standalone_systemserver_jars.begin(),
standalone_systemserver_jars.end(),
std::back_inserter(all_systemserver_jars_));
}
}
time_t OnDeviceRefresh::GetExecutionTimeUsed() const { return time(nullptr) - start_time_; }
time_t OnDeviceRefresh::GetExecutionTimeRemaining() const {
return std::max(static_cast<time_t>(0),
kMaximumExecutionSeconds - GetExecutionTimeUsed());
}
time_t OnDeviceRefresh::GetSubprocessTimeout() const {
return std::min(GetExecutionTimeRemaining(), kMaxChildProcessSeconds);
}
std::optional<std::vector<apex::ApexInfo>> OnDeviceRefresh::GetApexInfoList() const {
std::optional<apex::ApexInfoList> info_list =
apex::readApexInfoList(config_.GetApexInfoListFile().c_str());
if (!info_list.has_value()) {
return std::nullopt;
}
// We are only interested in active APEXes that contain compilable JARs.
std::unordered_set<std::string_view> relevant_apexes;
relevant_apexes.reserve(info_list->getApexInfo().size());
for (const std::vector<std::string>* jar_list :
{&boot_classpath_compilable_jars_, &all_systemserver_jars_, &boot_classpath_jars_}) {
for (auto& jar : *jar_list) {
std::string_view apex = ApexNameFromLocation(jar);
if (!apex.empty()) {
relevant_apexes.insert(apex);
}
}
}
// The ART APEX is always relevant no matter it contains any compilable JAR or not, because it
// contains the runtime.
relevant_apexes.insert("com.android.art");
std::vector<apex::ApexInfo> filtered_info_list;
std::copy_if(info_list->getApexInfo().begin(),
info_list->getApexInfo().end(),
std::back_inserter(filtered_info_list),
[&](const apex::ApexInfo& info) {
return info.getIsActive() && relevant_apexes.count(info.getModuleName()) != 0;
});
return filtered_info_list;
}
std::optional<art_apex::CacheInfo> OnDeviceRefresh::ReadCacheInfo() const {
return art_apex::read(cache_info_filename_.c_str());
}
Result<void> OnDeviceRefresh::WriteCacheInfo() const {
if (OS::FileExists(cache_info_filename_.c_str())) {
if (unlink(cache_info_filename_.c_str()) != 0) {
return ErrnoErrorf("Failed to unlink() file {}", QuotePath(cache_info_filename_));
}
}
const std::string dir_name = android::base::Dirname(cache_info_filename_);
if (!EnsureDirectoryExists(dir_name)) {
return Errorf("Could not create directory {}", QuotePath(dir_name));
}
std::vector<art_apex::KeyValuePair> system_properties;
for (const auto& [key, value] : config_.GetSystemProperties()) {
system_properties.emplace_back(key, value);
}
std::optional<std::vector<apex::ApexInfo>> apex_info_list = GetApexInfoList();
if (!apex_info_list.has_value()) {
return Errorf("Could not update {}: no APEX info", QuotePath(cache_info_filename_));
}
std::optional<apex::ApexInfo> art_apex_info = GetArtApexInfo(apex_info_list.value());
if (!art_apex_info.has_value()) {
return Errorf("Could not update {}: no ART APEX info", QuotePath(cache_info_filename_));
}
art_apex::ModuleInfo art_module_info = GenerateModuleInfo(art_apex_info.value());
std::vector<art_apex::ModuleInfo> module_info_list =
GenerateModuleInfoList(apex_info_list.value());
std::optional<std::vector<art_apex::Component>> bcp_components =
GenerateBootClasspathComponents();
if (!bcp_components.has_value()) {
return Errorf("No boot classpath components.");
}
std::optional<std::vector<art_apex::Component>> bcp_compilable_components =
GenerateBootClasspathCompilableComponents();
if (!bcp_compilable_components.has_value()) {
return Errorf("No boot classpath compilable components.");
}
std::optional<std::vector<art_apex::SystemServerComponent>> system_server_components =
GenerateSystemServerComponents();
if (!system_server_components.has_value()) {
return Errorf("No system_server components.");
}
std::ofstream out(cache_info_filename_.c_str());
if (out.fail()) {
return Errorf("Cannot open {} for writing.", QuotePath(cache_info_filename_));
}
std::unique_ptr<art_apex::CacheInfo> info(new art_apex::CacheInfo(
{art_apex::KeyValuePairList(system_properties)},
{art_module_info},
{art_apex::ModuleInfoList(module_info_list)},
{art_apex::Classpath(bcp_components.value())},
{art_apex::Classpath(bcp_compilable_components.value())},
{art_apex::SystemServerComponents(system_server_components.value())},
config_.GetCompilationOsMode() ? std::make_optional(true) : std::nullopt));
art_apex::write(out, *info);
out.close();
if (out.fail()) {
return Errorf("Cannot write to {}", QuotePath(cache_info_filename_));
}
return {};
}
static void ReportNextBootAnimationProgress(uint32_t current_compilation,
uint32_t number_of_compilations) {
// We arbitrarily show progress until 90%, expecting that our compilations take a large chunk of
// boot time.
uint32_t value = (90 * current_compilation) / number_of_compilations;
android::base::SetProperty("service.bootanim.progress", std::to_string(value));
}
std::vector<art_apex::Component> OnDeviceRefresh::GenerateBootClasspathComponents() const {
return GenerateComponents(boot_classpath_jars_);
}
std::vector<art_apex::Component> OnDeviceRefresh::GenerateBootClasspathCompilableComponents()
const {
return GenerateComponents(boot_classpath_compilable_jars_);
}
std::vector<art_apex::SystemServerComponent> OnDeviceRefresh::GenerateSystemServerComponents()
const {
return GenerateComponents<art_apex::SystemServerComponent>(
all_systemserver_jars_,
[&](const std::string& path, uint64_t size, const std::string& checksum) {
bool isInClasspath = ContainsElement(systemserver_classpath_jars_, path);
return art_apex::SystemServerComponent{path, size, checksum, isInClasspath};
});
}
std::string OnDeviceRefresh::GetBootImage(bool on_system, bool minimal) const {
DCHECK(!on_system || !minimal);
const char* basename = minimal ? kMinimalBootImageBasename : kFirstBootImageBasename;
if (on_system) {
// Typically "/system/framework/boot.art".
return GetPrebuiltPrimaryBootImageDir() + "/" + basename;
} else {
// Typically "/data/misc/apexdata/com.android.art/dalvik-cache/boot.art".
return config_.GetArtifactDirectory() + "/" + basename;
}
}
std::string OnDeviceRefresh::GetBootImagePath(bool on_system,
bool minimal,
const InstructionSet isa) const {
// Typically "/data/misc/apexdata/com.android.art/dalvik-cache/<isa>/boot.art".
return GetSystemImageFilename(GetBootImage(on_system, minimal).c_str(), isa);
}
std::string OnDeviceRefresh::GetSystemBootImageExtension() const {
std::string art_root = GetArtRoot() + "/";
// Find the first boot extension jar.
auto it = std::find_if_not(
boot_classpath_compilable_jars_.begin(),
boot_classpath_compilable_jars_.end(),
[&](const std::string& jar) { return android::base::StartsWith(jar, art_root); });
CHECK(it != boot_classpath_compilable_jars_.end());
// Typically "/system/framework/boot-framework.art".
return GetSystemBootImageDir() + "/" + GetBootImageComponentBasename(*it, /*is_first_jar=*/false);
}
std::string OnDeviceRefresh::GetSystemBootImageExtensionPath(const InstructionSet isa) const {
// Typically "/system/framework/<isa>/boot-framework.art".
return GetSystemImageFilename(GetSystemBootImageExtension().c_str(), isa);
}
std::string OnDeviceRefresh::GetSystemServerImagePath(bool on_system,
const std::string& jar_path) const {
if (on_system) {
if (LocationIsOnApex(jar_path)) {
return GetSystemOdexFilenameForApex(jar_path, config_.GetSystemServerIsa());
}
const std::string jar_name = android::base::Basename(jar_path);
const std::string image_name = ReplaceFileExtension(jar_name, "art");
const char* isa_str = GetInstructionSetString(config_.GetSystemServerIsa());
// Typically "/system/framework/oat/<isa>/services.art".
return Concatenate({GetAndroidRoot(), "/framework/oat/", isa_str, "/", image_name});
} else {
// Typically
// "/data/misc/apexdata/.../dalvik-cache/<isa>/system@[email protected]@classes.art".
const std::string image = GetApexDataImage(jar_path.c_str());
return GetSystemImageFilename(image.c_str(), config_.GetSystemServerIsa());
}
}
WARN_UNUSED bool OnDeviceRefresh::RemoveArtifactsDirectory() const {
if (config_.GetDryRun()) {
LOG(INFO) << "Directory " << QuotePath(config_.GetArtifactDirectory())
<< " and contents would be removed (dry-run).";
return true;
}
return RemoveDirectory(config_.GetArtifactDirectory());
}
WARN_UNUSED bool OnDeviceRefresh::BootClasspathArtifactsExist(
bool on_system,
bool minimal,
const InstructionSet isa,
/*out*/ std::string* error_msg,
/*out*/ std::vector<std::string>* checked_artifacts) const {
std::string path = GetBootImagePath(on_system, minimal, isa);
OdrArtifacts artifacts = OdrArtifacts::ForBootImage(path);
if (!ArtifactsExist(artifacts, /*check_art_file=*/true, error_msg, checked_artifacts)) {
return false;
}
// There is a split between the primary boot image and the extension on /system, so they need to
// be checked separately. This does not apply to the boot image on /data.
if (on_system) {
std::string extension_path = GetSystemBootImageExtensionPath(isa);
OdrArtifacts extension_artifacts = OdrArtifacts::ForBootImage(extension_path);
if (!ArtifactsExist(
extension_artifacts, /*check_art_file=*/true, error_msg, checked_artifacts)) {
return false;
}
}
return true;
}
WARN_UNUSED bool OnDeviceRefresh::SystemServerArtifactsExist(
bool on_system,
/*out*/ std::string* error_msg,
/*out*/ std::set<std::string>* jars_missing_artifacts,
/*out*/ std::vector<std::string>* checked_artifacts) const {
for (const std::string& jar_path : all_systemserver_jars_) {
const std::string image_location = GetSystemServerImagePath(on_system, jar_path);
const OdrArtifacts artifacts = OdrArtifacts::ForSystemServer(image_location);
// .art files are optional and are not generated for all jars by the build system.
const bool check_art_file = !on_system;
std::string error_msg_tmp;
if (!ArtifactsExist(artifacts, check_art_file, &error_msg_tmp, checked_artifacts)) {
jars_missing_artifacts->insert(jar_path);
*error_msg = error_msg->empty() ? error_msg_tmp : *error_msg + "\n" + error_msg_tmp;
}
}
return jars_missing_artifacts->empty();
}
WARN_UNUSED bool OnDeviceRefresh::CheckSystemPropertiesAreDefault() const {
// We don't have to check properties that match `kCheckedSystemPropertyPrefixes` here because none
// of them is persistent. This only applies when `cache-info.xml` does not exist. When
// `cache-info.xml` exists, we call `CheckSystemPropertiesHaveNotChanged` instead.
DCHECK(std::none_of(std::begin(kCheckedSystemPropertyPrefixes),
std::end(kCheckedSystemPropertyPrefixes),
[](const char* prefix) { return StartsWith(prefix, "persist."); }));
const std::unordered_map<std::string, std::string>& system_properties =
config_.GetSystemProperties();
for (const SystemPropertyConfig& system_property_config : *kSystemProperties.get()) {
auto property = system_properties.find(system_property_config.name);
DCHECK(property != system_properties.end());
if (property->second != system_property_config.default_value) {
LOG(INFO) << "System property " << system_property_config.name << " has a non-default value ("
<< property->second << ").";
return false;
}
}
return true;
}
WARN_UNUSED bool OnDeviceRefresh::CheckSystemPropertiesHaveNotChanged(
const art_apex::CacheInfo& cache_info) const {
std::unordered_map<std::string, std::string> cached_system_properties;
std::unordered_set<std::string> checked_properties;
const art_apex::KeyValuePairList* list = cache_info.getFirstSystemProperties();
if (list == nullptr) {
// This should never happen. We have already checked the ART module version, and the cache
// info is generated by the latest version of the ART module if it exists.
LOG(ERROR) << "Missing system properties from cache-info.";
return false;
}
for (const art_apex::KeyValuePair& pair : list->getItem()) {
cached_system_properties[pair.getK()] = pair.getV();
checked_properties.insert(pair.getK());
}
const std::unordered_map<std::string, std::string>& system_properties =
config_.GetSystemProperties();
for (const auto& [key, value] : system_properties) {
checked_properties.insert(key);
}
for (const std::string& name : checked_properties) {
auto property_it = system_properties.find(name);
std::string property = property_it != system_properties.end() ? property_it->second : "";
std::string cached_property = cached_system_properties[name];
if (property != cached_property) {
LOG(INFO) << "System property " << name << " value changed (before: \"" << cached_property
<< "\", now: \"" << property << "\").";
return false;
}
}
return true;
}
WARN_UNUSED bool OnDeviceRefresh::BootClasspathArtifactsOnSystemUsable(
const apex::ApexInfo& art_apex_info) const {
if (!art_apex_info.getIsFactory()) {
return false;
}
LOG(INFO) << "Factory ART APEX mounted.";
if (!CheckSystemPropertiesAreDefault()) {
return false;
}
LOG(INFO) << "System properties are set to default values.";
return true;
}
WARN_UNUSED bool OnDeviceRefresh::SystemServerArtifactsOnSystemUsable(
const std::vector<apex::ApexInfo>& apex_info_list) const {
if (std::any_of(apex_info_list.begin(),
apex_info_list.end(),
[](const apex::ApexInfo& apex_info) { return !apex_info.getIsFactory(); })) {
return false;
}
LOG(INFO) << "Factory APEXes mounted.";
if (!CheckSystemPropertiesAreDefault()) {
return false;
}
LOG(INFO) << "System properties are set to default values.";
return true;
}
WARN_UNUSED bool OnDeviceRefresh::CheckBootClasspathArtifactsAreUpToDate(
OdrMetrics& metrics,
const InstructionSet isa,
const apex::ApexInfo& art_apex_info,
const std::optional<art_apex::CacheInfo>& cache_info,
/*out*/ std::vector<std::string>* checked_artifacts) const {
if (BootClasspathArtifactsOnSystemUsable(art_apex_info)) {
// We can use the artifacts on /system. Check if they exist.
std::string error_msg;
if (BootClasspathArtifactsExist(/*on_system=*/true, /*minimal=*/false, isa, &error_msg)) {
return true;
}
LOG(INFO) << "Incomplete boot classpath artifacts on /system. " << error_msg;
LOG(INFO) << "Checking cache.";
}
if (!cache_info.has_value()) {
// If the cache info file does not exist, it usually means on-device compilation has not been
// done before because the device was using the factory version of modules, or artifacts were
// cleared because an updated version was uninstalled. Set the trigger to be
// `kApexVersionMismatch` so that compilation will always be performed.
PLOG(INFO) << "No prior cache-info file: " << QuotePath(cache_info_filename_);
metrics.SetTrigger(OdrMetrics::Trigger::kApexVersionMismatch);
return false;
}
// Check whether the current cache ART module info differs from the current ART module info.
const art_apex::ModuleInfo* cached_art_info = cache_info->getFirstArtModuleInfo();
if (cached_art_info == nullptr) {
LOG(INFO) << "Missing ART APEX info from cache-info.";
metrics.SetTrigger(OdrMetrics::Trigger::kApexVersionMismatch);
return false;
}
if (cached_art_info->getVersionCode() != art_apex_info.getVersionCode()) {
LOG(INFO) << "ART APEX version code mismatch (" << cached_art_info->getVersionCode()
<< " != " << art_apex_info.getVersionCode() << ").";
metrics.SetTrigger(OdrMetrics::Trigger::kApexVersionMismatch);
return false;
}
if (cached_art_info->getVersionName() != art_apex_info.getVersionName()) {
LOG(INFO) << "ART APEX version name mismatch (" << cached_art_info->getVersionName()
<< " != " << art_apex_info.getVersionName() << ").";
metrics.SetTrigger(OdrMetrics::Trigger::kApexVersionMismatch);
return false;
}
// Check lastUpdateMillis for samegrade installs. If `cached_art_info` is missing the
// lastUpdateMillis field then it is not current with the schema used by this binary so treat
// it as a samegrade update. Otherwise check whether the lastUpdateMillis changed.
const int64_t cached_art_last_update_millis =
cached_art_info->hasLastUpdateMillis() ? cached_art_info->getLastUpdateMillis() : -1;
if (cached_art_last_update_millis != art_apex_info.getLastUpdateMillis()) {
LOG(INFO) << "ART APEX last update time mismatch (" << cached_art_last_update_millis
<< " != " << art_apex_info.getLastUpdateMillis() << ").";
metrics.SetTrigger(OdrMetrics::Trigger::kApexVersionMismatch);