config.go 50 KB

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