config.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package android
  15. // This is the primary location to write and read all configuration values and
  16. // product variables necessary for soong_build's operation.
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "fmt"
  21. "io/ioutil"
  22. "os"
  23. "path/filepath"
  24. "reflect"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "github.com/google/blueprint"
  30. "github.com/google/blueprint/bootstrap"
  31. "github.com/google/blueprint/pathtools"
  32. "github.com/google/blueprint/proptools"
  33. "android/soong/android/soongconfig"
  34. "android/soong/bazel"
  35. "android/soong/remoteexec"
  36. "android/soong/starlark_fmt"
  37. )
  38. // Bool re-exports proptools.Bool for the android package.
  39. var Bool = proptools.Bool
  40. // String re-exports proptools.String for the android package.
  41. var String = proptools.String
  42. // StringDefault re-exports proptools.StringDefault for the android package.
  43. var StringDefault = proptools.StringDefault
  44. // FutureApiLevelInt is a placeholder constant for unreleased API levels.
  45. const FutureApiLevelInt = 10000
  46. // FutureApiLevel represents unreleased API levels.
  47. var FutureApiLevel = ApiLevel{
  48. value: "current",
  49. number: FutureApiLevelInt,
  50. isPreview: true,
  51. }
  52. // The product variables file name, containing product config from Kati.
  53. const productVariablesFileName = "soong.variables"
  54. // A Config object represents the entire build configuration for Android.
  55. type Config struct {
  56. *config
  57. }
  58. type SoongBuildMode int
  59. // Build modes that soong_build can run as.
  60. const (
  61. // Don't use bazel at all during module analysis.
  62. AnalysisNoBazel SoongBuildMode = iota
  63. // Symlink fores mode: merge two directory trees into a symlink forest
  64. SymlinkForest
  65. // Bp2build mode: Generate BUILD files from blueprint files and exit.
  66. Bp2build
  67. // Generate BUILD files which faithfully represent the dependency graph of
  68. // blueprint modules. Individual BUILD targets will not, however, faitfhully
  69. // express build semantics.
  70. GenerateQueryView
  71. // Generate BUILD files for API contributions to API surfaces
  72. ApiBp2build
  73. // Create a JSON representation of the module graph and exit.
  74. GenerateModuleGraph
  75. // Generate a documentation file for module type definitions and exit.
  76. GenerateDocFile
  77. // Use bazel during analysis of many allowlisted build modules. The allowlist
  78. // is considered a "developer mode" allowlist, as some modules may be
  79. // allowlisted on an experimental basis.
  80. BazelDevMode
  81. // Use bazel during analysis of a few allowlisted build modules. The allowlist
  82. // is considered "staging, as these are modules being prepared to be released
  83. // into prod mode shortly after.
  84. BazelStagingMode
  85. // Use bazel during analysis of build modules from an allowlist carefully
  86. // curated by the build team to be proven stable.
  87. BazelProdMode
  88. )
  89. // SoongOutDir returns the build output directory for the configuration.
  90. func (c Config) SoongOutDir() string {
  91. return c.soongOutDir
  92. }
  93. func (c Config) OutDir() string {
  94. return c.outDir
  95. }
  96. func (c Config) RunGoTests() bool {
  97. return c.runGoTests
  98. }
  99. func (c Config) DebugCompilation() bool {
  100. return false // Never compile Go code in the main build for debugging
  101. }
  102. func (c Config) Subninjas() []string {
  103. return []string{}
  104. }
  105. func (c Config) PrimaryBuilderInvocations() []bootstrap.PrimaryBuilderInvocation {
  106. return []bootstrap.PrimaryBuilderInvocation{}
  107. }
  108. // RunningInsideUnitTest returns true if this code is being run as part of a Soong unit test.
  109. func (c Config) RunningInsideUnitTest() bool {
  110. return c.config.TestProductVariables != nil
  111. }
  112. // A DeviceConfig object represents the configuration for a particular device
  113. // being built. For now there will only be one of these, but in the future there
  114. // may be multiple devices being built.
  115. type DeviceConfig struct {
  116. *deviceConfig
  117. }
  118. // VendorConfig represents the configuration for vendor-specific behavior.
  119. type VendorConfig soongconfig.SoongConfig
  120. // Definition of general build configuration for soong_build. Some of these
  121. // product configuration values are read from Kati-generated soong.variables.
  122. type config struct {
  123. // Options configurable with soong.variables
  124. productVariables productVariables
  125. // Only available on configs created by TestConfig
  126. TestProductVariables *productVariables
  127. // A specialized context object for Bazel/Soong mixed builds and migration
  128. // purposes.
  129. BazelContext BazelContext
  130. ProductVariablesFileName string
  131. // BuildOS stores the OsType for the OS that the build is running on.
  132. BuildOS OsType
  133. // BuildArch stores the ArchType for the CPU that the build is running on.
  134. BuildArch ArchType
  135. Targets map[OsType][]Target
  136. BuildOSTarget Target // the Target for tools run on the build machine
  137. BuildOSCommonTarget Target // the Target for common (java) tools run on the build machine
  138. AndroidCommonTarget Target // the Target for common modules for the Android device
  139. AndroidFirstDeviceTarget Target // the first Target for modules for the Android device
  140. // multilibConflicts for an ArchType is true if there is earlier configured
  141. // device architecture with the same multilib value.
  142. multilibConflicts map[ArchType]bool
  143. deviceConfig *deviceConfig
  144. outDir string // The output directory (usually out/)
  145. soongOutDir string
  146. moduleListFile string // the path to the file which lists blueprint files to parse.
  147. runGoTests bool
  148. env map[string]string
  149. envLock sync.Mutex
  150. envDeps map[string]string
  151. envFrozen bool
  152. // Changes behavior based on whether Kati runs after soong_build, or if soong_build
  153. // runs standalone.
  154. katiEnabled bool
  155. captureBuild bool // true for tests, saves build parameters for each module
  156. ignoreEnvironment bool // true for tests, returns empty from all Getenv calls
  157. fs pathtools.FileSystem
  158. mockBpList string
  159. BuildMode SoongBuildMode
  160. Bp2buildPackageConfig Bp2BuildConversionAllowlist
  161. Bp2buildSoongConfigDefinitions soongconfig.Bp2BuildSoongConfigDefinitions
  162. // If testAllowNonExistentPaths is true then PathForSource and PathForModuleSrc won't error
  163. // in tests when a path doesn't exist.
  164. TestAllowNonExistentPaths bool
  165. // The list of files that when changed, must invalidate soong_build to
  166. // regenerate build.ninja.
  167. ninjaFileDepsSet sync.Map
  168. OncePer
  169. // These fields are only used for metrics collection. A module should be added
  170. // to these maps only if its implementation supports Bazel handling in mixed
  171. // builds. A module being in the "enabled" list indicates that there is a
  172. // variant of that module for which bazel-handling actually took place.
  173. // A module being in the "disabled" list indicates that there is a variant of
  174. // that module for which bazel-handling was denied.
  175. mixedBuildsLock sync.Mutex
  176. mixedBuildEnabledModules map[string]struct{}
  177. mixedBuildDisabledModules map[string]struct{}
  178. }
  179. type deviceConfig struct {
  180. config *config
  181. OncePer
  182. }
  183. type jsonConfigurable interface {
  184. SetDefaultConfig()
  185. }
  186. func loadConfig(config *config) error {
  187. return loadFromConfigFile(&config.productVariables, absolutePath(config.ProductVariablesFileName))
  188. }
  189. // loadFromConfigFile loads and decodes configuration options from a JSON file
  190. // in the current working directory.
  191. func loadFromConfigFile(configurable *productVariables, filename string) error {
  192. // Try to open the file
  193. configFileReader, err := os.Open(filename)
  194. defer configFileReader.Close()
  195. if os.IsNotExist(err) {
  196. // Need to create a file, so that blueprint & ninja don't get in
  197. // a dependency tracking loop.
  198. // Make a file-configurable-options with defaults, write it out using
  199. // a json writer.
  200. configurable.SetDefaultConfig()
  201. err = saveToConfigFile(configurable, filename)
  202. if err != nil {
  203. return err
  204. }
  205. } else if err != nil {
  206. return fmt.Errorf("config file: could not open %s: %s", filename, err.Error())
  207. } else {
  208. // Make a decoder for it
  209. jsonDecoder := json.NewDecoder(configFileReader)
  210. err = jsonDecoder.Decode(configurable)
  211. if err != nil {
  212. return fmt.Errorf("config file: %s did not parse correctly: %s", filename, err.Error())
  213. }
  214. }
  215. if Bool(configurable.GcovCoverage) && Bool(configurable.ClangCoverage) {
  216. return fmt.Errorf("GcovCoverage and ClangCoverage cannot both be set")
  217. }
  218. configurable.Native_coverage = proptools.BoolPtr(
  219. Bool(configurable.GcovCoverage) ||
  220. Bool(configurable.ClangCoverage))
  221. // when Platform_sdk_final is true (or PLATFORM_VERSION_CODENAME is REL), use Platform_sdk_version;
  222. // if false (pre-released version, for example), use Platform_sdk_codename.
  223. if Bool(configurable.Platform_sdk_final) {
  224. if configurable.Platform_sdk_version != nil {
  225. configurable.Platform_sdk_version_or_codename =
  226. proptools.StringPtr(strconv.Itoa(*(configurable.Platform_sdk_version)))
  227. } else {
  228. return fmt.Errorf("Platform_sdk_version cannot be pointed by a NULL pointer")
  229. }
  230. } else {
  231. configurable.Platform_sdk_version_or_codename =
  232. proptools.StringPtr(String(configurable.Platform_sdk_codename))
  233. }
  234. return saveToBazelConfigFile(configurable, filepath.Dir(filename))
  235. }
  236. // atomically writes the config file in case two copies of soong_build are running simultaneously
  237. // (for example, docs generation and ninja manifest generation)
  238. func saveToConfigFile(config *productVariables, filename string) error {
  239. data, err := json.MarshalIndent(&config, "", " ")
  240. if err != nil {
  241. return fmt.Errorf("cannot marshal config data: %s", err.Error())
  242. }
  243. f, err := ioutil.TempFile(filepath.Dir(filename), "config")
  244. if err != nil {
  245. return fmt.Errorf("cannot create empty config file %s: %s", filename, err.Error())
  246. }
  247. defer os.Remove(f.Name())
  248. defer f.Close()
  249. _, err = f.Write(data)
  250. if err != nil {
  251. return fmt.Errorf("default config file: %s could not be written: %s", filename, err.Error())
  252. }
  253. _, err = f.WriteString("\n")
  254. if err != nil {
  255. return fmt.Errorf("default config file: %s could not be written: %s", filename, err.Error())
  256. }
  257. f.Close()
  258. os.Rename(f.Name(), filename)
  259. return nil
  260. }
  261. func saveToBazelConfigFile(config *productVariables, outDir string) error {
  262. dir := filepath.Join(outDir, bazel.SoongInjectionDirName, "product_config")
  263. err := createDirIfNonexistent(dir, os.ModePerm)
  264. if err != nil {
  265. return fmt.Errorf("Could not create dir %s: %s", dir, err)
  266. }
  267. nonArchVariantProductVariables := []string{}
  268. archVariantProductVariables := []string{}
  269. p := variableProperties{}
  270. t := reflect.TypeOf(p.Product_variables)
  271. for i := 0; i < t.NumField(); i++ {
  272. f := t.Field(i)
  273. nonArchVariantProductVariables = append(nonArchVariantProductVariables, strings.ToLower(f.Name))
  274. if proptools.HasTag(f, "android", "arch_variant") {
  275. archVariantProductVariables = append(archVariantProductVariables, strings.ToLower(f.Name))
  276. }
  277. }
  278. nonArchVariantProductVariablesJson := starlark_fmt.PrintStringList(nonArchVariantProductVariables, 0)
  279. if err != nil {
  280. return fmt.Errorf("cannot marshal product variable data: %s", err.Error())
  281. }
  282. archVariantProductVariablesJson := starlark_fmt.PrintStringList(archVariantProductVariables, 0)
  283. if err != nil {
  284. return fmt.Errorf("cannot marshal arch variant product variable data: %s", err.Error())
  285. }
  286. configJson, err := json.MarshalIndent(&config, "", " ")
  287. if err != nil {
  288. return fmt.Errorf("cannot marshal config data: %s", err.Error())
  289. }
  290. // The backslashes need to be escaped because this text is going to be put
  291. // inside a Starlark string literal.
  292. configJson = bytes.ReplaceAll(configJson, []byte("\\"), []byte("\\\\"))
  293. bzl := []string{
  294. bazel.GeneratedBazelFileWarning,
  295. fmt.Sprintf(`_product_vars = json.decode("""%s""")`, configJson),
  296. fmt.Sprintf(`_product_var_constraints = %s`, nonArchVariantProductVariablesJson),
  297. fmt.Sprintf(`_arch_variant_product_var_constraints = %s`, archVariantProductVariablesJson),
  298. "\n", `
  299. product_vars = _product_vars
  300. product_var_constraints = _product_var_constraints
  301. arch_variant_product_var_constraints = _arch_variant_product_var_constraints
  302. `,
  303. }
  304. err = os.WriteFile(filepath.Join(dir, "product_variables.bzl"), []byte(strings.Join(bzl, "\n")), 0644)
  305. if err != nil {
  306. return fmt.Errorf("Could not write .bzl config file %s", err)
  307. }
  308. err = os.WriteFile(filepath.Join(dir, "BUILD"), []byte(bazel.GeneratedBazelFileWarning), 0644)
  309. if err != nil {
  310. return fmt.Errorf("Could not write BUILD config file %s", err)
  311. }
  312. return nil
  313. }
  314. // NullConfig returns a mostly empty Config for use by standalone tools like dexpreopt_gen that
  315. // use the android package.
  316. func NullConfig(outDir, soongOutDir string) Config {
  317. return Config{
  318. config: &config{
  319. outDir: outDir,
  320. soongOutDir: soongOutDir,
  321. fs: pathtools.OsFs,
  322. },
  323. }
  324. }
  325. // NewConfig creates a new Config object. The srcDir argument specifies the path
  326. // to the root source directory. It also loads the config file, if found.
  327. func NewConfig(moduleListFile string, buildMode SoongBuildMode, runGoTests bool, outDir, soongOutDir string, availableEnv map[string]string) (Config, error) {
  328. // Make a config with default options.
  329. config := &config{
  330. ProductVariablesFileName: filepath.Join(soongOutDir, productVariablesFileName),
  331. env: availableEnv,
  332. outDir: outDir,
  333. soongOutDir: soongOutDir,
  334. runGoTests: runGoTests,
  335. multilibConflicts: make(map[ArchType]bool),
  336. moduleListFile: moduleListFile,
  337. fs: pathtools.NewOsFs(absSrcDir),
  338. mixedBuildDisabledModules: make(map[string]struct{}),
  339. mixedBuildEnabledModules: make(map[string]struct{}),
  340. }
  341. config.deviceConfig = &deviceConfig{
  342. config: config,
  343. }
  344. // Soundness check of the build and source directories. This won't catch strange
  345. // configurations with symlinks, but at least checks the obvious case.
  346. absBuildDir, err := filepath.Abs(soongOutDir)
  347. if err != nil {
  348. return Config{}, err
  349. }
  350. absSrcDir, err := filepath.Abs(".")
  351. if err != nil {
  352. return Config{}, err
  353. }
  354. if strings.HasPrefix(absSrcDir, absBuildDir) {
  355. return Config{}, fmt.Errorf("Build dir must not contain source directory")
  356. }
  357. // Load any configurable options from the configuration file
  358. err = loadConfig(config)
  359. if err != nil {
  360. return Config{}, err
  361. }
  362. KatiEnabledMarkerFile := filepath.Join(soongOutDir, ".soong.kati_enabled")
  363. if _, err := os.Stat(absolutePath(KatiEnabledMarkerFile)); err == nil {
  364. config.katiEnabled = true
  365. }
  366. determineBuildOS(config)
  367. // Sets up the map of target OSes to the finer grained compilation targets
  368. // that are configured from the product variables.
  369. targets, err := decodeTargetProductVariables(config)
  370. if err != nil {
  371. return Config{}, err
  372. }
  373. // Make the CommonOS OsType available for all products.
  374. targets[CommonOS] = []Target{commonTargetMap[CommonOS.Name]}
  375. var archConfig []archConfig
  376. if config.NdkAbis() {
  377. archConfig = getNdkAbisConfig()
  378. } else if config.AmlAbis() {
  379. archConfig = getAmlAbisConfig()
  380. }
  381. if archConfig != nil {
  382. androidTargets, err := decodeAndroidArchSettings(archConfig)
  383. if err != nil {
  384. return Config{}, err
  385. }
  386. targets[Android] = androidTargets
  387. }
  388. multilib := make(map[string]bool)
  389. for _, target := range targets[Android] {
  390. if seen := multilib[target.Arch.ArchType.Multilib]; seen {
  391. config.multilibConflicts[target.Arch.ArchType] = true
  392. }
  393. multilib[target.Arch.ArchType.Multilib] = true
  394. }
  395. // Map of OS to compilation targets.
  396. config.Targets = targets
  397. // Compilation targets for host tools.
  398. config.BuildOSTarget = config.Targets[config.BuildOS][0]
  399. config.BuildOSCommonTarget = getCommonTargets(config.Targets[config.BuildOS])[0]
  400. // Compilation targets for Android.
  401. if len(config.Targets[Android]) > 0 {
  402. config.AndroidCommonTarget = getCommonTargets(config.Targets[Android])[0]
  403. config.AndroidFirstDeviceTarget = FirstTarget(config.Targets[Android], "lib64", "lib32")[0]
  404. }
  405. config.BuildMode = buildMode
  406. config.BazelContext, err = NewBazelContext(config)
  407. config.Bp2buildPackageConfig = GetBp2BuildAllowList()
  408. return Config{config}, err
  409. }
  410. // mockFileSystem replaces all reads with accesses to the provided map of
  411. // filenames to contents stored as a byte slice.
  412. func (c *config) mockFileSystem(bp string, fs map[string][]byte) {
  413. mockFS := map[string][]byte{}
  414. if _, exists := mockFS["Android.bp"]; !exists {
  415. mockFS["Android.bp"] = []byte(bp)
  416. }
  417. for k, v := range fs {
  418. mockFS[k] = v
  419. }
  420. // no module list file specified; find every file named Blueprints or Android.bp
  421. pathsToParse := []string{}
  422. for candidate := range mockFS {
  423. base := filepath.Base(candidate)
  424. if base == "Android.bp" {
  425. pathsToParse = append(pathsToParse, candidate)
  426. }
  427. }
  428. if len(pathsToParse) < 1 {
  429. panic(fmt.Sprintf("No Blueprint or Android.bp files found in mock filesystem: %v\n", mockFS))
  430. }
  431. mockFS[blueprint.MockModuleListFile] = []byte(strings.Join(pathsToParse, "\n"))
  432. c.fs = pathtools.MockFs(mockFS)
  433. c.mockBpList = blueprint.MockModuleListFile
  434. }
  435. // Returns true if "Bazel builds" is enabled. In this mode, part of build
  436. // analysis is handled by Bazel.
  437. func (c *config) IsMixedBuildsEnabled() bool {
  438. return c.BuildMode == BazelProdMode || c.BuildMode == BazelDevMode
  439. }
  440. func (c *config) SetAllowMissingDependencies() {
  441. c.productVariables.Allow_missing_dependencies = proptools.BoolPtr(true)
  442. }
  443. // BlueprintToolLocation returns the directory containing build system tools
  444. // from Blueprint, like soong_zip and merge_zips.
  445. func (c *config) HostToolDir() string {
  446. if c.KatiEnabled() {
  447. return filepath.Join(c.outDir, "host", c.PrebuiltOS(), "bin")
  448. } else {
  449. return filepath.Join(c.soongOutDir, "host", c.PrebuiltOS(), "bin")
  450. }
  451. }
  452. func (c *config) HostToolPath(ctx PathContext, tool string) Path {
  453. path := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin", false, tool)
  454. return path
  455. }
  456. func (c *config) HostJNIToolPath(ctx PathContext, lib string) Path {
  457. ext := ".so"
  458. if runtime.GOOS == "darwin" {
  459. ext = ".dylib"
  460. }
  461. path := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "lib64", false, lib+ext)
  462. return path
  463. }
  464. func (c *config) HostJavaToolPath(ctx PathContext, tool string) Path {
  465. path := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "framework", false, tool)
  466. return path
  467. }
  468. // PrebuiltOS returns the name of the host OS used in prebuilts directories.
  469. func (c *config) PrebuiltOS() string {
  470. switch runtime.GOOS {
  471. case "linux":
  472. return "linux-x86"
  473. case "darwin":
  474. return "darwin-x86"
  475. default:
  476. panic("Unknown GOOS")
  477. }
  478. }
  479. // GoRoot returns the path to the root directory of the Go toolchain.
  480. func (c *config) GoRoot() string {
  481. return fmt.Sprintf("prebuilts/go/%s", c.PrebuiltOS())
  482. }
  483. // PrebuiltBuildTool returns the path to a tool in the prebuilts directory containing
  484. // checked-in tools, like Kati, Ninja or Toybox, for the current host OS.
  485. func (c *config) PrebuiltBuildTool(ctx PathContext, tool string) Path {
  486. return PathForSource(ctx, "prebuilts/build-tools", c.PrebuiltOS(), "bin", tool)
  487. }
  488. // CpPreserveSymlinksFlags returns the host-specific flag for the cp(1) command
  489. // to preserve symlinks.
  490. func (c *config) CpPreserveSymlinksFlags() string {
  491. switch runtime.GOOS {
  492. case "darwin":
  493. return "-R"
  494. case "linux":
  495. return "-d"
  496. default:
  497. return ""
  498. }
  499. }
  500. func (c *config) Getenv(key string) string {
  501. var val string
  502. var exists bool
  503. c.envLock.Lock()
  504. defer c.envLock.Unlock()
  505. if c.envDeps == nil {
  506. c.envDeps = make(map[string]string)
  507. }
  508. if val, exists = c.envDeps[key]; !exists {
  509. if c.envFrozen {
  510. panic("Cannot access new environment variables after envdeps are frozen")
  511. }
  512. val, _ = c.env[key]
  513. c.envDeps[key] = val
  514. }
  515. return val
  516. }
  517. func (c *config) GetenvWithDefault(key string, defaultValue string) string {
  518. ret := c.Getenv(key)
  519. if ret == "" {
  520. return defaultValue
  521. }
  522. return ret
  523. }
  524. func (c *config) IsEnvTrue(key string) bool {
  525. value := c.Getenv(key)
  526. return value == "1" || value == "y" || value == "yes" || value == "on" || value == "true"
  527. }
  528. func (c *config) IsEnvFalse(key string) bool {
  529. value := c.Getenv(key)
  530. return value == "0" || value == "n" || value == "no" || value == "off" || value == "false"
  531. }
  532. func (c *config) TargetsJava17() bool {
  533. return c.IsEnvTrue("EXPERIMENTAL_TARGET_JAVA_VERSION_17")
  534. }
  535. // EnvDeps returns the environment variables this build depends on. The first
  536. // call to this function blocks future reads from the environment.
  537. func (c *config) EnvDeps() map[string]string {
  538. c.envLock.Lock()
  539. defer c.envLock.Unlock()
  540. c.envFrozen = true
  541. return c.envDeps
  542. }
  543. func (c *config) KatiEnabled() bool {
  544. return c.katiEnabled
  545. }
  546. func (c *config) BuildId() string {
  547. return String(c.productVariables.BuildId)
  548. }
  549. // BuildNumberFile returns the path to a text file containing metadata
  550. // representing the current build's number.
  551. //
  552. // Rules that want to reference the build number should read from this file
  553. // without depending on it. They will run whenever their other dependencies
  554. // require them to run and get the current build number. This ensures they don't
  555. // rebuild on every incremental build when the build number changes.
  556. func (c *config) BuildNumberFile(ctx PathContext) Path {
  557. return PathForOutput(ctx, String(c.productVariables.BuildNumberFile))
  558. }
  559. // DeviceName returns the name of the current device target.
  560. // TODO: take an AndroidModuleContext to select the device name for multi-device builds
  561. func (c *config) DeviceName() string {
  562. return *c.productVariables.DeviceName
  563. }
  564. // DeviceProduct returns the current product target. There could be multiple of
  565. // these per device type.
  566. //
  567. // NOTE: Do not base conditional logic on this value. It may break product inheritance.
  568. func (c *config) DeviceProduct() string {
  569. return *c.productVariables.DeviceProduct
  570. }
  571. func (c *config) DeviceResourceOverlays() []string {
  572. return c.productVariables.DeviceResourceOverlays
  573. }
  574. func (c *config) ProductResourceOverlays() []string {
  575. return c.productVariables.ProductResourceOverlays
  576. }
  577. func (c *config) PlatformVersionName() string {
  578. return String(c.productVariables.Platform_version_name)
  579. }
  580. func (c *config) PlatformSdkVersion() ApiLevel {
  581. return uncheckedFinalApiLevel(*c.productVariables.Platform_sdk_version)
  582. }
  583. func (c *config) PlatformSdkFinal() bool {
  584. return Bool(c.productVariables.Platform_sdk_final)
  585. }
  586. func (c *config) PlatformSdkCodename() string {
  587. return String(c.productVariables.Platform_sdk_codename)
  588. }
  589. func (c *config) PlatformSdkExtensionVersion() int {
  590. return *c.productVariables.Platform_sdk_extension_version
  591. }
  592. func (c *config) PlatformBaseSdkExtensionVersion() int {
  593. return *c.productVariables.Platform_base_sdk_extension_version
  594. }
  595. func (c *config) PlatformSecurityPatch() string {
  596. return String(c.productVariables.Platform_security_patch)
  597. }
  598. func (c *config) PlatformPreviewSdkVersion() string {
  599. return String(c.productVariables.Platform_preview_sdk_version)
  600. }
  601. func (c *config) PlatformMinSupportedTargetSdkVersion() string {
  602. return String(c.productVariables.Platform_min_supported_target_sdk_version)
  603. }
  604. func (c *config) PlatformBaseOS() string {
  605. return String(c.productVariables.Platform_base_os)
  606. }
  607. func (c *config) PlatformVersionLastStable() string {
  608. return String(c.productVariables.Platform_version_last_stable)
  609. }
  610. func (c *config) PlatformVersionKnownCodenames() string {
  611. return String(c.productVariables.Platform_version_known_codenames)
  612. }
  613. func (c *config) MinSupportedSdkVersion() ApiLevel {
  614. return uncheckedFinalApiLevel(21)
  615. }
  616. func (c *config) FinalApiLevels() []ApiLevel {
  617. var levels []ApiLevel
  618. for i := 1; i <= c.PlatformSdkVersion().FinalOrFutureInt(); i++ {
  619. levels = append(levels, uncheckedFinalApiLevel(i))
  620. }
  621. return levels
  622. }
  623. func (c *config) PreviewApiLevels() []ApiLevel {
  624. var levels []ApiLevel
  625. for i, codename := range c.PlatformVersionActiveCodenames() {
  626. levels = append(levels, ApiLevel{
  627. value: codename,
  628. number: i,
  629. isPreview: true,
  630. })
  631. }
  632. return levels
  633. }
  634. func (c *config) LatestPreviewApiLevel() ApiLevel {
  635. level := NoneApiLevel
  636. for _, l := range c.PreviewApiLevels() {
  637. if l.GreaterThan(level) {
  638. level = l
  639. }
  640. }
  641. return level
  642. }
  643. func (c *config) AllSupportedApiLevels() []ApiLevel {
  644. var levels []ApiLevel
  645. levels = append(levels, c.FinalApiLevels()...)
  646. return append(levels, c.PreviewApiLevels()...)
  647. }
  648. // DefaultAppTargetSdk returns the API level that platform apps are targeting.
  649. // This converts a codename to the exact ApiLevel it represents.
  650. func (c *config) DefaultAppTargetSdk(ctx EarlyModuleContext) ApiLevel {
  651. if Bool(c.productVariables.Platform_sdk_final) {
  652. return c.PlatformSdkVersion()
  653. }
  654. codename := c.PlatformSdkCodename()
  655. if codename == "" {
  656. return NoneApiLevel
  657. }
  658. if codename == "REL" {
  659. panic("Platform_sdk_codename should not be REL when Platform_sdk_final is true")
  660. }
  661. return ApiLevelOrPanic(ctx, codename)
  662. }
  663. func (c *config) AppsDefaultVersionName() string {
  664. return String(c.productVariables.AppsDefaultVersionName)
  665. }
  666. // Codenames that are active in the current lunch target.
  667. func (c *config) PlatformVersionActiveCodenames() []string {
  668. return c.productVariables.Platform_version_active_codenames
  669. }
  670. func (c *config) ProductAAPTConfig() []string {
  671. return c.productVariables.AAPTConfig
  672. }
  673. func (c *config) ProductAAPTPreferredConfig() string {
  674. return String(c.productVariables.AAPTPreferredConfig)
  675. }
  676. func (c *config) ProductAAPTCharacteristics() string {
  677. return String(c.productVariables.AAPTCharacteristics)
  678. }
  679. func (c *config) ProductAAPTPrebuiltDPI() []string {
  680. return c.productVariables.AAPTPrebuiltDPI
  681. }
  682. func (c *config) DefaultAppCertificateDir(ctx PathContext) SourcePath {
  683. defaultCert := String(c.productVariables.DefaultAppCertificate)
  684. if defaultCert != "" {
  685. return PathForSource(ctx, filepath.Dir(defaultCert))
  686. }
  687. return PathForSource(ctx, "build/make/target/product/security")
  688. }
  689. func (c *config) DefaultAppCertificate(ctx PathContext) (pem, key SourcePath) {
  690. defaultCert := String(c.productVariables.DefaultAppCertificate)
  691. if defaultCert != "" {
  692. return PathForSource(ctx, defaultCert+".x509.pem"), PathForSource(ctx, defaultCert+".pk8")
  693. }
  694. defaultDir := c.DefaultAppCertificateDir(ctx)
  695. return defaultDir.Join(ctx, "testkey.x509.pem"), defaultDir.Join(ctx, "testkey.pk8")
  696. }
  697. func (c *config) ApexKeyDir(ctx ModuleContext) SourcePath {
  698. // TODO(b/121224311): define another variable such as TARGET_APEX_KEY_OVERRIDE
  699. defaultCert := String(c.productVariables.DefaultAppCertificate)
  700. if defaultCert == "" || filepath.Dir(defaultCert) == "build/make/target/product/security" {
  701. // When defaultCert is unset or is set to the testkeys path, use the APEX keys
  702. // that is under the module dir
  703. return pathForModuleSrc(ctx)
  704. }
  705. // If not, APEX keys are under the specified directory
  706. return PathForSource(ctx, filepath.Dir(defaultCert))
  707. }
  708. // Certificate for the NetworkStack sepolicy context
  709. func (c *config) MainlineSepolicyDevCertificatesDir(ctx ModuleContext) SourcePath {
  710. cert := String(c.productVariables.MainlineSepolicyDevCertificates)
  711. if cert != "" {
  712. return PathForSource(ctx, cert)
  713. }
  714. return c.DefaultAppCertificateDir(ctx)
  715. }
  716. // AllowMissingDependencies configures Blueprint/Soong to not fail when modules
  717. // are configured to depend on non-existent modules. Note that this does not
  718. // affect missing input dependencies at the Ninja level.
  719. func (c *config) AllowMissingDependencies() bool {
  720. return Bool(c.productVariables.Allow_missing_dependencies)
  721. }
  722. // Returns true if a full platform source tree cannot be assumed.
  723. func (c *config) UnbundledBuild() bool {
  724. return Bool(c.productVariables.Unbundled_build)
  725. }
  726. // Returns true if building apps that aren't bundled with the platform.
  727. // UnbundledBuild() is always true when this is true.
  728. func (c *config) UnbundledBuildApps() bool {
  729. return len(c.productVariables.Unbundled_build_apps) > 0
  730. }
  731. // Returns true if building image that aren't bundled with the platform.
  732. // UnbundledBuild() is always true when this is true.
  733. func (c *config) UnbundledBuildImage() bool {
  734. return Bool(c.productVariables.Unbundled_build_image)
  735. }
  736. // Returns true if building modules against prebuilt SDKs.
  737. func (c *config) AlwaysUsePrebuiltSdks() bool {
  738. return Bool(c.productVariables.Always_use_prebuilt_sdks)
  739. }
  740. func (c *config) MinimizeJavaDebugInfo() bool {
  741. return Bool(c.productVariables.MinimizeJavaDebugInfo) && !Bool(c.productVariables.Eng)
  742. }
  743. func (c *config) Debuggable() bool {
  744. return Bool(c.productVariables.Debuggable)
  745. }
  746. func (c *config) Eng() bool {
  747. return Bool(c.productVariables.Eng)
  748. }
  749. // DevicePrimaryArchType returns the ArchType for the first configured device architecture, or
  750. // Common if there are no device architectures.
  751. func (c *config) DevicePrimaryArchType() ArchType {
  752. if androidTargets := c.Targets[Android]; len(androidTargets) > 0 {
  753. return androidTargets[0].Arch.ArchType
  754. }
  755. return Common
  756. }
  757. func (c *config) SanitizeHost() []string {
  758. return append([]string(nil), c.productVariables.SanitizeHost...)
  759. }
  760. func (c *config) SanitizeDevice() []string {
  761. return append([]string(nil), c.productVariables.SanitizeDevice...)
  762. }
  763. func (c *config) SanitizeDeviceDiag() []string {
  764. return append([]string(nil), c.productVariables.SanitizeDeviceDiag...)
  765. }
  766. func (c *config) SanitizeDeviceArch() []string {
  767. return append([]string(nil), c.productVariables.SanitizeDeviceArch...)
  768. }
  769. func (c *config) EnableCFI() bool {
  770. if c.productVariables.EnableCFI == nil {
  771. return true
  772. }
  773. return *c.productVariables.EnableCFI
  774. }
  775. func (c *config) DisableScudo() bool {
  776. return Bool(c.productVariables.DisableScudo)
  777. }
  778. func (c *config) Android64() bool {
  779. for _, t := range c.Targets[Android] {
  780. if t.Arch.ArchType.Multilib == "lib64" {
  781. return true
  782. }
  783. }
  784. return false
  785. }
  786. func (c *config) UseGoma() bool {
  787. return Bool(c.productVariables.UseGoma)
  788. }
  789. func (c *config) UseRBE() bool {
  790. return Bool(c.productVariables.UseRBE)
  791. }
  792. func (c *config) UseRBEJAVAC() bool {
  793. return Bool(c.productVariables.UseRBEJAVAC)
  794. }
  795. func (c *config) UseRBER8() bool {
  796. return Bool(c.productVariables.UseRBER8)
  797. }
  798. func (c *config) UseRBED8() bool {
  799. return Bool(c.productVariables.UseRBED8)
  800. }
  801. func (c *config) UseRemoteBuild() bool {
  802. return c.UseGoma() || c.UseRBE()
  803. }
  804. func (c *config) RunErrorProne() bool {
  805. return c.IsEnvTrue("RUN_ERROR_PRONE")
  806. }
  807. // XrefCorpusName returns the Kythe cross-reference corpus name.
  808. func (c *config) XrefCorpusName() string {
  809. return c.Getenv("XREF_CORPUS")
  810. }
  811. // XrefCuEncoding returns the compilation unit encoding to use for Kythe code
  812. // xrefs. Can be 'json' (default), 'proto' or 'all'.
  813. func (c *config) XrefCuEncoding() string {
  814. if enc := c.Getenv("KYTHE_KZIP_ENCODING"); enc != "" {
  815. return enc
  816. }
  817. return "json"
  818. }
  819. // XrefCuJavaSourceMax returns the maximum number of the Java source files
  820. // in a single compilation unit
  821. const xrefJavaSourceFileMaxDefault = "1000"
  822. func (c Config) XrefCuJavaSourceMax() string {
  823. v := c.Getenv("KYTHE_JAVA_SOURCE_BATCH_SIZE")
  824. if v == "" {
  825. return xrefJavaSourceFileMaxDefault
  826. }
  827. if _, err := strconv.ParseUint(v, 0, 0); err != nil {
  828. fmt.Fprintf(os.Stderr,
  829. "bad KYTHE_JAVA_SOURCE_BATCH_SIZE value: %s, will use %s",
  830. err, xrefJavaSourceFileMaxDefault)
  831. return xrefJavaSourceFileMaxDefault
  832. }
  833. return v
  834. }
  835. func (c *config) EmitXrefRules() bool {
  836. return c.XrefCorpusName() != ""
  837. }
  838. func (c *config) ClangTidy() bool {
  839. return Bool(c.productVariables.ClangTidy)
  840. }
  841. func (c *config) TidyChecks() string {
  842. if c.productVariables.TidyChecks == nil {
  843. return ""
  844. }
  845. return *c.productVariables.TidyChecks
  846. }
  847. func (c *config) LibartImgHostBaseAddress() string {
  848. return "0x60000000"
  849. }
  850. func (c *config) LibartImgDeviceBaseAddress() string {
  851. return "0x70000000"
  852. }
  853. func (c *config) ArtUseReadBarrier() bool {
  854. return Bool(c.productVariables.ArtUseReadBarrier)
  855. }
  856. // Enforce Runtime Resource Overlays for a module. RROs supersede static RROs,
  857. // but some modules still depend on it.
  858. //
  859. // More info: https://source.android.com/devices/architecture/rros
  860. func (c *config) EnforceRROForModule(name string) bool {
  861. enforceList := c.productVariables.EnforceRROTargets
  862. if len(enforceList) > 0 {
  863. if InList("*", enforceList) {
  864. return true
  865. }
  866. return InList(name, enforceList)
  867. }
  868. return false
  869. }
  870. func (c *config) EnforceRROExcludedOverlay(path string) bool {
  871. excluded := c.productVariables.EnforceRROExcludedOverlays
  872. if len(excluded) > 0 {
  873. return HasAnyPrefix(path, excluded)
  874. }
  875. return false
  876. }
  877. func (c *config) ExportedNamespaces() []string {
  878. return append([]string(nil), c.productVariables.NamespacesToExport...)
  879. }
  880. func (c *config) HostStaticBinaries() bool {
  881. return Bool(c.productVariables.HostStaticBinaries)
  882. }
  883. func (c *config) UncompressPrivAppDex() bool {
  884. return Bool(c.productVariables.UncompressPrivAppDex)
  885. }
  886. func (c *config) ModulesLoadedByPrivilegedModules() []string {
  887. return c.productVariables.ModulesLoadedByPrivilegedModules
  888. }
  889. // DexpreoptGlobalConfigPath returns the path to the dexpreopt.config file in
  890. // the output directory, if it was created during the product configuration
  891. // phase by Kati.
  892. func (c *config) DexpreoptGlobalConfigPath(ctx PathContext) OptionalPath {
  893. if c.productVariables.DexpreoptGlobalConfig == nil {
  894. return OptionalPathForPath(nil)
  895. }
  896. return OptionalPathForPath(
  897. pathForBuildToolDep(ctx, *c.productVariables.DexpreoptGlobalConfig))
  898. }
  899. // DexpreoptGlobalConfig returns the raw byte contents of the dexpreopt global
  900. // configuration. Since the configuration file was created by Kati during
  901. // product configuration (externally of soong_build), it's not tracked, so we
  902. // also manually add a Ninja file dependency on the configuration file to the
  903. // rule that creates the main build.ninja file. This ensures that build.ninja is
  904. // regenerated correctly if dexpreopt.config changes.
  905. func (c *config) DexpreoptGlobalConfig(ctx PathContext) ([]byte, error) {
  906. path := c.DexpreoptGlobalConfigPath(ctx)
  907. if !path.Valid() {
  908. return nil, nil
  909. }
  910. ctx.AddNinjaFileDeps(path.String())
  911. return ioutil.ReadFile(absolutePath(path.String()))
  912. }
  913. func (c *deviceConfig) WithDexpreopt() bool {
  914. return c.config.productVariables.WithDexpreopt
  915. }
  916. func (c *config) FrameworksBaseDirExists(ctx PathGlobContext) bool {
  917. return ExistentPathForSource(ctx, "frameworks", "base", "Android.bp").Valid()
  918. }
  919. func (c *config) VndkSnapshotBuildArtifacts() bool {
  920. return Bool(c.productVariables.VndkSnapshotBuildArtifacts)
  921. }
  922. func (c *config) HasMultilibConflict(arch ArchType) bool {
  923. return c.multilibConflicts[arch]
  924. }
  925. func (c *config) PrebuiltHiddenApiDir(ctx PathContext) string {
  926. return String(c.productVariables.PrebuiltHiddenApiDir)
  927. }
  928. func (c *deviceConfig) Arches() []Arch {
  929. var arches []Arch
  930. for _, target := range c.config.Targets[Android] {
  931. arches = append(arches, target.Arch)
  932. }
  933. return arches
  934. }
  935. func (c *deviceConfig) BinderBitness() string {
  936. is32BitBinder := c.config.productVariables.Binder32bit
  937. if is32BitBinder != nil && *is32BitBinder {
  938. return "32"
  939. }
  940. return "64"
  941. }
  942. func (c *deviceConfig) VendorPath() string {
  943. if c.config.productVariables.VendorPath != nil {
  944. return *c.config.productVariables.VendorPath
  945. }
  946. return "vendor"
  947. }
  948. func (c *deviceConfig) VndkVersion() string {
  949. return String(c.config.productVariables.DeviceVndkVersion)
  950. }
  951. func (c *deviceConfig) RecoverySnapshotVersion() string {
  952. return String(c.config.productVariables.RecoverySnapshotVersion)
  953. }
  954. func (c *deviceConfig) CurrentApiLevelForVendorModules() string {
  955. return StringDefault(c.config.productVariables.DeviceCurrentApiLevelForVendorModules, "current")
  956. }
  957. func (c *deviceConfig) PlatformVndkVersion() string {
  958. return String(c.config.productVariables.Platform_vndk_version)
  959. }
  960. func (c *deviceConfig) ProductVndkVersion() string {
  961. return String(c.config.productVariables.ProductVndkVersion)
  962. }
  963. func (c *deviceConfig) ExtraVndkVersions() []string {
  964. return c.config.productVariables.ExtraVndkVersions
  965. }
  966. func (c *deviceConfig) VndkUseCoreVariant() bool {
  967. return Bool(c.config.productVariables.VndkUseCoreVariant)
  968. }
  969. func (c *deviceConfig) SystemSdkVersions() []string {
  970. return c.config.productVariables.DeviceSystemSdkVersions
  971. }
  972. func (c *deviceConfig) PlatformSystemSdkVersions() []string {
  973. return c.config.productVariables.Platform_systemsdk_versions
  974. }
  975. func (c *deviceConfig) OdmPath() string {
  976. if c.config.productVariables.OdmPath != nil {
  977. return *c.config.productVariables.OdmPath
  978. }
  979. return "odm"
  980. }
  981. func (c *deviceConfig) ProductPath() string {
  982. if c.config.productVariables.ProductPath != nil {
  983. return *c.config.productVariables.ProductPath
  984. }
  985. return "product"
  986. }
  987. func (c *deviceConfig) SystemExtPath() string {
  988. if c.config.productVariables.SystemExtPath != nil {
  989. return *c.config.productVariables.SystemExtPath
  990. }
  991. return "system_ext"
  992. }
  993. func (c *deviceConfig) BtConfigIncludeDir() string {
  994. return String(c.config.productVariables.BtConfigIncludeDir)
  995. }
  996. func (c *deviceConfig) DeviceKernelHeaderDirs() []string {
  997. return c.config.productVariables.DeviceKernelHeaders
  998. }
  999. // JavaCoverageEnabledForPath returns whether Java code coverage is enabled for
  1000. // path. Coverage is enabled by default when the product variable
  1001. // JavaCoveragePaths is empty. If JavaCoveragePaths is not empty, coverage is
  1002. // enabled for any path which is part of this variable (and not part of the
  1003. // JavaCoverageExcludePaths product variable). Value "*" in JavaCoveragePaths
  1004. // represents any path.
  1005. func (c *deviceConfig) JavaCoverageEnabledForPath(path string) bool {
  1006. coverage := false
  1007. if len(c.config.productVariables.JavaCoveragePaths) == 0 ||
  1008. InList("*", c.config.productVariables.JavaCoveragePaths) ||
  1009. HasAnyPrefix(path, c.config.productVariables.JavaCoveragePaths) {
  1010. coverage = true
  1011. }
  1012. if coverage && len(c.config.productVariables.JavaCoverageExcludePaths) > 0 {
  1013. if HasAnyPrefix(path, c.config.productVariables.JavaCoverageExcludePaths) {
  1014. coverage = false
  1015. }
  1016. }
  1017. return coverage
  1018. }
  1019. // Returns true if gcov or clang coverage is enabled.
  1020. func (c *deviceConfig) NativeCoverageEnabled() bool {
  1021. return Bool(c.config.productVariables.GcovCoverage) ||
  1022. Bool(c.config.productVariables.ClangCoverage)
  1023. }
  1024. func (c *deviceConfig) ClangCoverageEnabled() bool {
  1025. return Bool(c.config.productVariables.ClangCoverage)
  1026. }
  1027. func (c *deviceConfig) ClangCoverageContinuousMode() bool {
  1028. return Bool(c.config.productVariables.ClangCoverageContinuousMode)
  1029. }
  1030. func (c *deviceConfig) GcovCoverageEnabled() bool {
  1031. return Bool(c.config.productVariables.GcovCoverage)
  1032. }
  1033. // NativeCoverageEnabledForPath returns whether (GCOV- or Clang-based) native
  1034. // code coverage is enabled for path. By default, coverage is not enabled for a
  1035. // given path unless it is part of the NativeCoveragePaths product variable (and
  1036. // not part of the NativeCoverageExcludePaths product variable). Value "*" in
  1037. // NativeCoveragePaths represents any path.
  1038. func (c *deviceConfig) NativeCoverageEnabledForPath(path string) bool {
  1039. coverage := false
  1040. if len(c.config.productVariables.NativeCoveragePaths) > 0 {
  1041. if InList("*", c.config.productVariables.NativeCoveragePaths) || HasAnyPrefix(path, c.config.productVariables.NativeCoveragePaths) {
  1042. coverage = true
  1043. }
  1044. }
  1045. if coverage && len(c.config.productVariables.NativeCoverageExcludePaths) > 0 {
  1046. if HasAnyPrefix(path, c.config.productVariables.NativeCoverageExcludePaths) {
  1047. coverage = false
  1048. }
  1049. }
  1050. return coverage
  1051. }
  1052. func (c *deviceConfig) AfdoAdditionalProfileDirs() []string {
  1053. return c.config.productVariables.AfdoAdditionalProfileDirs
  1054. }
  1055. func (c *deviceConfig) PgoAdditionalProfileDirs() []string {
  1056. return c.config.productVariables.PgoAdditionalProfileDirs
  1057. }
  1058. func (c *deviceConfig) VendorSepolicyDirs() []string {
  1059. return c.config.productVariables.BoardVendorSepolicyDirs
  1060. }
  1061. func (c *deviceConfig) OdmSepolicyDirs() []string {
  1062. return c.config.productVariables.BoardOdmSepolicyDirs
  1063. }
  1064. func (c *deviceConfig) SystemExtPublicSepolicyDirs() []string {
  1065. return c.config.productVariables.SystemExtPublicSepolicyDirs
  1066. }
  1067. func (c *deviceConfig) SystemExtPrivateSepolicyDirs() []string {
  1068. return c.config.productVariables.SystemExtPrivateSepolicyDirs
  1069. }
  1070. func (c *deviceConfig) SepolicyM4Defs() []string {
  1071. return c.config.productVariables.BoardSepolicyM4Defs
  1072. }
  1073. func (c *deviceConfig) OverrideManifestPackageNameFor(name string) (manifestName string, overridden bool) {
  1074. return findOverrideValue(c.config.productVariables.ManifestPackageNameOverrides, name,
  1075. "invalid override rule %q in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES should be <module_name>:<manifest_name>")
  1076. }
  1077. func (c *deviceConfig) OverrideCertificateFor(name string) (certificatePath string, overridden bool) {
  1078. return findOverrideValue(c.config.productVariables.CertificateOverrides, name,
  1079. "invalid override rule %q in PRODUCT_CERTIFICATE_OVERRIDES should be <module_name>:<certificate_module_name>")
  1080. }
  1081. func (c *deviceConfig) OverridePackageNameFor(name string) string {
  1082. newName, overridden := findOverrideValue(
  1083. c.config.productVariables.PackageNameOverrides,
  1084. name,
  1085. "invalid override rule %q in PRODUCT_PACKAGE_NAME_OVERRIDES should be <module_name>:<package_name>")
  1086. if overridden {
  1087. return newName
  1088. }
  1089. return name
  1090. }
  1091. func findOverrideValue(overrides []string, name string, errorMsg string) (newValue string, overridden bool) {
  1092. if overrides == nil || len(overrides) == 0 {
  1093. return "", false
  1094. }
  1095. for _, o := range overrides {
  1096. split := strings.Split(o, ":")
  1097. if len(split) != 2 {
  1098. // This shouldn't happen as this is first checked in make, but just in case.
  1099. panic(fmt.Errorf(errorMsg, o))
  1100. }
  1101. if matchPattern(split[0], name) {
  1102. return substPattern(split[0], split[1], name), true
  1103. }
  1104. }
  1105. return "", false
  1106. }
  1107. func (c *deviceConfig) ApexGlobalMinSdkVersionOverride() string {
  1108. return String(c.config.productVariables.ApexGlobalMinSdkVersionOverride)
  1109. }
  1110. func (c *config) IntegerOverflowDisabledForPath(path string) bool {
  1111. if len(c.productVariables.IntegerOverflowExcludePaths) == 0 {
  1112. return false
  1113. }
  1114. return HasAnyPrefix(path, c.productVariables.IntegerOverflowExcludePaths)
  1115. }
  1116. func (c *config) CFIDisabledForPath(path string) bool {
  1117. if len(c.productVariables.CFIExcludePaths) == 0 {
  1118. return false
  1119. }
  1120. return HasAnyPrefix(path, c.productVariables.CFIExcludePaths)
  1121. }
  1122. func (c *config) CFIEnabledForPath(path string) bool {
  1123. if len(c.productVariables.CFIIncludePaths) == 0 {
  1124. return false
  1125. }
  1126. return HasAnyPrefix(path, c.productVariables.CFIIncludePaths) && !c.CFIDisabledForPath(path)
  1127. }
  1128. func (c *config) MemtagHeapDisabledForPath(path string) bool {
  1129. if len(c.productVariables.MemtagHeapExcludePaths) == 0 {
  1130. return false
  1131. }
  1132. return HasAnyPrefix(path, c.productVariables.MemtagHeapExcludePaths)
  1133. }
  1134. func (c *config) MemtagHeapAsyncEnabledForPath(path string) bool {
  1135. if len(c.productVariables.MemtagHeapAsyncIncludePaths) == 0 {
  1136. return false
  1137. }
  1138. return HasAnyPrefix(path, c.productVariables.MemtagHeapAsyncIncludePaths) && !c.MemtagHeapDisabledForPath(path)
  1139. }
  1140. func (c *config) MemtagHeapSyncEnabledForPath(path string) bool {
  1141. if len(c.productVariables.MemtagHeapSyncIncludePaths) == 0 {
  1142. return false
  1143. }
  1144. return HasAnyPrefix(path, c.productVariables.MemtagHeapSyncIncludePaths) && !c.MemtagHeapDisabledForPath(path)
  1145. }
  1146. func (c *config) VendorConfig(name string) VendorConfig {
  1147. return soongconfig.Config(c.productVariables.VendorVars[name])
  1148. }
  1149. func (c *config) NdkAbis() bool {
  1150. return Bool(c.productVariables.Ndk_abis)
  1151. }
  1152. func (c *config) AmlAbis() bool {
  1153. return Bool(c.productVariables.Aml_abis)
  1154. }
  1155. func (c *config) FlattenApex() bool {
  1156. return Bool(c.productVariables.Flatten_apex)
  1157. }
  1158. func (c *config) ForceApexSymlinkOptimization() bool {
  1159. return Bool(c.productVariables.ForceApexSymlinkOptimization)
  1160. }
  1161. func (c *config) ApexCompressionEnabled() bool {
  1162. return Bool(c.productVariables.CompressedApex) && !c.UnbundledBuildApps()
  1163. }
  1164. func (c *config) EnforceSystemCertificate() bool {
  1165. return Bool(c.productVariables.EnforceSystemCertificate)
  1166. }
  1167. func (c *config) EnforceSystemCertificateAllowList() []string {
  1168. return c.productVariables.EnforceSystemCertificateAllowList
  1169. }
  1170. func (c *config) EnforceProductPartitionInterface() bool {
  1171. return Bool(c.productVariables.EnforceProductPartitionInterface)
  1172. }
  1173. func (c *config) EnforceInterPartitionJavaSdkLibrary() bool {
  1174. return Bool(c.productVariables.EnforceInterPartitionJavaSdkLibrary)
  1175. }
  1176. func (c *config) InterPartitionJavaLibraryAllowList() []string {
  1177. return c.productVariables.InterPartitionJavaLibraryAllowList
  1178. }
  1179. func (c *config) InstallExtraFlattenedApexes() bool {
  1180. return Bool(c.productVariables.InstallExtraFlattenedApexes)
  1181. }
  1182. func (c *config) ProductHiddenAPIStubs() []string {
  1183. return c.productVariables.ProductHiddenAPIStubs
  1184. }
  1185. func (c *config) ProductHiddenAPIStubsSystem() []string {
  1186. return c.productVariables.ProductHiddenAPIStubsSystem
  1187. }
  1188. func (c *config) ProductHiddenAPIStubsTest() []string {
  1189. return c.productVariables.ProductHiddenAPIStubsTest
  1190. }
  1191. func (c *deviceConfig) TargetFSConfigGen() []string {
  1192. return c.config.productVariables.TargetFSConfigGen
  1193. }
  1194. func (c *config) ProductPublicSepolicyDirs() []string {
  1195. return c.productVariables.ProductPublicSepolicyDirs
  1196. }
  1197. func (c *config) ProductPrivateSepolicyDirs() []string {
  1198. return c.productVariables.ProductPrivateSepolicyDirs
  1199. }
  1200. func (c *config) MissingUsesLibraries() []string {
  1201. return c.productVariables.MissingUsesLibraries
  1202. }
  1203. func (c *config) TargetMultitreeUpdateMeta() bool {
  1204. return c.productVariables.MultitreeUpdateMeta
  1205. }
  1206. func (c *deviceConfig) DeviceArch() string {
  1207. return String(c.config.productVariables.DeviceArch)
  1208. }
  1209. func (c *deviceConfig) DeviceArchVariant() string {
  1210. return String(c.config.productVariables.DeviceArchVariant)
  1211. }
  1212. func (c *deviceConfig) DeviceSecondaryArch() string {
  1213. return String(c.config.productVariables.DeviceSecondaryArch)
  1214. }
  1215. func (c *deviceConfig) DeviceSecondaryArchVariant() string {
  1216. return String(c.config.productVariables.DeviceSecondaryArchVariant)
  1217. }
  1218. func (c *deviceConfig) BoardUsesRecoveryAsBoot() bool {
  1219. return Bool(c.config.productVariables.BoardUsesRecoveryAsBoot)
  1220. }
  1221. func (c *deviceConfig) BoardKernelBinaries() []string {
  1222. return c.config.productVariables.BoardKernelBinaries
  1223. }
  1224. func (c *deviceConfig) BoardKernelModuleInterfaceVersions() []string {
  1225. return c.config.productVariables.BoardKernelModuleInterfaceVersions
  1226. }
  1227. func (c *deviceConfig) BoardMoveRecoveryResourcesToVendorBoot() bool {
  1228. return Bool(c.config.productVariables.BoardMoveRecoveryResourcesToVendorBoot)
  1229. }
  1230. func (c *deviceConfig) PlatformSepolicyVersion() string {
  1231. return String(c.config.productVariables.PlatformSepolicyVersion)
  1232. }
  1233. func (c *deviceConfig) TotSepolicyVersion() string {
  1234. return String(c.config.productVariables.TotSepolicyVersion)
  1235. }
  1236. func (c *deviceConfig) PlatformSepolicyCompatVersions() []string {
  1237. return c.config.productVariables.PlatformSepolicyCompatVersions
  1238. }
  1239. func (c *deviceConfig) BoardSepolicyVers() string {
  1240. if ver := String(c.config.productVariables.BoardSepolicyVers); ver != "" {
  1241. return ver
  1242. }
  1243. return c.PlatformSepolicyVersion()
  1244. }
  1245. func (c *deviceConfig) BoardPlatVendorPolicy() []string {
  1246. return c.config.productVariables.BoardPlatVendorPolicy
  1247. }
  1248. func (c *deviceConfig) BoardReqdMaskPolicy() []string {
  1249. return c.config.productVariables.BoardReqdMaskPolicy
  1250. }
  1251. func (c *deviceConfig) BoardSystemExtPublicPrebuiltDirs() []string {
  1252. return c.config.productVariables.BoardSystemExtPublicPrebuiltDirs
  1253. }
  1254. func (c *deviceConfig) BoardSystemExtPrivatePrebuiltDirs() []string {
  1255. return c.config.productVariables.BoardSystemExtPrivatePrebuiltDirs
  1256. }
  1257. func (c *deviceConfig) BoardProductPublicPrebuiltDirs() []string {
  1258. return c.config.productVariables.BoardProductPublicPrebuiltDirs
  1259. }
  1260. func (c *deviceConfig) BoardProductPrivatePrebuiltDirs() []string {
  1261. return c.config.productVariables.BoardProductPrivatePrebuiltDirs
  1262. }
  1263. func (c *deviceConfig) SystemExtSepolicyPrebuiltApiDir() string {
  1264. return String(c.config.productVariables.SystemExtSepolicyPrebuiltApiDir)
  1265. }
  1266. func (c *deviceConfig) ProductSepolicyPrebuiltApiDir() string {
  1267. return String(c.config.productVariables.ProductSepolicyPrebuiltApiDir)
  1268. }
  1269. func (c *deviceConfig) IsPartnerTrebleSepolicyTestEnabled() bool {
  1270. return c.SystemExtSepolicyPrebuiltApiDir() != "" || c.ProductSepolicyPrebuiltApiDir() != ""
  1271. }
  1272. func (c *deviceConfig) DirectedVendorSnapshot() bool {
  1273. return c.config.productVariables.DirectedVendorSnapshot
  1274. }
  1275. func (c *deviceConfig) VendorSnapshotModules() map[string]bool {
  1276. return c.config.productVariables.VendorSnapshotModules
  1277. }
  1278. func (c *deviceConfig) DirectedRecoverySnapshot() bool {
  1279. return c.config.productVariables.DirectedRecoverySnapshot
  1280. }
  1281. func (c *deviceConfig) RecoverySnapshotModules() map[string]bool {
  1282. return c.config.productVariables.RecoverySnapshotModules
  1283. }
  1284. func createDirsMap(previous map[string]bool, dirs []string) (map[string]bool, error) {
  1285. var ret = make(map[string]bool)
  1286. for _, dir := range dirs {
  1287. clean := filepath.Clean(dir)
  1288. if previous[clean] || ret[clean] {
  1289. return nil, fmt.Errorf("Duplicate entry %s", dir)
  1290. }
  1291. ret[clean] = true
  1292. }
  1293. return ret, nil
  1294. }
  1295. func (c *deviceConfig) createDirsMapOnce(onceKey OnceKey, previous map[string]bool, dirs []string) map[string]bool {
  1296. dirMap := c.Once(onceKey, func() interface{} {
  1297. ret, err := createDirsMap(previous, dirs)
  1298. if err != nil {
  1299. panic(fmt.Errorf("%s: %w", onceKey.key, err))
  1300. }
  1301. return ret
  1302. })
  1303. if dirMap == nil {
  1304. return nil
  1305. }
  1306. return dirMap.(map[string]bool)
  1307. }
  1308. var vendorSnapshotDirsExcludedKey = NewOnceKey("VendorSnapshotDirsExcludedMap")
  1309. func (c *deviceConfig) VendorSnapshotDirsExcludedMap() map[string]bool {
  1310. return c.createDirsMapOnce(vendorSnapshotDirsExcludedKey, nil,
  1311. c.config.productVariables.VendorSnapshotDirsExcluded)
  1312. }
  1313. var vendorSnapshotDirsIncludedKey = NewOnceKey("VendorSnapshotDirsIncludedMap")
  1314. func (c *deviceConfig) VendorSnapshotDirsIncludedMap() map[string]bool {
  1315. excludedMap := c.VendorSnapshotDirsExcludedMap()
  1316. return c.createDirsMapOnce(vendorSnapshotDirsIncludedKey, excludedMap,
  1317. c.config.productVariables.VendorSnapshotDirsIncluded)
  1318. }
  1319. var recoverySnapshotDirsExcludedKey = NewOnceKey("RecoverySnapshotDirsExcludedMap")
  1320. func (c *deviceConfig) RecoverySnapshotDirsExcludedMap() map[string]bool {
  1321. return c.createDirsMapOnce(recoverySnapshotDirsExcludedKey, nil,
  1322. c.config.productVariables.RecoverySnapshotDirsExcluded)
  1323. }
  1324. var recoverySnapshotDirsIncludedKey = NewOnceKey("RecoverySnapshotDirsIncludedMap")
  1325. func (c *deviceConfig) RecoverySnapshotDirsIncludedMap() map[string]bool {
  1326. excludedMap := c.RecoverySnapshotDirsExcludedMap()
  1327. return c.createDirsMapOnce(recoverySnapshotDirsIncludedKey, excludedMap,
  1328. c.config.productVariables.RecoverySnapshotDirsIncluded)
  1329. }
  1330. func (c *deviceConfig) HostFakeSnapshotEnabled() bool {
  1331. return c.config.productVariables.HostFakeSnapshotEnabled
  1332. }
  1333. func (c *deviceConfig) ShippingApiLevel() ApiLevel {
  1334. if c.config.productVariables.ShippingApiLevel == nil {
  1335. return NoneApiLevel
  1336. }
  1337. apiLevel, _ := strconv.Atoi(*c.config.productVariables.ShippingApiLevel)
  1338. return uncheckedFinalApiLevel(apiLevel)
  1339. }
  1340. func (c *deviceConfig) BuildBrokenClangAsFlags() bool {
  1341. return c.config.productVariables.BuildBrokenClangAsFlags
  1342. }
  1343. func (c *deviceConfig) BuildBrokenClangCFlags() bool {
  1344. return c.config.productVariables.BuildBrokenClangCFlags
  1345. }
  1346. func (c *deviceConfig) BuildBrokenClangProperty() bool {
  1347. return c.config.productVariables.BuildBrokenClangProperty
  1348. }
  1349. func (c *deviceConfig) BuildBrokenEnforceSyspropOwner() bool {
  1350. return c.config.productVariables.BuildBrokenEnforceSyspropOwner
  1351. }
  1352. func (c *deviceConfig) BuildBrokenTrebleSyspropNeverallow() bool {
  1353. return c.config.productVariables.BuildBrokenTrebleSyspropNeverallow
  1354. }
  1355. func (c *deviceConfig) BuildDebugfsRestrictionsEnabled() bool {
  1356. return c.config.productVariables.BuildDebugfsRestrictionsEnabled
  1357. }
  1358. func (c *deviceConfig) BuildBrokenVendorPropertyNamespace() bool {
  1359. return c.config.productVariables.BuildBrokenVendorPropertyNamespace
  1360. }
  1361. func (c *deviceConfig) BuildBrokenInputDir(name string) bool {
  1362. return InList(name, c.config.productVariables.BuildBrokenInputDirModules)
  1363. }
  1364. func (c *deviceConfig) BuildBrokenDepfile() bool {
  1365. return Bool(c.config.productVariables.BuildBrokenDepfile)
  1366. }
  1367. func (c *deviceConfig) RequiresInsecureExecmemForSwiftshader() bool {
  1368. return c.config.productVariables.RequiresInsecureExecmemForSwiftshader
  1369. }
  1370. func (c *config) SelinuxIgnoreNeverallows() bool {
  1371. return c.productVariables.SelinuxIgnoreNeverallows
  1372. }
  1373. func (c *deviceConfig) SepolicySplit() bool {
  1374. return c.config.productVariables.SepolicySplit
  1375. }
  1376. func (c *deviceConfig) SepolicyFreezeTestExtraDirs() []string {
  1377. return c.config.productVariables.SepolicyFreezeTestExtraDirs
  1378. }
  1379. func (c *deviceConfig) SepolicyFreezeTestExtraPrebuiltDirs() []string {
  1380. return c.config.productVariables.SepolicyFreezeTestExtraPrebuiltDirs
  1381. }
  1382. func (c *deviceConfig) GenerateAidlNdkPlatformBackend() bool {
  1383. return c.config.productVariables.GenerateAidlNdkPlatformBackend
  1384. }
  1385. func (c *config) IgnorePrefer32OnDevice() bool {
  1386. return c.productVariables.IgnorePrefer32OnDevice
  1387. }
  1388. func (c *config) BootJars() []string {
  1389. return c.Once(earlyBootJarsKey, func() interface{} {
  1390. list := c.productVariables.BootJars.CopyOfJars()
  1391. return append(list, c.productVariables.ApexBootJars.CopyOfJars()...)
  1392. }).([]string)
  1393. }
  1394. func (c *config) NonApexBootJars() ConfiguredJarList {
  1395. return c.productVariables.BootJars
  1396. }
  1397. func (c *config) ApexBootJars() ConfiguredJarList {
  1398. return c.productVariables.ApexBootJars
  1399. }
  1400. func (c *config) RBEWrapper() string {
  1401. return c.GetenvWithDefault("RBE_WRAPPER", remoteexec.DefaultWrapperPath)
  1402. }
  1403. // UseHostMusl returns true if the host target has been configured to build against musl libc.
  1404. func (c *config) UseHostMusl() bool {
  1405. return Bool(c.productVariables.HostMusl)
  1406. }
  1407. func (c *config) LogMixedBuild(ctx BaseModuleContext, useBazel bool) {
  1408. moduleName := ctx.Module().Name()
  1409. c.mixedBuildsLock.Lock()
  1410. defer c.mixedBuildsLock.Unlock()
  1411. if useBazel {
  1412. c.mixedBuildEnabledModules[moduleName] = struct{}{}
  1413. } else {
  1414. c.mixedBuildDisabledModules[moduleName] = struct{}{}
  1415. }
  1416. }