config.go 61 KB

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