config.go 60 KB

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