-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
2658 lines (2202 loc) · 84.4 KB
/
config.go
File metadata and controls
2658 lines (2202 loc) · 84.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 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 (
"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/shared"
)
// 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
KatiSuffix string
KatiEnabled bool
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 a documentation file for module type definitions and exit.
GenerateDocFile
)
const testKeyDir = "build/make/target/product/security"
func (c Config) genericConfig() Config {
return Config{c.config.genericConfigField}
}
// 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{}
}
func (c Config) IsBootstrap() bool { return false }
// 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 {
if c.IsEnvFalse("DISABLE_VERIFY_OVERLAPS") && c.ReleaseDisableVerifyOverlaps() {
panic("The current release configuration does not support verify_overlaps. DISABLE_VERIFY_OVERLAPS cannot be set to false")
}
return c.IsEnvTrue("DISABLE_VERIFY_OVERLAPS") || c.ReleaseDisableVerifyOverlaps() || !c.ReleaseDefaultModuleBuildFromSource()
}
func (c Config) CoverageSuffix() string {
if v := c.IsEnvTrue("EMMA_INSTRUMENT"); v {
return "coverage."
}
return ""
}
// 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)
}
func (c Config) DeviceCheckPrebuiltMaxPageSize() bool {
return Bool(c.config.productVariables.DeviceCheckPrebuiltMaxPageSize)
}
// 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
}
// If native modules should have symbols stripped by default. Default false, enabled for build tools
func (c Config) StripByDefault() bool {
return proptools.Bool(c.config.productVariables.StripByDefault)
}
func (c Config) ReleaseAconfigExtraReleaseConfigs() []string {
result := []string{}
if val, ok := c.config.productVariables.BuildFlags["RELEASE_ACONFIG_EXTRA_RELEASE_CONFIGS"]; ok {
if len(val) > 0 {
// Remove any duplicates from the list.
found := make(map[string]bool)
for _, k := range strings.Split(val, " ") {
if !found[k] {
found[k] = true
result = append(result, k)
}
}
}
}
return result
}
func (c Config) ReleaseAconfigExtraReleaseConfigsValueSets() map[string][]string {
result := make(map[string][]string)
for _, rcName := range c.ReleaseAconfigExtraReleaseConfigs() {
if value, ok := c.config.productVariables.BuildFlags["RELEASE_ACONFIG_VALUE_SETS_"+rcName]; ok {
result[rcName] = strings.Split(value, " ")
}
}
return result
}
// 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
}
func (c Config) ReleaseBuildClangVersion(defaultVersion string) string {
if val, exists := c.GetBuildFlag("RELEASE_BUILD_CLANG_VERSION"); exists && val != "" {
return val
}
return defaultVersion
}
func (c Config) ReleaseBuildClangShortVersion(defaultVersion string) string {
if val, exists := c.GetBuildFlag("RELEASE_BUILD_CLANG_SHORT_VERSION"); exists && val != "" {
return val
}
return defaultVersion
}
// 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)
}
func (c Config) ReleaseDefaultUpdatableModuleVersion() string {
if val, exists := c.GetBuildFlag("RELEASE_DEFAULT_UPDATABLE_MODULE_VERSION"); exists {
return val
}
panic("RELEASE_DEFAULT_UPDATABLE_MODULE_VERSION is missing from build flags.")
}
func (c Config) ReleaseDisableVerifyOverlaps() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_DISABLE_VERIFY_OVERLAPS_CHECK")
}
// 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)
}
// Enable read flag from new storage
func (c Config) ReleaseCreateAconfigStorageFile() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_CREATE_ACONFIG_STORAGE_FILE")
}
func (c Config) ReleaseUseSystemFeatureBuildFlags() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_USE_SYSTEM_FEATURE_BUILD_FLAGS")
}
func (c Config) ReleaseUseSystemFeatureXmlForUnavailableFeatures() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_USE_SYSTEM_FEATURE_XML_FOR_UNAVAILABLE_FEATURES")
}
func (c Config) ReleaseRustUseArmTargetArchVariant() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_RUST_USE_ARM_TARGET_ARCH_VARIANT")
}
func (c Config) ReleaseUseSparseEncoding() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_SOONG_SPARSE_ENCODING")
}
func (c Config) ReleaseUseUncompressedFonts() bool {
return c.config.productVariables.GetBuildFlagBool("RELEASE_SOONG_UNCOMPRESSED_FONTS")
}
func (c Config) ReleaseAconfigStorageVersion() string {
if val, exists := c.GetBuildFlag("RELEASE_ACONFIG_STORAGE_VERSION"); exists {
return val
} else {
// Default value is 2.
return "2"
}
}
// TODO: b/414412266 Remove this flag after feature released.
func (c Config) ReleaseJarjarFlagsInFramework() bool {
return c.GetBuildFlagBool("RELEASE_JARJAR_FLAGS_IN_FRAMEWORK")
}
func (c Config) ReleaseMainlineBetaNamespaceConfig() string {
if val, exists := c.GetBuildFlag("RELEASE_MAINLINE_BETA_NAMESPACE_CONFIG"); exists {
return val
} else {
return ""
}
}
func (c Config) ReleaseRemoveBetaFlagsFromAconfigFlagsPb() bool {
return c.GetBuildFlagBool("RELEASE_REMOVE_BETA_FLAGS_FROM_ACONFIG_FLAGS_PB")
}
// 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
// envDeps must be a singleton. non-generic and generic configurations share a single
// instance of envDeps.
type envDeps struct {
envLock sync.Mutex
envDeps map[string]string
envFrozen bool
}
// 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
// Flags for Partial Compile, derived from SOONG_PARTIAL_COMPILE.
partialCompileFlags partialCompileFlags
// 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
envDeps *envDeps
// Changes behavior based on whether Kati runs after soong_build, or if soong_build
// runs standalone.
katiEnabled bool
katiSuffix string
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
// If isGeneric is true, this config is the generic config.
isGeneric bool
// InstallPath requires the device name.
// This is only for the installPath.
deviceNameToInstall *string
// Copy of this config struct but some product-specific variables are
// replaced with the generic configuration values.
genericConfigField *config
// modulesForTests stores the list of modules that exist during Soong tests. It is nil
// when not running Soong tests.
modulesForTests *modulesForTests
}
type partialCompileFlags struct {
// Whether to use d8 instead of r8.
// Known issue (b/428178183): Super Partition overflow is probable when
// many outputs are built with this flag.
Use_d8 bool
// Whether to disable stub validation for partial compile builds.
// This is similar to setting `DISABLE_STUB_VALIDATION=true`: the
// validation checks are still created, but are not run by default.
// To run the validation checks, use `m {MODULE_NAME}-stub-validation`.
Disable_stub_validation bool
// Whether to enable incremental java compilation.
Enable_inc_javac bool
// Whether to use the kotlin-incremental-client when compiling .kt files.
Enable_inc_kotlin bool
// Whether to enable incremental d8
Enable_inc_d8 bool
// Whether to enable passing dependencies incrementally from kotlin to java.
Enable_inc_kotlin_java_dep bool
// Whether to enable incremental d8 when outside platform builds.
Enable_inc_d8_outside_platform bool
// Add others as needed.
}
// These are the flags when `SOONG_PARTIAL_COMPILE=false`.
var falsePartialCompileFlags = partialCompileFlags{}
// These are the flags when `SOONG_PARTIAL_COMPILE=true`.
var truePartialCompileFlags = partialCompileFlags{
Use_d8: false,
Disable_stub_validation: true,
Enable_inc_kotlin: true,
Enable_inc_javac: true,
Enable_inc_d8: true,
Enable_inc_kotlin_java_dep: true,
Enable_inc_d8_outside_platform: true,
}
// These are the flags when `SOONG_PARTIAL_COMPILE=all`.
// Include everything from `SOONG_PARTIAL_COMPILE=true`, and flags
// that have known issues.
var allPartialCompileFlags = func() (flags partialCompileFlags) {
flags = truePartialCompileFlags
// b/428178183
flags.Use_d8 = true
return
}()
// These are the flags when `SOONG_PARTIAL_COMPILE=default`.
var defaultPartialCompileFlags = falsePartialCompileFlags
type deviceConfig struct {
config *config
OncePer
}
type jsonConfigurable interface {
SetDefaultConfig()
}
// Parse SOONG_PARTIAL_COMPILE.
//
// SOONG_PARTIAL_COMPILE determines which features are enabled or disabled in
// rule generation. Changing this environment variable causes reanalysis.
//
// SOONG_USE_PARTIAL_COMPILE determines whether or not we **use** PARTIAL_COMPILE.
// Rule generation must support both cases, since changing it does not cause
// reanalysis.
//
// The user-facing documentation shows:
//
// - empty, "false", or "off": disable partial compile completely.
// - "default": "The current default state" This is the value typically assigned in
// `${ANDROID_BUILD_ENVIRONMENT_CONFIG_DIR}/${ANDROID_BUILD_ENVIRONMENT_CONFIG}.json`.
// - "true" or "on": enable all stable partial compile features.
//
// What we actually allow is a comma separated list of tokens, whose first
// character may be "+" (enable) or "-" (disable). If neither is present, "+"
// is assumed. For example, "on,+use_d8" will enable partial compilation, and
// additionally set the use_d8 flag (regardless of whether it is opt-in or
// opt-out).
//
// To add a new feature to the list, add the field in the struct
// `partialCompileFlags` above, and then add the name of the field in the
// switch statement below.
func (c *config) parsePartialCompileFlags(isEngBuild bool) (partialCompileFlags, error) {
if !isEngBuild {
return partialCompileFlags{}, nil
}
value := c.Getenv("SOONG_PARTIAL_COMPILE")
if value == "" {
return partialCompileFlags{}, nil
}
ret := partialCompileFlags{}
tokens := strings.Split(strings.ToLower(value), ",")
makeVal := func(state string) bool {
switch state {
case "-":
return false
case "+":
return true
default:
panic(fmt.Errorf("Invalid state %v in parsePartialCompileFlags.makeVal", state))
}
return false
}
for _, tok := range tokens {
var state string
if len(tok) == 0 {
continue
}
switch tok[0:1] {
case "":
// Ignore empty tokens.
continue
case "-", "+":
state = tok[0:1]
tok = tok[1:]
default:
// Treat `feature` as `+feature`.
state = "+"
}
switch tok {
// Big toggle switches.
case "false":
ret = falsePartialCompileFlags
case "default":
ret = defaultPartialCompileFlags
case "true":
ret = truePartialCompileFlags
case "all":
ret = allPartialCompileFlags
// Individual flags.
case "inc_d8_outside_platform", "enable_inc_d8_outside_platform":
ret.Enable_inc_d8_outside_platform = makeVal(state)
case "disable_inc_d8_outside_platform":
ret.Enable_inc_d8_outside_platform = !makeVal(state)
case "inc_d8", "enable_inc_d8":
ret.Enable_inc_d8 = makeVal(state)
case "disable_inc_d8":
ret.Enable_inc_d8 = !makeVal(state)
case "inc_javac", "enable_inc_javac":
ret.Enable_inc_javac = makeVal(state)
case "disable_inc_javac":
ret.Enable_inc_javac = !makeVal(state)
case "inc_kotlin", "enable_inc_kotlin":
ret.Enable_inc_kotlin = makeVal(state)
case "disable_inc_kotlin":
ret.Enable_inc_kotlin = !makeVal(state)
case "inc_kotlin_java_dep", "enable_inc_kotlin_java_dep":
ret.Enable_inc_kotlin_java_dep = makeVal(state)
case "disable_inc_kotlin_java_dep":
ret.Enable_inc_kotlin_java_dep = !makeVal(state)
case "stub_validation", "enable_stub_validation":
ret.Disable_stub_validation = !makeVal(state)
case "disable_stub_validation":
ret.Disable_stub_validation = makeVal(state)
case "use_d8":
ret.Use_d8 = makeVal(state)
default:
return partialCompileFlags{}, fmt.Errorf("Unknown SOONG_PARTIAL_COMPILE value: %v", tok)
}
}
return ret, nil
}
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)
jsonDecoder.DisallowUnknownFields()
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 nil
}
// 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
}
// 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,
},
}
}
func initConfig(cmdArgs CmdArgs, availableEnv map[string]string) (*config, error) {
// Make a config with default options.
newConfig := &config{
ProductVariablesFileName: cmdArgs.SoongVariables,
env: availableEnv,
outDir: cmdArgs.OutDir,
soongOutDir: cmdArgs.SoongOutDir,
runGoTests: cmdArgs.RunGoTests,
katiSuffix: cmdArgs.KatiSuffix,
multilibConflicts: make(map[ArchType]bool),
moduleListFile: cmdArgs.ModuleListFile,
fs: pathtools.NewOsFs(absSrcDir),
envDeps: &envDeps{},
OncePer: &OncePer{},
buildFromSourceStub: cmdArgs.BuildFromSourceStub,
katiEnabled: cmdArgs.KatiEnabled,
}
variant, ok := os.LookupEnv("TARGET_BUILD_VARIANT")
isEngBuild := !ok || variant == "eng"
newConfig.deviceConfig = &deviceConfig{
config: newConfig,
}
// 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(newConfig)
if err != nil {
return &config{}, err
}
determineBuildOS(newConfig)
// Sets up the map of target OSes to the finer grained compilation targets
// that are configured from the product variables.
targets, err := decodeTargetProductVariables(newConfig)
if err != nil {
return &config{}, err
}
newConfig.partialCompileFlags, err = newConfig.parsePartialCompileFlags(isEngBuild)
if err != nil {
return &config{}, err
}
// Make the CommonOS OsType available for all products.
targets[CommonOS] = []Target{commonTargetMap[CommonOS.Name]}
var archConfig []archConfig
if newConfig.NdkAbis() {
archConfig = getNdkAbisConfig()
} else if newConfig.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 {
newConfig.multilibConflicts[target.Arch.ArchType] = true
}
multilib[target.Arch.ArchType.Multilib] = true
}
// Map of OS to compilation targets.
newConfig.Targets = targets
// Compilation targets for host tools.
newConfig.BuildOSTarget = newConfig.Targets[newConfig.BuildOS][0]
newConfig.BuildOSCommonTarget = getCommonTargets(newConfig.Targets[newConfig.BuildOS])[0]
// Compilation targets for Android.
if len(newConfig.Targets[Android]) > 0 {
newConfig.AndroidCommonTarget = getCommonTargets(newConfig.Targets[Android])[0]
newConfig.AndroidFirstDeviceTarget = FirstTarget(newConfig.Targets[Android], "lib64", "lib32")[0]
}
setBuildMode := func(arg string, mode SoongBuildMode) {
if arg != "" {
if newConfig.BuildMode != AnalysisNoBazel {
fmt.Fprintf(os.Stderr, "buildMode is already set, illegal argument: %s", arg)
os.Exit(1)
}
newConfig.BuildMode = mode
}
}
setBuildMode(cmdArgs.DocFile, GenerateDocFile)
newConfig.productVariables.Build_from_text_stub = boolPtr(newConfig.BuildFromTextStub())
newConfig.deviceNameToInstall = newConfig.productVariables.DeviceName
return newConfig, err
}
// Replace variables in config.productVariables that have tags with "generic" key.
// A generic tag may have a string or an int value for the generic configuration.
// If the value is "unset", generic configuration will unset the variable.
func overrideGenericConfig(config *config) {
config.genericConfigField.isGeneric = true
type_pv := reflect.TypeOf(config.genericConfigField.productVariables)
value_pv := reflect.ValueOf(&config.genericConfigField.productVariables)
for i := range type_pv.NumField() {
type_pv_field := type_pv.Field(i)
generic_value := type_pv_field.Tag.Get("generic")
// If a product variable has an annotation of "generic" tag, use the
// value of the tag to set the generic variable.
if generic_value != "" {
value_pv_field := value_pv.Elem().Field(i)
if generic_value == "unset" {
// unset the product variable
value_pv_field.SetZero()
continue
}
kind_of_type_pv := type_pv_field.Type.Kind()
is_pointer := false
if kind_of_type_pv == reflect.Pointer {
is_pointer = true
kind_of_type_pv = type_pv_field.Type.Elem().Kind()
}
switch kind_of_type_pv {
case reflect.String:
if is_pointer {
value_pv_field.Set(reflect.ValueOf(stringPtr(generic_value)))
} else {
value_pv_field.Set(reflect.ValueOf(generic_value))
}
case reflect.Int:
generic_int, err := strconv.Atoi(generic_value)
if err != nil {
panic(fmt.Errorf("Only an int value can be assigned to int variable: %s", err))
}
if is_pointer {
value_pv_field.Set(reflect.ValueOf(intPtr(generic_int)))
} else {
value_pv_field.Set(reflect.ValueOf(generic_int))
}
default:
panic(fmt.Errorf("Unknown type to replace for generic variable: %s", &kind_of_type_pv))
}
}
}
// envDeps and OncePer must be singletons.
config.genericConfigField.envDeps = config.envDeps
config.genericConfigField.OncePer = config.OncePer
// keep the device name to get the install path.
config.genericConfigField.deviceNameToInstall = config.deviceNameToInstall
}
// NewConfig creates a new Config object. It also loads the config file, if
// found. The Config object includes a duplicated Config object in it for the
// generic configuration that does not provide any product specific information.
func NewConfig(cmdArgs CmdArgs, availableEnv map[string]string) (Config, error) {
config, err := initConfig(cmdArgs, availableEnv)
if err != nil {
return Config{}, err
}
// Initialize generic configuration.
config.genericConfigField, err = initConfig(cmdArgs, availableEnv)
// Update product specific variables with the generic configuration.
overrideGenericConfig(config)
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)
c.genericConfigField.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 {
return filepath.Join(c.outDir, "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
}