config.go 58 KB

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