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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
|
// Copyright (C) 2019 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.
package apex
import (
"encoding/json"
"fmt"
"path"
"path/filepath"
"runtime"
"slices"
"sort"
"strconv"
"strings"
"android/soong/aconfig"
"android/soong/android"
"android/soong/dexpreopt"
"android/soong/java"
"github.com/google/blueprint"
"github.com/google/blueprint/proptools"
)
var (
pctx = android.NewPackageContext("android/apex")
)
func init() {
pctx.Import("android/soong/aconfig")
pctx.Import("android/soong/android")
pctx.Import("android/soong/cc/config")
pctx.Import("android/soong/java")
pctx.HostBinToolVariable("apexer", "apexer")
pctx.HostBinToolVariable("apexer_with_DCLA_preprocessing", "apexer_with_DCLA_preprocessing")
// ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
// projects, and hence cannot build 'aapt2'. Use the SDK prebuilt instead.
hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
if !ctx.Config().FrameworksBaseDirExists(ctx) {
return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
} else {
return ctx.Config().HostToolPath(ctx, tool).String()
}
})
}
hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
pctx.HostBinToolVariable("avbtool", "avbtool")
pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
pctx.HostBinToolVariable("merge_zips", "merge_zips")
pctx.HostBinToolVariable("mke2fs", "mke2fs")
pctx.HostBinToolVariable("resize2fs", "resize2fs")
pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
pctx.HostBinToolVariable("soong_zip", "soong_zip")
pctx.HostBinToolVariable("zip2zip", "zip2zip")
pctx.HostBinToolVariable("zipalign", "zipalign")
pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
pctx.HostBinToolVariable("extract_apks", "extract_apks")
pctx.HostBinToolVariable("make_f2fs", "make_f2fs")
pctx.HostBinToolVariable("sload_f2fs", "sload_f2fs")
pctx.HostBinToolVariable("make_erofs", "mkfs.erofs")
pctx.HostBinToolVariable("apex_compression_tool", "apex_compression_tool")
pctx.HostBinToolVariable("dexdeps", "dexdeps")
pctx.HostBinToolVariable("apex_ls", "apex-ls")
pctx.HostBinToolVariable("apex_sepolicy_tests", "apex_sepolicy_tests")
pctx.HostBinToolVariable("deapexer", "deapexer")
pctx.HostBinToolVariable("debugfs_static", "debugfs_static")
pctx.HostBinToolVariable("fsck_erofs", "fsck.erofs")
pctx.SourcePathVariable("genNdkUsedbyApexPath", "build/soong/scripts/gen_ndk_usedby_apex.sh")
pctx.HostBinToolVariable("conv_linker_config", "conv_linker_config")
pctx.HostBinToolVariable("assemble_vintf", "assemble_vintf")
pctx.HostBinToolVariable("apex_elf_checker", "apex_elf_checker")
pctx.HostBinToolVariable("aconfig", "aconfig")
pctx.HostBinToolVariable("host_apex_verifier", "host_apex_verifier")
}
type createStorageStruct struct {
Output_file string
Desc string
File_type string
}
var createStorageInfo = []createStorageStruct{
{"package.map", "create_aconfig_package_map_file", "package_map"},
{"flag.map", "create_aconfig_flag_map_file", "flag_map"},
{"flag.val", "create_aconfig_flag_val_file", "flag_val"},
{"flag.info", "create_aconfig_flag_info_file", "flag_info"},
}
var (
apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
Command: `rm -f $out && ${jsonmodify} $in ` +
`-a provideNativeLibs ${provideNativeLibs} ` +
`-a requireNativeLibs ${requireNativeLibs} ` +
`-se version 0 ${default_version} ` +
`${opt} ` +
`-o $out`,
CommandDeps: []string{"${jsonmodify}"},
Description: "prepare ${out}",
}, "provideNativeLibs", "requireNativeLibs", "default_version", "opt")
stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
CommandDeps: []string{"${conv_apex_manifest}"},
Description: "strip ${in}=>${out}",
})
pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
CommandDeps: []string{"${conv_apex_manifest}"},
Description: "convert ${in}=>${out}",
})
// TODO(b/113233103): make sure that file_contexts is as expected, i.e., validate
// against the binary policy using sefcontext_compiler -p <policy>.
// TODO(b/114327326): automate the generation of file_contexts
apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
`(. ${out}.copy_commands) && ` +
`APEXER_TOOL_PATH=${tool_path} ` +
`${apexer} --force --manifest ${manifest} ` +
`--file_contexts ${file_contexts} ` +
`--canned_fs_config ${canned_fs_config} ` +
`--include_build_info ` +
`--payload_type image ` +
`--key ${key} ${opt_flags} ${image_dir} ${out} `,
CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
"${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
"${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
Rspfile: "${out}.copy_commands",
RspfileContent: "${copy_commands}",
Description: "APEX ${image_dir} => ${out}",
}, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key",
"opt_flags", "manifest")
DCLAApexRule = pctx.StaticRule("DCLAApexRule", blueprint.RuleParams{
Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
`(. ${out}.copy_commands) && ` +
`APEXER_TOOL_PATH=${tool_path} ` +
`${apexer_with_DCLA_preprocessing} ` +
`--apexer ${apexer} ` +
`--canned_fs_config ${canned_fs_config} ` +
`${image_dir} ` +
`${out} ` +
`-- ` +
`--include_build_info ` +
`--force ` +
`--payload_type image ` +
`--key ${key} ` +
`--file_contexts ${file_contexts} ` +
`--manifest ${manifest} ` +
`${opt_flags} `,
CommandDeps: []string{"${apexer_with_DCLA_preprocessing}", "${apexer}", "${avbtool}", "${e2fsdroid}",
"${merge_zips}", "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}",
"${sload_f2fs}", "${make_erofs}", "${soong_zip}", "${zipalign}", "${aapt2}",
"prebuilts/sdk/current/public/android.jar"},
Rspfile: "${out}.copy_commands",
RspfileContent: "${copy_commands}",
Description: "APEX ${image_dir} => ${out}",
}, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key",
"opt_flags", "manifest", "is_DCLA")
apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
blueprint.RuleParams{
Command: `${aapt2} convert --output-format proto $in -o $out`,
CommandDeps: []string{"${aapt2}"},
})
apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Command: `${zip2zip} -i $in -o $out.base ` +
`apex_payload.img:apex/${abi}.img ` +
`apex_build_info.pb:apex/${abi}.build_info.pb ` +
`apex_manifest.json:root/apex_manifest.json ` +
`apex_manifest.pb:root/apex_manifest.pb ` +
`AndroidManifest.xml:manifest/AndroidManifest.xml ` +
`assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
`${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
`${merge_zips} $out $out.base $out.config`,
CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Description: "app bundle",
}, "abi", "config")
diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
Command: `diff --unchanged-group-format='' \` +
`--changed-group-format='%<' \` +
`${image_content_file} ${allowed_files_file} || (` +
`echo "New unexpected files were added to ${apex_module_name}." ` +
` "To fix the build run following command:" && ` +
`echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
`exit 1); touch ${out}`,
Description: "Diff ${image_content_file} and ${allowed_files_file}",
}, "image_content_file", "allowed_files_file", "apex_module_name")
generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
CommandDeps: []string{"${genNdkUsedbyApexPath}"},
Description: "Generate symbol list used by Apex",
}, "image_dir", "readelf")
apexSepolicyTestsRule = pctx.StaticRule("apexSepolicyTestsRule", blueprint.RuleParams{
Command: `${apex_ls} -Z ${in} > ${out}.fc` +
` && ${apex_sepolicy_tests} -f ${out}.fc --partition ${partition_tag} && touch ${out}`,
CommandDeps: []string{"${apex_sepolicy_tests}", "${apex_ls}"},
Description: "run apex_sepolicy_tests",
}, "partition_tag")
apexLinkerconfigValidationRule = pctx.StaticRule("apexLinkerconfigValidationRule", blueprint.RuleParams{
Command: `${conv_linker_config} validate --type apex ${image_dir} && touch ${out}`,
CommandDeps: []string{"${conv_linker_config}"},
Description: "run apex_linkerconfig_validation",
}, "image_dir")
apexHostVerifierRule = pctx.StaticRule("apexHostVerifierRule", blueprint.RuleParams{
Command: `${host_apex_verifier} --deapexer=${deapexer} --debugfs=${debugfs_static} ` +
`--fsckerofs=${fsck_erofs} --apex=${in} --partition_tag=${partition_tag} && touch ${out}`,
CommandDeps: []string{"${host_apex_verifier}", "${deapexer}", "${debugfs_static}", "${fsck_erofs}"},
Description: "run host_apex_verifier",
}, "partition_tag")
assembleVintfRule = pctx.StaticRule("assembleVintfRule", blueprint.RuleParams{
Command: `rm -f $out && VINTF_IGNORE_TARGET_FCM_VERSION=true ${assemble_vintf} -i $in -o $out`,
CommandDeps: []string{"${assemble_vintf}"},
Description: "run assemble_vintf",
})
apexElfCheckerUnwantedRule = pctx.StaticRule("apexElfCheckerUnwantedRule", blueprint.RuleParams{
Command: `${apex_elf_checker} --tool_path ${tool_path} --unwanted ${unwanted} ${in} && touch ${out}`,
CommandDeps: []string{"${apex_elf_checker}", "${deapexer}", "${debugfs_static}", "${fsck_erofs}", "${config.ClangBin}/llvm-readelf"},
Description: "run apex_elf_checker --unwanted",
}, "tool_path", "unwanted")
)
func (a *apexBundle) buildAconfigFiles(ctx android.ModuleContext) []apexFile {
var aconfigFiles android.Paths
for _, file := range a.filesInfo {
if file.module == nil {
continue
}
if dep, ok := android.OtherModuleProvider(ctx, file.module, android.AconfigPropagatingProviderKey); ok {
if len(dep.AconfigFiles) > 0 && dep.AconfigFiles[ctx.ModuleName()] != nil {
aconfigFiles = append(aconfigFiles, dep.AconfigFiles[ctx.ModuleName()]...)
}
}
validationFlag := ctx.DeviceConfig().AconfigContainerValidation()
if validationFlag == "error" || validationFlag == "warning" {
android.VerifyAconfigBuildMode(ctx, ctx.ModuleName(), file.module, validationFlag == "error")
}
}
aconfigFiles = android.FirstUniquePaths(aconfigFiles)
var files []apexFile
if len(aconfigFiles) > 0 {
apexAconfigFile := android.PathForModuleOut(ctx, "aconfig_flags.pb")
ctx.Build(pctx, android.BuildParams{
Rule: aconfig.AllDeclarationsRule,
Inputs: aconfigFiles,
Output: apexAconfigFile,
Description: "combine_aconfig_declarations",
Args: map[string]string{
"cache_files": android.JoinPathsWithPrefix(aconfigFiles, "--cache "),
},
})
files = append(files, newApexFile(ctx, apexAconfigFile, "aconfig_flags", "etc", etc, nil))
// To enable fingerprint, we need to have v2 storage files. The default version is 1.
storageFilesVersion := 1
if ctx.Config().ReleaseFingerprintAconfigPackages() {
storageFilesVersion = 2
}
for _, info := range createStorageInfo {
outputFile := android.PathForModuleOut(ctx, info.Output_file)
ctx.Build(pctx, android.BuildParams{
Rule: aconfig.CreateStorageRule,
Inputs: aconfigFiles,
Output: outputFile,
Description: info.Desc,
Args: map[string]string{
"container": ctx.ModuleName(),
"file_type": info.File_type,
"cache_files": android.JoinPathsWithPrefix(aconfigFiles, "--cache "),
"version": strconv.Itoa(storageFilesVersion),
},
})
files = append(files, newApexFile(ctx, outputFile, info.File_type, "etc", etc, nil))
}
}
return files
}
// buildManifest creates buile rules to modify the input apex_manifest.json to add information
// gathered by the build system such as provided/required native libraries. Two output files having
// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
// a.manifest.PbOut is protobuf format for R+ devices.
// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
// Put dependency({provide|require}NativeLibs) in apex_manifest.json
provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
// VNDK APEX name is determined at runtime, so update "name" in apex_manifest
optCommands := []string{}
if a.vndkApex {
apexName := vndkApexNamePrefix + a.vndkVersion()
optCommands = append(optCommands, "-v name "+apexName)
}
// Collect jniLibs. Notice that a.filesInfo is already sorted
var jniLibs []string
for _, fi := range a.filesInfo {
if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
jniLibs = append(jniLibs, fi.stem())
}
}
if len(jniLibs) > 0 {
optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
}
if android.InList(":vndk", requireNativeLibs) {
if _, vndkVersion := a.getImageVariationPair(); vndkVersion != "" {
optCommands = append(optCommands, "-v vndkVersion "+vndkVersion)
}
}
manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
defaultVersion := ctx.Config().ReleaseDefaultUpdatableModuleVersion()
if a.properties.Variant_version != nil {
defaultVersionInt, err := strconv.Atoi(defaultVersion)
if err != nil {
ctx.ModuleErrorf("expected RELEASE_DEFAULT_UPDATABLE_MODULE_VERSION to be an int, but got %s", defaultVersion)
}
if defaultVersionInt%10 != 0 && defaultVersionInt%10 != 9 {
ctx.ModuleErrorf("expected RELEASE_DEFAULT_UPDATABLE_MODULE_VERSION to end in a zero or a nine, but got %s", defaultVersion)
}
variantVersion := []rune(*a.properties.Variant_version)
if len(variantVersion) != 1 || variantVersion[0] < '0' || variantVersion[0] > '9' {
ctx.PropertyErrorf("variant_version", "expected an integer between 0-9; got %s", *a.properties.Variant_version)
}
defaultVersionRunes := []rune(defaultVersion)
defaultVersionRunes[len(defaultVersion)-1] = []rune(variantVersion)[0]
defaultVersion = string(defaultVersionRunes)
}
if override := ctx.Config().Getenv("OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION"); override != "" {
defaultVersion = override
}
ctx.Build(pctx, android.BuildParams{
Rule: apexManifestRule,
Input: src,
Output: manifestJsonFullOut,
Args: map[string]string{
"provideNativeLibs": strings.Join(provideNativeLibs, " "),
"requireNativeLibs": strings.Join(requireNativeLibs, " "),
"default_version": defaultVersion,
"opt": strings.Join(optCommands, " "),
},
})
// b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
// stripped-down version so that APEX modules built from R+ can be installed to Q
minSdkVersion := a.minSdkVersion(ctx)
if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
ctx.Build(pctx, android.BuildParams{
Rule: stripApexManifestRule,
Input: manifestJsonFullOut,
Output: a.manifestJsonOut,
})
}
// From R+, protobuf binary format (.pb) is the standard format for apex_manifest
a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
ctx.Build(pctx, android.BuildParams{
Rule: pbApexManifestRule,
Input: manifestJsonFullOut,
Output: a.manifestPbOut,
})
}
// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
// labeled as system_file or vendor_apex_metadata_file.
func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.Path {
var fileContexts android.Path
var fileContextsDir string
isFileContextsModule := false
if a.properties.File_contexts == nil {
fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
} else {
if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
isFileContextsModule = true
otherModule := android.GetModuleProxyFromPathDep(ctx, m, t)
if otherModule != nil {
fileContextsDir = ctx.OtherModuleDir(*otherModule)
}
}
fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
}
if fileContextsDir == "" {
fileContextsDir = filepath.Dir(fileContexts.String())
}
fileContextsDir += string(filepath.Separator)
if a.Platform() {
if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
}
}
if !isFileContextsModule && !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
}
output := android.PathForModuleOut(ctx, "file_contexts")
rule := android.NewRuleBuilder(pctx, ctx)
labelForRoot := "u:object_r:system_file:s0"
labelForManifest := "u:object_r:system_file:s0"
if a.SocSpecific() && !a.vndkApex {
// APEX on /vendor should label ./ and ./apex_manifest.pb as vendor file.
labelForRoot = "u:object_r:vendor_file:s0"
labelForManifest = "u:object_r:vendor_apex_metadata_file:s0"
}
// remove old file
rule.Command().Text("rm").FlagWithOutput("-f ", output)
// copy file_contexts
rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
// new line
rule.Command().Text("echo").Text(">>").Output(output)
// force-label /apex_manifest.pb and /
rule.Command().Text("echo").Text("/apex_manifest\\\\.pb").Text(labelForManifest).Text(">>").Output(output)
rule.Command().Text("echo").Text("/").Text(labelForRoot).Text(">>").Output(output)
rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
return output
}
// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
// files included in this APEX is shown. The text file is dist'ed so that people can see what's
// included in the APEX without actually downloading and extracting it.
func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.Path {
output := android.PathForModuleOut(ctx, "installed-files.txt")
rule := android.NewRuleBuilder(pctx, ctx)
rule.Command().
Implicit(builtApex).
Text("(cd " + imageDir.String() + " ; ").
Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Text(" | sort -nr > ").
Output(output)
rule.Build("installed-files."+a.Name(), "Installed files")
return output
}
// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
// creation process.
func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.Path {
output := android.PathForModuleOut(ctx, "bundle_config.json")
type ApkConfig struct {
Package_name string `json:"package_name"`
Apk_path string `json:"path"`
}
config := struct {
Compression struct {
Uncompressed_glob []string `json:"uncompressed_glob"`
} `json:"compression"`
Apex_config struct {
Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
} `json:"apex_config,omitempty"`
}{}
config.Compression.Uncompressed_glob = []string{
"apex_payload.img",
"apex_manifest.*",
}
// Collect the manifest names and paths of android apps if their manifest names are
// overridden.
for _, fi := range a.filesInfo {
if fi.class != app && fi.class != appSet {
continue
}
packageName := fi.overriddenPackageName
if packageName != "" {
config.Apex_config.Apex_embedded_apk_config = append(
config.Apex_config.Apex_embedded_apk_config,
ApkConfig{
Package_name: packageName,
Apk_path: fi.path(),
})
}
}
j, err := json.Marshal(config)
if err != nil {
panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
}
android.WriteFileRule(ctx, output, string(j))
return output
}
func markManifestTestOnly(ctx android.ModuleContext, androidManifestFile android.Path) android.Path {
return java.ManifestFixer(ctx, androidManifestFile, java.ManifestFixerParams{
TestOnly: true,
})
}
func shouldApplyAssembleVintf(fi apexFile) bool {
isVintfFragment, _ := path.Match("etc/vintf/*", fi.path())
_, fromVintfFragmentModule := fi.module.(*android.VintfFragmentModule)
return isVintfFragment && !fromVintfFragmentModule
}
func runAssembleVintf(ctx android.ModuleContext, vintfFragment android.Path) android.Path {
processed := android.PathForModuleOut(ctx, "vintf", vintfFragment.Base())
ctx.Build(pctx, android.BuildParams{
Rule: assembleVintfRule,
Input: vintfFragment,
Output: processed,
Description: "run assemble_vintf for VINTF in APEX",
})
return processed
}
// installApexSystemServerFiles installs dexpreopt and dexjar files for system server classpath entries
// provided by the apex. They are installed here instead of in library module because there may be multiple
// variants of the library, generally one for the "main" apex and another with a different min_sdk_version
// for the Android Go version of the apex. Both variants would attempt to install to the same locations,
// and the library variants cannot determine which one should. The apex module is better equipped to determine
// if it is "selected".
// This assumes that the jars produced by different min_sdk_version values are identical, which is currently
// true but may not be true if the min_sdk_version difference between the variants spans version that changed
// the dex format.
func (a *apexBundle) installApexSystemServerFiles(ctx android.ModuleContext) {
// If performInstalls is set this module is responsible for creating the install rules.
performInstalls := a.GetOverriddenBy() == "" && !a.testApex && a.installable()
// TODO(b/234351700): Remove once ART does not have separated debug APEX, or make the selection
// explicit in the ART Android.bp files.
if ctx.Config().UseDebugArt() {
if ctx.ModuleName() == "com.android.art" {
performInstalls = false
}
} else {
if ctx.ModuleName() == "com.android.art.debug" {
performInstalls = false
}
}
psi := android.PrebuiltSelectionInfoMap{}
ctx.VisitDirectDeps(func(am android.Module) {
if info, exists := android.OtherModuleProvider(ctx, am, android.PrebuiltSelectionInfoProvider); exists {
psi = info
}
})
if len(psi.GetSelectedModulesForApiDomain(ctx.ModuleName())) > 0 {
performInstalls = false
}
for _, fi := range a.filesInfo {
for _, install := range fi.systemServerDexpreoptInstalls {
var installedFile android.InstallPath
if performInstalls {
installedFile = ctx.InstallFile(install.InstallDirOnDevice, install.InstallFileOnDevice, install.OutputPathOnHost)
} else {
// Another module created the install rules, but this module should still depend on
// the installed locations.
installedFile = install.InstallDirOnDevice.Join(ctx, install.InstallFileOnDevice)
}
a.extraInstalledFiles = append(a.extraInstalledFiles, installedFile)
a.extraInstalledPairs = append(a.extraInstalledPairs, installPair{install.OutputPathOnHost, installedFile})
ctx.PackageFile(install.InstallDirOnDevice, install.InstallFileOnDevice, install.OutputPathOnHost)
}
if performInstalls {
for _, dexJar := range fi.systemServerDexJars {
// Copy the system server dex jar to a predefined location where dex2oat will find it.
android.CopyFileRule(ctx, dexJar,
android.PathForOutput(ctx, dexpreopt.SystemServerDexjarsDir, dexJar.Base()))
}
}
}
}
// buildApex creates build rules to build an APEX using apexer.
func (a *apexBundle) buildApex(ctx android.ModuleContext) {
suffix := imageApexSuffix
apexName := a.BaseModuleName()
////////////////////////////////////////////////////////////////////////////////////////////
// Step 1: copy built files to appropriate directories under the image directory
imageDir := android.PathForModuleOut(ctx, "image"+suffix)
installSymbolFiles := a.ExportedToMake() && a.installable()
// set of dependency module:location mappings
installMapSet := make(map[string]bool)
// TODO(jiyong): use the RuleBuilder
var copyCommands []string
var implicitInputs []android.Path
apexDir := android.PathForModuleInPartitionInstall(ctx, "apex", apexName)
for _, fi := range a.filesInfo {
destPath := imageDir.Join(ctx, fi.path()).String()
// Prepare the destination path
destPathDir := filepath.Dir(destPath)
if fi.class == appSet {
copyCommands = append(copyCommands, "rm -rf "+destPathDir)
}
copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
installMapPath := fi.builtFile
// Copy the built file to the directory. But if the symlink optimization is turned
// on, place a symlink to the corresponding file in /system partition instead.
if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
pathOnDevice := filepath.Join("/", fi.partition, fi.path())
copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
} else {
// Copy the file into APEX
if !a.testApex && shouldApplyAssembleVintf(fi) {
// copy the output of assemble_vintf instead of the original
vintfFragment := runAssembleVintf(ctx, fi.builtFile)
copyCommands = append(copyCommands, "cp -f "+vintfFragment.String()+" "+destPath)
implicitInputs = append(implicitInputs, vintfFragment)
} else {
copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
implicitInputs = append(implicitInputs, fi.builtFile)
}
var installedPath android.InstallPath
if fi.class == appSet {
// In case of AppSet, we need to copy additional APKs as well. They
// are zipped. So we need to unzip them.
copyCommands = append(copyCommands,
fmt.Sprintf("unzip -qDD -d %s %s", destPathDir,
fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs().String()))
if installSymbolFiles {
installedPath = ctx.InstallFileWithExtraFilesZip(apexDir.Join(ctx, fi.installDir),
fi.stem(), fi.builtFile, fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs())
}
} else {
if installSymbolFiles {
// store installedPath. symlinks might be created if required.
installedPath = ctx.InstallFile(apexDir.Join(ctx, fi.installDir), fi.stem(), fi.builtFile)
}
}
// Create additional symlinks pointing the file inside the APEX (if any). Note that
// this is independent from the symlink optimization.
for _, symlinkPath := range fi.symlinkPaths() {
symlinkDest := imageDir.Join(ctx, symlinkPath).String()
copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
if installSymbolFiles {
ctx.InstallSymlink(apexDir.Join(ctx, filepath.Dir(symlinkPath)), filepath.Base(symlinkPath), installedPath)
}
}
installMapPath = installedPath
}
// Copy the test files (if any)
for _, d := range fi.dataPaths {
// TODO(eakammer): This is now the third repetition of ~this logic for test paths, refactoring should be possible
relPath := d.ToRelativeInstallPath()
dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath)).String()
copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
implicitInputs = append(implicitInputs, d.SrcPath)
}
installMapSet[installMapPath.String()+":"+fi.installDir+"/"+fi.builtFile.Base()] = true
}
implicitInputs = append(implicitInputs, a.manifestPbOut)
if len(installMapSet) > 0 {
var installs []string
installs = append(installs, android.SortedKeys(installMapSet)...)
ctx.SetLicenseInstallMap(installs)
}
////////////////////////////////////////////////////////////////////////////////////////////
// Step 1.a: Write the list of files in this APEX to a txt file and compare it against
// the allowed list given via the allowed_files property. Build fails when the two lists
// differ.
//
// TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
// to be using this at this moment. Furthermore, this looks very similar to what
// buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
// hurt readability.
if a.overridableProperties.Allowed_files != nil {
// Build content.txt
var contentLines []string
imageContentFile := android.PathForModuleOut(ctx, "content.txt")
contentLines = append(contentLines, "./apex_manifest.pb")
minSdkVersion := a.minSdkVersion(ctx)
if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
contentLines = append(contentLines, "./apex_manifest.json")
}
for _, fi := range a.filesInfo {
contentLines = append(contentLines, "./"+fi.path())
}
sort.Strings(contentLines)
android.WriteFileRule(ctx, imageContentFile, strings.Join(contentLines, "\n"))
implicitInputs = append(implicitInputs, imageContentFile)
// Compare content.txt against allowed_files.
allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
ctx.Build(pctx, android.BuildParams{
Rule: diffApexContentRule,
Implicits: implicitInputs,
Output: phonyOutput,
Description: "diff apex image content",
Args: map[string]string{
"allowed_files_file": allowedFilesFile.String(),
"image_content_file": imageContentFile.String(),
"apex_module_name": a.Name(),
},
})
implicitInputs = append(implicitInputs, phonyOutput)
}
unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
outHostBinDir := ctx.Config().HostToolPath(ctx, "").String()
prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
////////////////////////////////////////////////////////////////////////////////////
// Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
// in this APEX. The file will be used by apexer in later steps.
cannedFsConfig := a.buildCannedFsConfig(ctx)
implicitInputs = append(implicitInputs, cannedFsConfig)
////////////////////////////////////////////////////////////////////////////////////
// Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
// TODO(jiyong): use the RuleBuilder
optFlags := []string{}
fileContexts := a.buildFileContexts(ctx)
implicitInputs = append(implicitInputs, fileContexts)
implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
manifestPackageName := a.getOverrideManifestPackageName(ctx)
if manifestPackageName != "" {
optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
}
androidManifest := a.properties.AndroidManifest.GetOrDefault(ctx, "")
if androidManifest != "" {
androidManifestFile := android.PathForModuleSrc(ctx, androidManifest)
if a.testApex {
androidManifestFile = markManifestTestOnly(ctx, androidManifestFile)
}
implicitInputs = append(implicitInputs, androidManifestFile)
optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
} else if a.testApex {
optFlags = append(optFlags, "--test_only")
}
// Determine target/min sdk version from the context
// TODO(jiyong): make this as a function
moduleMinSdkVersion := a.minSdkVersion(ctx)
minSdkVersion := moduleMinSdkVersion.String()
// bundletool doesn't understand what "current" is. We need to transform it to
// codename
if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
if useApiFingerprint, fingerprintMinSdkVersion, fingerprintDeps :=
java.UseApiFingerprint(ctx); useApiFingerprint {
minSdkVersion = fingerprintMinSdkVersion
implicitInputs = append(implicitInputs, fingerprintDeps)
}
}
// apex module doesn't have a concept of target_sdk_version, hence for the time
// being targetSdkVersion == default targetSdkVersion of the branch.
targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
if useApiFingerprint, fingerprintTargetSdkVersion, fingerprintDeps :=
java.UseApiFingerprint(ctx); useApiFingerprint {
targetSdkVersion = fingerprintTargetSdkVersion
implicitInputs = append(implicitInputs, fingerprintDeps)
}
optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
if a.overridableProperties.Logging_parent != "" {
optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
}
// Create a NOTICE file, and embed it as an asset file in the APEX.
htmlGzNotice := android.PathForModuleOut(ctx, "NOTICE.html.gz")
android.BuildNoticeHtmlOutputFromLicenseMetadata(
ctx, htmlGzNotice, "", "",
[]string{
android.PathForModuleInstall(ctx).String() + "/",
android.PathForModuleInPartitionInstall(ctx, "apex").String() + "/",
})
noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
builder := android.NewRuleBuilder(pctx, ctx)
builder.Command().Text("cp").
Input(htmlGzNotice).
Output(noticeAssetPath)
builder.Build("notice_dir", "Building notice dir")
implicitInputs = append(implicitInputs, noticeAssetPath)
optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeAssetPath.String()))
if a.testOnlyShouldSkipPayloadSign() {
optFlags = append(optFlags, "--unsigned_payload")
}
if moduleMinSdkVersion == android.SdkVersion_Android10 {
implicitInputs = append(implicitInputs, a.manifestJsonOut)
optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
}
optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
if a.dynamic_common_lib_apex() {
ctx.Build(pctx, android.BuildParams{
Rule: DCLAApexRule,
Implicits: implicitInputs,
Output: unsignedOutputFile,
Description: "apex",
Args: map[string]string{
"tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
"image_dir": imageDir.String(),
"copy_commands": strings.Join(copyCommands, " && "),
"manifest": a.manifestPbOut.String(),
"file_contexts": fileContexts.String(),
"canned_fs_config": cannedFsConfig.String(),
"key": a.privateKeyFile.String(),
"opt_flags": strings.Join(optFlags, " "),
},
})
} else {
ctx.Build(pctx, android.BuildParams{
Rule: apexRule,
Implicits: implicitInputs,
Output: unsignedOutputFile,
Description: "apex",
Args: map[string]string{
"tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
"image_dir": imageDir.String(),
"copy_commands": strings.Join(copyCommands, " && "),
"manifest": a.manifestPbOut.String(),
"file_contexts": fileContexts.String(),
"canned_fs_config": cannedFsConfig.String(),
"key": a.privateKeyFile.String(),
"opt_flags": strings.Join(optFlags, " "),
},
})
}
// TODO(jiyong): make the two rules below as separate functions
apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
a.bundleModuleFile = bundleModuleFile
ctx.Build(pctx, android.BuildParams{
Rule: apexProtoConvertRule,
Input: unsignedOutputFile,
Output: apexProtoFile,
Description: "apex proto convert",
})
implicitInputs = append(implicitInputs, unsignedOutputFile)
// Run coverage analysis
apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
ctx.Build(pctx, android.BuildParams{
Rule: generateAPIsUsedbyApexRule,
Implicits: implicitInputs,
Description: "coverage",
Output: apisUsedbyOutputFile,
Args: map[string]string{
"image_dir": imageDir.String(),
"readelf": "${config.ClangBin}/llvm-readelf",
},
})
a.nativeApisUsedByModuleFile = apisUsedbyOutputFile
var nativeLibNames []string
for _, f := range a.filesInfo {
if f.class == nativeSharedLib {
nativeLibNames = append(nativeLibNames, f.stem())
}
}
apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
rb := android.NewRuleBuilder(pctx, ctx)
rb.Command().
Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
Output(apisBackedbyOutputFile).
Flags(nativeLibNames)
rb.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
a.nativeApisBackedByModuleFile = apisBackedbyOutputFile
var javaLibOrApkPath []android.Path
for _, f := range a.filesInfo {
if f.class == javaSharedLib || f.class == app {
javaLibOrApkPath = append(javaLibOrApkPath, f.builtFile)
}
}
javaApiUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.xml")
javaUsedByRule := android.NewRuleBuilder(pctx, ctx)
javaUsedByRule.Command().
Tool(android.PathForSource(ctx, "build/soong/scripts/gen_java_usedby_apex.sh")).
BuiltTool("dexdeps").
Output(javaApiUsedbyOutputFile).
Inputs(javaLibOrApkPath)
javaUsedByRule.Build("java_usedby_list", "Generate Java APIs used by Apex")
a.javaApisUsedByModuleFile = javaApiUsedbyOutputFile
bundleConfig := a.buildBundleConfig(ctx)
var abis []string
for _, target := range ctx.MultiTargets() {
if len(target.Arch.Abi) > 0 {
abis = append(abis, target.Arch.Abi[0])
}
}
abis = android.FirstUniqueStrings(abis)
ctx.Build(pctx, android.BuildParams{
Rule: apexBundleRule,
Input: apexProtoFile,
Implicit: bundleConfig,
Output: a.bundleModuleFile,
Description: "apex bundle module",
Args: map[string]string{
"abi": strings.Join(abis, "."),
"config": bundleConfig.String(),
},
})
////////////////////////////////////////////////////////////////////////////////////
// Step 4: Sign the APEX using signapk
signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
pem, key := a.getCertificateAndPrivateKey(ctx)
rule := java.Signapk
args := map[string]string{
"certificates": pem.String() + " " + key.String(),
"flags": "-a 4096 --align-file-size", //alignment
}
implicits := android.Paths{pem, key}
if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
rule = java.SignapkRE
args["implicits"] = strings.Join(implicits.Strings(), ",")
args["outCommaList"] = signedOutputFile.String()
}
var validations android.Paths
validations = append(validations, runApexLinkerconfigValidation(ctx, unsignedOutputFile, imageDir))
if !a.skipValidation(apexSepolicyTests) && android.InList(a.payloadFsType, []fsType{ext4, erofs}) {
validations = append(validations, runApexSepolicyTests(ctx, a, unsignedOutputFile))
}
if !a.testApex && len(a.properties.Unwanted_transitive_deps) > 0 {
validations = append(validations,
runApexElfCheckerUnwanted(ctx, unsignedOutputFile, a.properties.Unwanted_transitive_deps))
}
if !a.skipValidation(hostApexVerifier) && android.InList(a.payloadFsType, []fsType{ext4, erofs}) {
validations = append(validations, runApexHostVerifier(ctx, a, unsignedOutputFile))
}
ctx.Build(pctx, android.BuildParams{
Rule: rule,
Description: "signapk",
Output: signedOutputFile,
Input: unsignedOutputFile,
Implicits: implicits,
Args: args,
Validations: validations,
})
if suffix == imageApexSuffix {
a.outputApexFile = signedOutputFile
}
a.outputFile = signedOutputFile
if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
ctx.PropertyErrorf("test_only_force_compression", "not available")
return
}
installSuffix := suffix
a.setCompression(ctx)
if a.isCompressed {
unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
compressRule := android.NewRuleBuilder(pctx, ctx)
compressRule.Command().
Text("rm").
FlagWithOutput("-f ", unsignedCompressedOutputFile)
compressRule.Command().
BuiltTool("apex_compression_tool").
Flag("compress").
FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
FlagWithInput("--input ", signedOutputFile).
FlagWithOutput("--output ", unsignedCompressedOutputFile)
compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
args["outCommaList"] = signedCompressedOutputFile.String()
}
ctx.Build(pctx, android.BuildParams{
Rule: rule,
Description: "sign compressedApex",
Output: signedCompressedOutputFile,
Input: unsignedCompressedOutputFile,
Implicits: implicits,
Args: args,
})
a.outputFile = signedCompressedOutputFile
installSuffix = imageCapexSuffix
}
if !a.installable() {
a.SkipInstall()
}
installDeps := slices.Concat(a.compatSymlinks, a.extraInstalledFiles)
// Install to $OUT/soong/{target,host}/.../apex.
a.installedFile = ctx.InstallFile(a.installDir, a.Name()+installSuffix, a.outputFile, installDeps...)
// installed-files.txt is dist'ed
a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
a.apexKeysPath = writeApexKeys(ctx, a)
}
// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
// the zip container of this APEX. See the description of the 'certificate' property for how
// the cert and the private key are found.
func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
if a.containerCertificateFile != nil {
return a.containerCertificateFile, a.containerPrivateKeyFile
}
cert := String(a.overridableProperties.Certificate)
if cert == "" {
return ctx.Config().DefaultAppCertificate(ctx)
}
defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
pem = defaultDir.Join(ctx, cert+".x509.pem")
key = defaultDir.Join(ctx, cert+".pk8")
return pem, key
}
func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
// For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
// to see if it should be overridden because their <apex name> is dynamically generated
// according to its VNDK version.
if a.vndkApex {
overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
if overridden {
return overrideName + ".v" + a.vndkVersion()
}
return ""
}
packageNameFromProp := a.overridableProperties.Package_name.GetOrDefault(ctx, "")
if packageNameFromProp != "" {
return packageNameFromProp
}
manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
if overridden {
return manifestPackageName
}
return ""
}
func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
if a.properties.IsCoverageVariant {
// Otherwise, we will have duplicated rules for coverage and
// non-coverage variants of the same APEX
return
}
depInfos := android.DepNameToDepInfoMap{}
a.WalkPayloadDeps(ctx, func(ctx android.BaseModuleContext, from, to android.ModuleProxy, externalDep bool) bool {
if from.Name() == to.Name() {
// This can happen for cc.reuseObjTag. We are not interested in tracking this.
// As soon as the dependency graph crosses the APEX boundary, don't go further.
return !externalDep
}
// Skip dependencies that are only available to APEXes; they are developed with updatability
// in mind and don't need manual approval.
if android.OtherModulePointerProviderOrDefault(ctx, to, android.CommonModuleInfoProvider).NotAvailableForPlatform {
return !externalDep
}
depTag := ctx.OtherModuleDependencyTag(to)
// Check to see if dependency been marked to skip the dependency check
if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
return !externalDep
}
if info, exists := depInfos[to.Name()]; exists {
if !android.InList(from.Name(), info.From) {
info.From = append(info.From, from.Name())
}
info.IsExternal = info.IsExternal && externalDep
depInfos[to.Name()] = info
} else {
toMinSdkVersion := "(no version)"
if info, ok := android.OtherModuleProvider(ctx, to, android.CommonModuleInfoProvider); ok &&
!info.MinSdkVersion.IsPlatform && info.MinSdkVersion.ApiLevel != nil {
toMinSdkVersion = info.MinSdkVersion.ApiLevel.String()
}
depInfos[to.Name()] = android.ApexModuleDepInfo{
To: to.Name(),
From: []string{from.Name()},
IsExternal: externalDep,
MinSdkVersion: toMinSdkVersion,
}
}
// As soon as the dependency graph crosses the APEX boundary, don't go further.
return !externalDep
})
a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).String(), depInfos)
ctx.Build(pctx, android.BuildParams{
Rule: android.Phony,
Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Inputs: []android.Path{
a.ApexBundleDepsInfo.FullListPath(),
a.ApexBundleDepsInfo.FlatListPath(),
},
})
}
func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
depSetsBuilder := java.NewLintDepSetBuilder()
for _, fi := range a.filesInfo {
if fi.lintInfo != nil {
depSetsBuilder.Transitive(fi.lintInfo)
}
}
depSets := depSetsBuilder.Build()
var validations android.Paths
if a.checkStrictUpdatabilityLinting(ctx) {
baselines := depSets.Baseline.ToList()
if len(baselines) > 0 {
outputFile := java.VerifyStrictUpdatabilityChecks(ctx, baselines)
validations = append(validations, outputFile)
}
}
a.lintReports = java.BuildModuleLintReportZips(ctx, depSets, validations)
}
func (a *apexBundle) buildCannedFsConfig(ctx android.ModuleContext) android.Path {
var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
var executablePaths []string // this also includes dirs
var appSetDirs []string
appSetFiles := make(map[string]android.Path)
for _, f := range a.filesInfo {
pathInApex := f.path()
if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
executablePaths = append(executablePaths, pathInApex)
for _, d := range f.dataPaths {
rel := d.ToRelativeInstallPath()
readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, rel))
}
for _, s := range f.symlinks {
executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
}
} else if f.class == appSet {
// base APK
readOnlyPaths = append(readOnlyPaths, pathInApex)
// Additional APKs
appSetDirs = append(appSetDirs, f.installDir)
appSetFiles[f.installDir] = f.module.(*java.AndroidAppSet).PackedAdditionalOutputs()
} else {
readOnlyPaths = append(readOnlyPaths, pathInApex)
}
dir := f.installDir
for !android.InList(dir, executablePaths) && dir != "" {
executablePaths = append(executablePaths, dir)
dir, _ = filepath.Split(dir) // move up to the parent
if len(dir) > 0 {
// remove trailing slash
dir = dir[:len(dir)-1]
}
}
}
sort.Strings(readOnlyPaths)
sort.Strings(executablePaths)
sort.Strings(appSetDirs)
cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
builder := android.NewRuleBuilder(pctx, ctx)
cmd := builder.Command()
cmd.Text("(")
cmd.Text("echo '/ 1000 1000 0755';")
for _, p := range readOnlyPaths {
cmd.Textf("echo '/%s 1000 1000 0644';", p)
}
for _, p := range executablePaths {
cmd.Textf("echo '/%s 0 2000 0755';", p)
}
for _, dir := range appSetDirs {
cmd.Textf("echo '/%s 0 2000 0755';", dir)
file := appSetFiles[dir]
cmd.Text("zipinfo -1").Input(file).Textf(`| sed "s:\(.*\):/%s/\1 1000 1000 0644:";`, dir)
}
// Custom fs_config is "appended" to the last so that entries from the file are preferred
// over default ones set above.
customFsConfig := a.properties.Canned_fs_config.GetOrDefault(ctx, "")
if customFsConfig != "" {
cmd.Text("cat").Input(android.PathForModuleSrc(ctx, customFsConfig))
}
cmd.Text(")").FlagWithOutput("> ", cannedFsConfig)
builder.Build("generateFsConfig", fmt.Sprintf("Generating canned fs config for %s", a.BaseModuleName()))
return cannedFsConfig
}
func runApexLinkerconfigValidation(ctx android.ModuleContext, apexFile android.Path, imageDir android.Path) android.Path {
timestamp := android.PathForModuleOut(ctx, "apex_linkerconfig_validation.timestamp")
ctx.Build(pctx, android.BuildParams{
Rule: apexLinkerconfigValidationRule,
Input: apexFile,
Output: timestamp,
Args: map[string]string{
"image_dir": imageDir.String(),
},
})
return timestamp
}
// Can't use PartitionTag() because PartitionTag() returns the partition this module is actually
// installed (e.g. PartitionTag() may return "system" for vendor apex when vendor is linked to /system/vendor)
func (a *apexBundle) partition() string {
if a.SocSpecific() {
return "vendor"
} else if a.DeviceSpecific() {
return "odm"
} else if a.ProductSpecific() {
return "product"
} else if a.SystemExtSpecific() {
return "system_ext"
} else {
return "system"
}
}
// Runs apex_sepolicy_tests
//
// $ apex-ls -Z {apex_file} > {file_contexts}
// $ apex_sepolicy_tests -f {file_contexts}
func runApexSepolicyTests(ctx android.ModuleContext, a *apexBundle, apexFile android.Path) android.Path {
timestamp := android.PathForModuleOut(ctx, "apex_sepolicy_tests.timestamp")
ctx.Build(pctx, android.BuildParams{
Rule: apexSepolicyTestsRule,
Input: apexFile,
Output: timestamp,
Args: map[string]string{
"partition_tag": a.partition(),
},
})
return timestamp
}
func runApexElfCheckerUnwanted(ctx android.ModuleContext, apexFile android.Path, unwanted []string) android.Path {
timestamp := android.PathForModuleOut(ctx, "apex_elf_unwanted.timestamp")
ctx.Build(pctx, android.BuildParams{
Rule: apexElfCheckerUnwantedRule,
Input: apexFile,
Output: timestamp,
Args: map[string]string{
"unwanted": android.JoinWithSuffixAndSeparator(unwanted, ".so", ":"),
"tool_path": ctx.Config().HostToolPath(ctx, "").String() + ":${config.ClangBin}",
},
})
return timestamp
}
func runApexHostVerifier(ctx android.ModuleContext, a *apexBundle, apexFile android.Path) android.Path {
timestamp := android.PathForModuleOut(ctx, "host_apex_verifier.timestamp")
ctx.Build(pctx, android.BuildParams{
Rule: apexHostVerifierRule,
Input: apexFile,
Output: timestamp,
Args: map[string]string{
"partition_tag": a.partition(),
},
})
return timestamp
}
|