config.go 56 KB

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