config.go 63 KB

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