-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
2077 lines (1723 loc) · 65.3 KB
/
config.go
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 2015 Google Inc. All rights reserved.
//
// 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 android
// This is the primary location to write and read all configuration values and
// product variables necessary for soong_build's operation.
import (
"android/soong/shared"
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"unicode"
"github.com/google/blueprint"
"github.com/google/blueprint/bootstrap"
"github.com/google/blueprint/pathtools"
"github.com/google/blueprint/proptools"
"android/soong/android/soongconfig"
"android/soong/bazel"
"android/soong/remoteexec"
"android/soong/starlark_fmt"
)
// Bool re-exports proptools.Bool for the android package.
var Bool = proptools.Bool
// String re-exports proptools.String for the android package.
var String = proptools.String
// StringDefault re-exports proptools.StringDefault for the android package.
var StringDefault = proptools.StringDefault
// FutureApiLevelInt is a placeholder constant for unreleased API levels.
const FutureApiLevelInt = 10000
// PrivateApiLevel represents the api level of SdkSpecPrivate (sdk_version: "")
// This api_level exists to differentiate user-provided "" from "current" sdk_version
// The differentiation is necessary to enable different validation rules for these two possible values.
var PrivateApiLevel = ApiLevel{
value: "current", // The value is current since aidl expects `current` as the default (TestAidlFlagsWithMinSdkVersion)
number: FutureApiLevelInt + 1, // This is used to differentiate it from FutureApiLevel
isPreview: true,
}
// FutureApiLevel represents unreleased API levels.
var FutureApiLevel = ApiLevel{
value: "current",
number: FutureApiLevelInt,
isPreview: true,
}
// The product variables file name, containing product config from Kati.
const productVariablesFileName = "soong.variables"
// A Config object represents the entire build configuration for Android.
type Config struct {
*config
}
type SoongBuildMode int
type CmdArgs struct {
bootstrap.Args
RunGoTests bool
OutDir string
SoongOutDir string
SoongVariables string
BazelQueryViewDir string
ModuleGraphFile string
ModuleActionsFile string
DocFile string
BuildFromSourceStub bool
EnsureAllowlistIntegrity bool
}
// Build modes that soong_build can run as.
const (
// Don't use bazel at all during module analysis.
AnalysisNoBazel SoongBuildMode = iota
// Generate BUILD files which faithfully represent the dependency graph of
// blueprint modules. Individual BUILD targets will not, however, faitfhully
// express build semantics.
GenerateQueryView
// Create a JSON representation of the module graph and exit.
GenerateModuleGraph
// Generate a documentation file for module type definitions and exit.
GenerateDocFile
)
// SoongOutDir returns the build output directory for the configuration.
func (c Config) SoongOutDir() string {
return c.soongOutDir
}
// tempDir returns the path to out/soong/.temp, which is cleared at the beginning of every build.
func (c Config) tempDir() string {
return shared.TempDirForOutDir(c.soongOutDir)
}
func (c Config) OutDir() string {
return c.outDir
}
func (c Config) RunGoTests() bool {
return c.runGoTests
}
func (c Config) DebugCompilation() bool {
return false // Never compile Go code in the main build for debugging
}
func (c Config) Subninjas() []string {
return []string{}
}
func (c Config) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
return []bootstrap.PrimaryBuilderInvocation{}
}
// RunningInsideUnitTest returns true if this code is being run as part of a Soong unit test.
func (c Config) RunningInsideUnitTest() bool {
return c.config.TestProductVariables != nil
}
// DisableHiddenApiChecks returns true if hiddenapi checks have been disabled.
// For 'eng' target variant hiddenapi checks are disabled by default for performance optimisation,
// but can be enabled by setting environment variable ENABLE_HIDDENAPI_FLAGS=true.
// For other target variants hiddenapi check are enabled by default but can be disabled by
// setting environment variable UNSAFE_DISABLE_HIDDENAPI_FLAGS=true.
// If both ENABLE_HIDDENAPI_FLAGS=true and UNSAFE_DISABLE_HIDDENAPI_FLAGS=true, then
// ENABLE_HIDDENAPI_FLAGS=true will be triggered and hiddenapi checks will be considered enabled.
func (c Config) DisableHiddenApiChecks() bool {
return !c.IsEnvTrue("ENABLE_HIDDENAPI_FLAGS") &&
(c.IsEnvTrue("UNSAFE_DISABLE_HIDDENAPI_FLAGS") ||
Bool(c.productVariables.Eng))
}
// DisableVerifyOverlaps returns true if verify_overlaps is skipped.
// Mismatch in version of apexes and module SDK is required for mainline prebuilts to work in
// trunk stable.
// Thus, verify_overlaps is disabled when RELEASE_DEFAULT_MODULE_BUILD_FROM_SOURCE is set to false.
// TODO(b/308174018): Re-enable verify_overlaps for both builr from source/mainline prebuilts.
func (c Config) DisableVerifyOverlaps() bool {
return c.IsEnvTrue("DISABLE_VERIFY_OVERLAPS") || !c.ReleaseDefaultModuleBuildFromSource()
}
// MaxPageSizeSupported returns the max page size supported by the device. This
// value will define the ELF segment alignment for binaries (executables and
// shared libraries).
func (c Config) MaxPageSizeSupported() string {
return String(c.config.productVariables.DeviceMaxPageSizeSupported)
}
// NoBionicPageSizeMacro returns true when AOSP is page size agnostic.
// This means that the bionic's macro PAGE_SIZE won't be defined.
// Returns false when AOSP is NOT page size agnostic.
// This means that bionic's macro PAGE_SIZE is defined.
func (c Config) NoBionicPageSizeMacro() bool {
return Bool(c.config.productVariables.DeviceNoBionicPageSizeMacro)
}
// The release version passed to aconfig, derived from RELEASE_VERSION
func (c Config) ReleaseVersion() string {
return c.config.productVariables.ReleaseVersion
}
// The aconfig value set passed to aconfig, derived from RELEASE_VERSION
func (c Config) ReleaseAconfigValueSets() []string {
return c.config.productVariables.ReleaseAconfigValueSets
}
// The flag default permission value passed to aconfig
// derived from RELEASE_ACONFIG_FLAG_DEFAULT_PERMISSION
func (c Config) ReleaseAconfigFlagDefaultPermission() string {
return c.config.productVariables.ReleaseAconfigFlagDefaultPermission
}
// The flag indicating behavior for the tree wrt building modules or using prebuilts
// derived from RELEASE_DEFAULT_MODULE_BUILD_FROM_SOURCE
func (c Config) ReleaseDefaultModuleBuildFromSource() bool {
return c.config.productVariables.ReleaseDefaultModuleBuildFromSource == nil ||
Bool(c.config.productVariables.ReleaseDefaultModuleBuildFromSource)
}
// Enables flagged apis annotated with READ_WRITE aconfig flags to be included in the stubs
// and hiddenapi flags so that they are accessible at runtime
func (c Config) ReleaseExportRuntimeApis() bool {
return Bool(c.config.productVariables.ExportRuntimeApis)
}
// Enables ABI monitoring of NDK libraries
func (c Config) ReleaseNdkAbiMonitored() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_NDK_ABI_MONITORED")
}
func (c Config) ReleaseHiddenApiExportableStubs() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_HIDDEN_API_EXPORTABLE_STUBS") ||
Bool(c.config.productVariables.HiddenapiExportableStubs)
}
// A DeviceConfig object represents the configuration for a particular device
// being built. For now there will only be one of these, but in the future there
// may be multiple devices being built.
type DeviceConfig struct {
*deviceConfig
}
// VendorConfig represents the configuration for vendor-specific behavior.
type VendorConfig soongconfig.SoongConfig
// Definition of general build configuration for soong_build. Some of these
// product configuration values are read from Kati-generated soong.variables.
type config struct {
// Options configurable with soong.variables
productVariables ProductVariables
// Only available on configs created by TestConfig
TestProductVariables *ProductVariables
ProductVariablesFileName string
// BuildOS stores the OsType for the OS that the build is running on.
BuildOS OsType
// BuildArch stores the ArchType for the CPU that the build is running on.
BuildArch ArchType
Targets map[OsType][]Target
BuildOSTarget Target // the Target for tools run on the build machine
BuildOSCommonTarget Target // the Target for common (java) tools run on the build machine
AndroidCommonTarget Target // the Target for common modules for the Android device
AndroidFirstDeviceTarget Target // the first Target for modules for the Android device
// multilibConflicts for an ArchType is true if there is earlier configured
// device architecture with the same multilib value.
multilibConflicts map[ArchType]bool
deviceConfig *deviceConfig
outDir string // The output directory (usually out/)
soongOutDir string
moduleListFile string // the path to the file which lists blueprint files to parse.
runGoTests bool
env map[string]string
envLock sync.Mutex
envDeps map[string]string
envFrozen bool
// Changes behavior based on whether Kati runs after soong_build, or if soong_build
// runs standalone.
katiEnabled bool
captureBuild bool // true for tests, saves build parameters for each module
ignoreEnvironment bool // true for tests, returns empty from all Getenv calls
fs pathtools.FileSystem
mockBpList string
BuildMode SoongBuildMode
// If testAllowNonExistentPaths is true then PathForSource and PathForModuleSrc won't error
// in tests when a path doesn't exist.
TestAllowNonExistentPaths bool
// The list of files that when changed, must invalidate soong_build to
// regenerate build.ninja.
ninjaFileDepsSet sync.Map
OncePer
// If buildFromSourceStub is true then the Java API stubs are
// built from the source Java files, not the signature text files.
buildFromSourceStub bool
// If ensureAllowlistIntegrity is true, then the presence of any allowlisted
// modules that aren't mixed-built for at least one variant will cause a build
// failure
ensureAllowlistIntegrity bool
// List of Api libraries that contribute to Api surfaces.
apiLibraries map[string]struct{}
}
type deviceConfig struct {
config *config
OncePer
}
type jsonConfigurable interface {
SetDefaultConfig()
}
func loadConfig(config *config) error {
return loadFromConfigFile(&config.productVariables, absolutePath(config.ProductVariablesFileName))
}
// Checks if the string is a valid go identifier. This is equivalent to blueprint's definition
// of an identifier, so it will match the same identifiers as those that can be used in bp files.
func isGoIdentifier(ident string) bool {
for i, r := range ident {
valid := r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) && i > 0
if !valid {
return false
}
}
return len(ident) > 0
}
// loadFromConfigFile loads and decodes configuration options from a JSON file
// in the current working directory.
func loadFromConfigFile(configurable *ProductVariables, filename string) error {
// Try to open the file
configFileReader, err := os.Open(filename)
defer configFileReader.Close()
if os.IsNotExist(err) {
// Need to create a file, so that blueprint & ninja don't get in
// a dependency tracking loop.
// Make a file-configurable-options with defaults, write it out using
// a json writer.
configurable.SetDefaultConfig()
err = saveToConfigFile(configurable, filename)
if err != nil {
return err
}
} else if err != nil {
return fmt.Errorf("config file: could not open %s: %s", filename, err.Error())
} else {
// Make a decoder for it
jsonDecoder := json.NewDecoder(configFileReader)
err = jsonDecoder.Decode(configurable)
if err != nil {
return fmt.Errorf("config file: %s did not parse correctly: %s", filename, err.Error())
}
}
if Bool(configurable.GcovCoverage) && Bool(configurable.ClangCoverage) {
return fmt.Errorf("GcovCoverage and ClangCoverage cannot both be set")
}
configurable.Native_coverage = proptools.BoolPtr(
Bool(configurable.GcovCoverage) ||
Bool(configurable.ClangCoverage))
// The go scanner's definition of identifiers is c-style identifiers, but allowing unicode's
// definition of letters and digits. This is the same scanner that blueprint uses, so it
// will allow the same identifiers as are valid in bp files.
for namespace := range configurable.VendorVars {
if !isGoIdentifier(namespace) {
return fmt.Errorf("soong config namespaces must be valid identifiers: %q", namespace)
}
for variable := range configurable.VendorVars[namespace] {
if !isGoIdentifier(variable) {
return fmt.Errorf("soong config variables must be valid identifiers: %q", variable)
}
}
}
// when Platform_sdk_final is true (or PLATFORM_VERSION_CODENAME is REL), use Platform_sdk_version;
// if false (pre-released version, for example), use Platform_sdk_codename.
if Bool(configurable.Platform_sdk_final) {
if configurable.Platform_sdk_version != nil {
configurable.Platform_sdk_version_or_codename =
proptools.StringPtr(strconv.Itoa(*(configurable.Platform_sdk_version)))
} else {
return fmt.Errorf("Platform_sdk_version cannot be pointed by a NULL pointer")
}
} else {
configurable.Platform_sdk_version_or_codename =
proptools.StringPtr(String(configurable.Platform_sdk_codename))
}
return saveToBazelConfigFile(configurable, filepath.Dir(filename))
}
// atomically writes the config file in case two copies of soong_build are running simultaneously
// (for example, docs generation and ninja manifest generation)
func saveToConfigFile(config *ProductVariables, filename string) error {
data, err := json.MarshalIndent(&config, "", " ")
if err != nil {
return fmt.Errorf("cannot marshal config data: %s", err.Error())
}
f, err := os.CreateTemp(filepath.Dir(filename), "config")
if err != nil {
return fmt.Errorf("cannot create empty config file %s: %s", filename, err.Error())
}
defer os.Remove(f.Name())
defer f.Close()
_, err = f.Write(data)
if err != nil {
return fmt.Errorf("default config file: %s could not be written: %s", filename, err.Error())
}
_, err = f.WriteString("\n")
if err != nil {
return fmt.Errorf("default config file: %s could not be written: %s", filename, err.Error())
}
f.Close()
os.Rename(f.Name(), filename)
return nil
}
type productVariableStarlarkRepresentation struct {
soongType string
selectable bool
archVariant bool
}
func saveToBazelConfigFile(config *ProductVariables, outDir string) error {
dir := filepath.Join(outDir, bazel.SoongInjectionDirName, "product_config")
err := createDirIfNonexistent(dir, os.ModePerm)
if err != nil {
return fmt.Errorf("Could not create dir %s: %s", dir, err)
}
allProductVariablesType := reflect.TypeOf((*ProductVariables)(nil)).Elem()
productVariablesInfo := make(map[string]productVariableStarlarkRepresentation)
p := variableProperties{}
t := reflect.TypeOf(p.Product_variables)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
archVariant := proptools.HasTag(f, "android", "arch_variant")
if mainProductVariablesStructField, ok := allProductVariablesType.FieldByName(f.Name); ok {
productVariablesInfo[f.Name] = productVariableStarlarkRepresentation{
soongType: stringRepresentationOfSimpleType(mainProductVariablesStructField.Type),
selectable: true,
archVariant: archVariant,
}
} else {
panic("Unknown variable " + f.Name)
}
}
err = pathtools.WriteFileIfChanged(filepath.Join(dir, "product_variable_constants.bzl"), []byte(fmt.Sprintf(`
# product_var_constant_info is a map of product variables to information about them. The fields are:
# - soongType: The type of the product variable as it appears in soong's ProductVariables struct.
# examples are string, bool, int, *bool, *string, []string, etc. This may be an overly
# conservative estimation of the type, for example a *bool could oftentimes just be a
# bool that defaults to false.
# - selectable: if this product variable can be selected on in Android.bp/build files. This means
# it's listed in the "variableProperties" soong struct. Currently all variables in
# this list are selectable because we only need the selectable ones at the moment,
# but the list may be expanded later.
# - archVariant: If the variable is tagged as arch variant in the "variableProperties" struct.
product_var_constant_info = %s
product_var_constraints = [k for k, v in product_var_constant_info.items() if v.selectable]
arch_variant_product_var_constraints = [k for k, v in product_var_constant_info.items() if v.selectable and v.archVariant]
`, starlark_fmt.PrintAny(productVariablesInfo, 0))), 0644)
if err != nil {
return fmt.Errorf("Could not write .bzl config file %s", err)
}
err = pathtools.WriteFileIfChanged(filepath.Join(dir, "BUILD"),
[]byte(bazel.GeneratedBazelFileWarning), 0644)
if err != nil {
return fmt.Errorf("Could not write BUILD config file %s", err)
}
return nil
}
func stringRepresentationOfSimpleType(ty reflect.Type) string {
switch ty.Kind() {
case reflect.String:
return "string"
case reflect.Bool:
return "bool"
case reflect.Int:
return "int"
case reflect.Slice:
return "[]" + stringRepresentationOfSimpleType(ty.Elem())
case reflect.Pointer:
return "*" + stringRepresentationOfSimpleType(ty.Elem())
default:
panic("unimplemented type: " + ty.Kind().String())
}
}
// NullConfig returns a mostly empty Config for use by standalone tools like dexpreopt_gen that
// use the android package.
func NullConfig(outDir, soongOutDir string) Config {
return Config{
config: &config{
outDir: outDir,
soongOutDir: soongOutDir,
fs: pathtools.OsFs,
},
}
}
// NewConfig creates a new Config object. The srcDir argument specifies the path
// to the root source directory. It also loads the config file, if found.
func NewConfig(cmdArgs CmdArgs, availableEnv map[string]string) (Config, error) {
// Make a config with default options.
config := &config{
ProductVariablesFileName: cmdArgs.SoongVariables,
env: availableEnv,
outDir: cmdArgs.OutDir,
soongOutDir: cmdArgs.SoongOutDir,
runGoTests: cmdArgs.RunGoTests,
multilibConflicts: make(map[ArchType]bool),
moduleListFile: cmdArgs.ModuleListFile,
fs: pathtools.NewOsFs(absSrcDir),
buildFromSourceStub: cmdArgs.BuildFromSourceStub,
}
config.deviceConfig = &deviceConfig{
config: config,
}
// Soundness check of the build and source directories. This won't catch strange
// configurations with symlinks, but at least checks the obvious case.
absBuildDir, err := filepath.Abs(cmdArgs.SoongOutDir)
if err != nil {
return Config{}, err
}
absSrcDir, err := filepath.Abs(".")
if err != nil {
return Config{}, err
}
if strings.HasPrefix(absSrcDir, absBuildDir) {
return Config{}, fmt.Errorf("Build dir must not contain source directory")
}
// Load any configurable options from the configuration file
err = loadConfig(config)
if err != nil {
return Config{}, err
}
KatiEnabledMarkerFile := filepath.Join(cmdArgs.SoongOutDir, ".soong.kati_enabled")
if _, err := os.Stat(absolutePath(KatiEnabledMarkerFile)); err == nil {
config.katiEnabled = true
}
determineBuildOS(config)
// Sets up the map of target OSes to the finer grained compilation targets
// that are configured from the product variables.
targets, err := decodeTargetProductVariables(config)
if err != nil {
return Config{}, err
}
// Make the CommonOS OsType available for all products.
targets[CommonOS] = []Target{commonTargetMap[CommonOS.Name]}
var archConfig []archConfig
if config.NdkAbis() {
archConfig = getNdkAbisConfig()
} else if config.AmlAbis() {
archConfig = getAmlAbisConfig()
}
if archConfig != nil {
androidTargets, err := decodeAndroidArchSettings(archConfig)
if err != nil {
return Config{}, err
}
targets[Android] = androidTargets
}
multilib := make(map[string]bool)
for _, target := range targets[Android] {
if seen := multilib[target.Arch.ArchType.Multilib]; seen {
config.multilibConflicts[target.Arch.ArchType] = true
}
multilib[target.Arch.ArchType.Multilib] = true
}
// Map of OS to compilation targets.
config.Targets = targets
// Compilation targets for host tools.
config.BuildOSTarget = config.Targets[config.BuildOS][0]
config.BuildOSCommonTarget = getCommonTargets(config.Targets[config.BuildOS])[0]
// Compilation targets for Android.
if len(config.Targets[Android]) > 0 {
config.AndroidCommonTarget = getCommonTargets(config.Targets[Android])[0]
config.AndroidFirstDeviceTarget = FirstTarget(config.Targets[Android], "lib64", "lib32")[0]
}
setBuildMode := func(arg string, mode SoongBuildMode) {
if arg != "" {
if config.BuildMode != AnalysisNoBazel {
fmt.Fprintf(os.Stderr, "buildMode is already set, illegal argument: %s", arg)
os.Exit(1)
}
config.BuildMode = mode
}
}
setBuildMode(cmdArgs.BazelQueryViewDir, GenerateQueryView)
setBuildMode(cmdArgs.ModuleGraphFile, GenerateModuleGraph)
setBuildMode(cmdArgs.DocFile, GenerateDocFile)
// TODO(b/276958307): Replace the hardcoded list to a sdk_library local prop.
config.apiLibraries = map[string]struct{}{
"android.net.ipsec.ike": {},
"art.module.public.api": {},
"conscrypt.module.public.api": {},
"framework-adservices": {},
"framework-appsearch": {},
"framework-bluetooth": {},
"framework-configinfrastructure": {},
"framework-connectivity": {},
"framework-connectivity-t": {},
"framework-devicelock": {},
"framework-graphics": {},
"framework-healthfitness": {},
"framework-location": {},
"framework-media": {},
"framework-mediaprovider": {},
"framework-nfc": {},
"framework-ondevicepersonalization": {},
"framework-pdf": {},
"framework-pdf-v": {},
"framework-permission": {},
"framework-permission-s": {},
"framework-scheduling": {},
"framework-sdkextensions": {},
"framework-statsd": {},
"framework-sdksandbox": {},
"framework-tethering": {},
"framework-uwb": {},
"framework-virtualization": {},
"framework-wifi": {},
"i18n.module.public.api": {},
}
config.productVariables.Build_from_text_stub = boolPtr(config.BuildFromTextStub())
return Config{config}, err
}
// mockFileSystem replaces all reads with accesses to the provided map of
// filenames to contents stored as a byte slice.
func (c *config) mockFileSystem(bp string, fs map[string][]byte) {
mockFS := map[string][]byte{}
if _, exists := mockFS["Android.bp"]; !exists {
mockFS["Android.bp"] = []byte(bp)
}
for k, v := range fs {
mockFS[k] = v
}
// no module list file specified; find every file named Blueprints or Android.bp
pathsToParse := []string{}
for candidate := range mockFS {
base := filepath.Base(candidate)
if base == "Android.bp" {
pathsToParse = append(pathsToParse, candidate)
}
}
if len(pathsToParse) < 1 {
panic(fmt.Sprintf("No Blueprint or Android.bp files found in mock filesystem: %v\n", mockFS))
}
mockFS[blueprint.MockModuleListFile] = []byte(strings.Join(pathsToParse, "\n"))
c.fs = pathtools.MockFs(mockFS)
c.mockBpList = blueprint.MockModuleListFile
}
func (c *config) SetAllowMissingDependencies() {
c.productVariables.Allow_missing_dependencies = proptools.BoolPtr(true)
}
// BlueprintToolLocation returns the directory containing build system tools
// from Blueprint, like soong_zip and merge_zips.
func (c *config) HostToolDir() string {
if c.KatiEnabled() {
return filepath.Join(c.outDir, "host", c.PrebuiltOS(), "bin")
} else {
return filepath.Join(c.soongOutDir, "host", c.PrebuiltOS(), "bin")
}
}
func (c *config) HostToolPath(ctx PathContext, tool string) Path {
path := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin", tool)
return path
}
func (c *config) HostJNIToolPath(ctx PathContext, lib string) Path {
ext := ".so"
if runtime.GOOS == "darwin" {
ext = ".dylib"
}
path := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "lib64", lib+ext)
return path
}
func (c *config) HostJavaToolPath(ctx PathContext, tool string) Path {
path := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "framework", tool)
return path
}
func (c *config) HostCcSharedLibPath(ctx PathContext, lib string) Path {
libDir := "lib"
if ctx.Config().BuildArch.Multilib == "lib64" {
libDir = "lib64"
}
return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, libDir, lib+".so")
}
// PrebuiltOS returns the name of the host OS used in prebuilts directories.
func (c *config) PrebuiltOS() string {
switch runtime.GOOS {
case "linux":
return "linux-x86"
case "darwin":
return "darwin-x86"
default:
panic("Unknown GOOS")
}
}
// GoRoot returns the path to the root directory of the Go toolchain.
func (c *config) GoRoot() string {
return fmt.Sprintf("prebuilts/go/%s", c.PrebuiltOS())
}
// PrebuiltBuildTool returns the path to a tool in the prebuilts directory containing
// checked-in tools, like Kati, Ninja or Toybox, for the current host OS.
func (c *config) PrebuiltBuildTool(ctx PathContext, tool string) Path {
return PathForSource(ctx, "prebuilts/build-tools", c.PrebuiltOS(), "bin", tool)
}
// CpPreserveSymlinksFlags returns the host-specific flag for the cp(1) command
// to preserve symlinks.
func (c *config) CpPreserveSymlinksFlags() string {
switch runtime.GOOS {
case "darwin":
return "-R"
case "linux":
return "-d"
default:
return ""
}
}
func (c *config) Getenv(key string) string {
var val string
var exists bool
c.envLock.Lock()
defer c.envLock.Unlock()
if c.envDeps == nil {
c.envDeps = make(map[string]string)
}
if val, exists = c.envDeps[key]; !exists {
if c.envFrozen {
panic("Cannot access new environment variables after envdeps are frozen")
}
val, _ = c.env[key]
c.envDeps[key] = val
}
return val
}
func (c *config) GetenvWithDefault(key string, defaultValue string) string {
ret := c.Getenv(key)
if ret == "" {
return defaultValue
}
return ret
}
func (c *config) IsEnvTrue(key string) bool {
value := c.Getenv(key)
return value == "1" || value == "y" || value == "yes" || value == "on" || value == "true"
}
func (c *config) IsEnvFalse(key string) bool {
value := c.Getenv(key)
return value == "0" || value == "n" || value == "no" || value == "off" || value == "false"
}
// EnvDeps returns the environment variables this build depends on. The first
// call to this function blocks future reads from the environment.
func (c *config) EnvDeps() map[string]string {
c.envLock.Lock()
defer c.envLock.Unlock()
c.envFrozen = true
return c.envDeps
}
func (c *config) KatiEnabled() bool {
return c.katiEnabled
}
func (c *config) ProductVariables() ProductVariables {
return c.productVariables
}
func (c *config) BuildId() string {
return String(c.productVariables.BuildId)
}
// BuildNumberFile returns the path to a text file containing metadata
// representing the current build's number.
//
// Rules that want to reference the build number should read from this file
// without depending on it. They will run whenever their other dependencies
// require them to run and get the current build number. This ensures they don't
// rebuild on every incremental build when the build number changes.
func (c *config) BuildNumberFile(ctx PathContext) Path {
return PathForOutput(ctx, String(c.productVariables.BuildNumberFile))
}
// DeviceName returns the name of the current device target.
// TODO: take an AndroidModuleContext to select the device name for multi-device builds
func (c *config) DeviceName() string {
return *c.productVariables.DeviceName
}
// DeviceProduct returns the current product target. There could be multiple of
// these per device type.
//
// NOTE: Do not base conditional logic on this value. It may break product inheritance.
func (c *config) DeviceProduct() string {
return *c.productVariables.DeviceProduct
}
// HasDeviceProduct returns if the build has a product. A build will not
// necessarily have a product when --skip-config is passed to soong, like it is
// in prebuilts/build-tools/build-prebuilts.sh
func (c *config) HasDeviceProduct() bool {
return c.productVariables.DeviceProduct != nil
}
func (c *config) DeviceResourceOverlays() []string {
return c.productVariables.DeviceResourceOverlays
}
func (c *config) ProductResourceOverlays() []string {
return c.productVariables.ProductResourceOverlays
}
func (c *config) PlatformVersionName() string {
return String(c.productVariables.Platform_version_name)
}
func (c *config) PlatformSdkVersion() ApiLevel {
return uncheckedFinalApiLevel(*c.productVariables.Platform_sdk_version)
}
func (c *config) RawPlatformSdkVersion() *int {
return c.productVariables.Platform_sdk_version
}
func (c *config) PlatformSdkFinal() bool {
return Bool(c.productVariables.Platform_sdk_final)
}
func (c *config) PlatformSdkCodename() string {
return String(c.productVariables.Platform_sdk_codename)
}
func (c *config) PlatformSdkExtensionVersion() int {
return *c.productVariables.Platform_sdk_extension_version
}
func (c *config) PlatformBaseSdkExtensionVersion() int {
return *c.productVariables.Platform_base_sdk_extension_version
}
func (c *config) PlatformSecurityPatch() string {
return String(c.productVariables.Platform_security_patch)
}
func (c *config) PlatformPreviewSdkVersion() string {
return String(c.productVariables.Platform_preview_sdk_version)
}
func (c *config) PlatformMinSupportedTargetSdkVersion() string {
return String(c.productVariables.Platform_min_supported_target_sdk_version)
}
func (c *config) PlatformBaseOS() string {
return String(c.productVariables.Platform_base_os)
}
func (c *config) PlatformVersionLastStable() string {
return String(c.productVariables.Platform_version_last_stable)
}
func (c *config) PlatformVersionKnownCodenames() string {
return String(c.productVariables.Platform_version_known_codenames)
}
func (c *config) MinSupportedSdkVersion() ApiLevel {
return uncheckedFinalApiLevel(21)
}
func (c *config) FinalApiLevels() []ApiLevel {
var levels []ApiLevel
for i := 1; i <= c.PlatformSdkVersion().FinalOrFutureInt(); i++ {
levels = append(levels, uncheckedFinalApiLevel(i))
}
return levels
}
func (c *config) PreviewApiLevels() []ApiLevel {
var levels []ApiLevel
i := 0
for _, codename := range c.PlatformVersionActiveCodenames() {
if codename == "REL" {
continue
}
levels = append(levels, ApiLevel{
value: codename,
number: i,
isPreview: true,
})
i++
}
return levels
}
func (c *config) LatestPreviewApiLevel() ApiLevel {
level := NoneApiLevel
for _, l := range c.PreviewApiLevels() {
if l.GreaterThan(level) {
level = l
}
}
return level
}
func (c *config) AllSupportedApiLevels() []ApiLevel {
var levels []ApiLevel
levels = append(levels, c.FinalApiLevels()...)
return append(levels, c.PreviewApiLevels()...)
}
// DefaultAppTargetSdk returns the API level that platform apps are targeting.
// This converts a codename to the exact ApiLevel it represents.
func (c *config) DefaultAppTargetSdk(ctx EarlyModuleContext) ApiLevel {
if Bool(c.productVariables.Platform_sdk_final) {
return c.PlatformSdkVersion()
}
codename := c.PlatformSdkCodename()
hostOnlyBuild := c.productVariables.DeviceArch == nil
if codename == "" {
// There are some host-only builds (those are invoked by build-prebuilts.sh) which
// don't set platform sdk codename. Platform sdk codename makes sense only when we
// are building the platform. So we don't enforce the below panic for the host-only
// builds.
if hostOnlyBuild {
return NoneApiLevel
}
panic("Platform_sdk_codename must be set")
}
if codename == "REL" {
panic("Platform_sdk_codename should not be REL when Platform_sdk_final is true")
}
return ApiLevelOrPanic(ctx, codename)
}
func (c *config) AppsDefaultVersionName() string {
return String(c.productVariables.AppsDefaultVersionName)
}