test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. // Copyright 2016 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 cc
  15. import (
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "github.com/google/blueprint/proptools"
  20. "android/soong/android"
  21. "android/soong/bazel"
  22. "android/soong/bazel/cquery"
  23. "android/soong/tradefed"
  24. )
  25. // TestLinkerProperties properties to be registered via the linker
  26. type TestLinkerProperties struct {
  27. // if set, build against the gtest library. Defaults to true.
  28. Gtest *bool
  29. // if set, use the isolated gtest runner. Defaults to true if gtest is also true and the arch is Windows, false
  30. // otherwise.
  31. Isolated *bool
  32. }
  33. // TestInstallerProperties properties to be registered via the installer
  34. type TestInstallerProperties struct {
  35. // list of compatibility suites (for example "cts", "vts") that the module should be installed into.
  36. Test_suites []string `android:"arch_variant"`
  37. }
  38. // Test option struct.
  39. type TestOptions struct {
  40. android.CommonTestOptions
  41. // The UID that you want to run the test as on a device.
  42. Run_test_as *string
  43. // A list of free-formed strings without spaces that categorize the test.
  44. Test_suite_tag []string
  45. // a list of extra test configuration files that should be installed with the module.
  46. Extra_test_configs []string `android:"path,arch_variant"`
  47. // Add ShippingApiLevelModuleController to auto generated test config. If the device properties
  48. // for the shipping api level is less than the min_shipping_api_level, skip this module.
  49. Min_shipping_api_level *int64
  50. // Add ShippingApiLevelModuleController to auto generated test config. If any of the device
  51. // shipping api level and vendor api level properties are less than the
  52. // vsr_min_shipping_api_level, skip this module.
  53. // As this includes the shipping api level check, it is not allowed to define
  54. // min_shipping_api_level at the same time with this property.
  55. Vsr_min_shipping_api_level *int64
  56. // Add MinApiLevelModuleController with ro.vndk.version property. If ro.vndk.version has an
  57. // integer value and the value is less than the min_vndk_version, skip this module.
  58. Min_vndk_version *int64
  59. }
  60. type TestBinaryProperties struct {
  61. // Create a separate binary for each source file. Useful when there is
  62. // global state that can not be torn down and reset between each test suite.
  63. Test_per_src *bool
  64. // Disables the creation of a test-specific directory when used with
  65. // relative_install_path. Useful if several tests need to be in the same
  66. // directory, but test_per_src doesn't work.
  67. No_named_install_directory *bool
  68. // list of files or filegroup modules that provide data that should be installed alongside
  69. // the test
  70. Data []string `android:"path,arch_variant"`
  71. // list of shared library modules that should be installed alongside the test
  72. Data_libs []string `android:"arch_variant"`
  73. // list of binary modules that should be installed alongside the test
  74. Data_bins []string `android:"arch_variant"`
  75. // the name of the test configuration (for example "AndroidTest.xml") that should be
  76. // installed with the module.
  77. Test_config *string `android:"path,arch_variant"`
  78. // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
  79. // should be installed with the module.
  80. Test_config_template *string `android:"path,arch_variant"`
  81. // Test options.
  82. Test_options TestOptions
  83. // Add RootTargetPreparer to auto generated test config. This guarantees the test to run
  84. // with root permission.
  85. Require_root *bool
  86. // Add RunCommandTargetPreparer to stop framework before the test and start it after the test.
  87. Disable_framework *bool
  88. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  89. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  90. // explicitly.
  91. Auto_gen_config *bool
  92. // Add parameterized mainline modules to auto generated test config. The options will be
  93. // handled by TradeFed to download and install the specified modules on the device.
  94. Test_mainline_modules []string
  95. // Install the test into a folder named for the module in all test suites.
  96. Per_testcase_directory *bool
  97. }
  98. func init() {
  99. android.RegisterModuleType("cc_test", TestFactory)
  100. android.RegisterModuleType("cc_test_library", TestLibraryFactory)
  101. android.RegisterModuleType("cc_benchmark", BenchmarkFactory)
  102. android.RegisterModuleType("cc_test_host", TestHostFactory)
  103. android.RegisterModuleType("cc_benchmark_host", BenchmarkHostFactory)
  104. }
  105. // cc_test generates a test config file and an executable binary file to test
  106. // specific functionality on a device. The executable binary gets an implicit
  107. // static_libs dependency on libgtests unless the gtest flag is set to false.
  108. func TestFactory() android.Module {
  109. module := NewTest(android.HostAndDeviceSupported, true)
  110. module.bazelHandler = &ccTestBazelHandler{module: module}
  111. return module.Init()
  112. }
  113. // cc_test_library creates an archive of files (i.e. .o files) which is later
  114. // referenced by another module (such as cc_test, cc_defaults or cc_test_library)
  115. // for archiving or linking.
  116. func TestLibraryFactory() android.Module {
  117. module := NewTestLibrary(android.HostAndDeviceSupported)
  118. return module.Init()
  119. }
  120. // cc_benchmark compiles an executable binary that performs benchmark testing
  121. // of a specific component in a device. Additional files such as test suites
  122. // and test configuration are installed on the side of the compiled executed
  123. // binary.
  124. func BenchmarkFactory() android.Module {
  125. module := NewBenchmark(android.HostAndDeviceSupported)
  126. return module.Init()
  127. }
  128. // cc_test_host compiles a test host binary.
  129. func TestHostFactory() android.Module {
  130. module := NewTest(android.HostSupported, true)
  131. return module.Init()
  132. }
  133. // cc_benchmark_host compiles an executable binary that performs benchmark
  134. // testing of a specific component in the host. Additional files such as
  135. // test suites and test configuration are installed on the side of the
  136. // compiled executed binary.
  137. func BenchmarkHostFactory() android.Module {
  138. module := NewBenchmark(android.HostSupported)
  139. return module.Init()
  140. }
  141. type testPerSrc interface {
  142. testPerSrc() bool
  143. srcs() []string
  144. isAllTestsVariation() bool
  145. setSrc(string, string)
  146. unsetSrc()
  147. }
  148. func (test *testBinary) testPerSrc() bool {
  149. return Bool(test.Properties.Test_per_src)
  150. }
  151. func (test *testBinary) srcs() []string {
  152. return test.baseCompiler.Properties.Srcs
  153. }
  154. func (test *testBinary) dataPaths() []android.DataPath {
  155. return test.data
  156. }
  157. func (test *testBinary) isAllTestsVariation() bool {
  158. stem := test.binaryDecorator.Properties.Stem
  159. return stem != nil && *stem == ""
  160. }
  161. func (test *testBinary) setSrc(name, src string) {
  162. test.baseCompiler.Properties.Srcs = []string{src}
  163. test.binaryDecorator.Properties.Stem = StringPtr(name)
  164. }
  165. func (test *testBinary) unsetSrc() {
  166. test.baseCompiler.Properties.Srcs = nil
  167. test.binaryDecorator.Properties.Stem = StringPtr("")
  168. }
  169. func (test *testBinary) testBinary() bool {
  170. return true
  171. }
  172. var _ testPerSrc = (*testBinary)(nil)
  173. func TestPerSrcMutator(mctx android.BottomUpMutatorContext) {
  174. if m, ok := mctx.Module().(*Module); ok {
  175. if test, ok := m.linker.(testPerSrc); ok {
  176. numTests := len(test.srcs())
  177. if test.testPerSrc() && numTests > 0 {
  178. if duplicate, found := android.CheckDuplicate(test.srcs()); found {
  179. mctx.PropertyErrorf("srcs", "found a duplicate entry %q", duplicate)
  180. return
  181. }
  182. testNames := make([]string, numTests)
  183. for i, src := range test.srcs() {
  184. testNames[i] = strings.TrimSuffix(filepath.Base(src), filepath.Ext(src))
  185. }
  186. // In addition to creating one variation per test source file,
  187. // create an additional "all tests" variation named "", and have it
  188. // depends on all other test_per_src variations. This is useful to
  189. // create subsequent dependencies of a given module on all
  190. // test_per_src variations created above: by depending on
  191. // variation "", that module will transitively depend on all the
  192. // other test_per_src variations without the need to know their
  193. // name or even their number.
  194. testNames = append(testNames, "")
  195. tests := mctx.CreateLocalVariations(testNames...)
  196. allTests := tests[numTests]
  197. allTests.(*Module).linker.(testPerSrc).unsetSrc()
  198. // Prevent the "all tests" variation from being installable nor
  199. // exporting to Make, as it won't create any output file.
  200. allTests.(*Module).Properties.PreventInstall = true
  201. allTests.(*Module).Properties.HideFromMake = true
  202. for i, src := range test.srcs() {
  203. tests[i].(*Module).linker.(testPerSrc).setSrc(testNames[i], src)
  204. mctx.AddInterVariantDependency(testPerSrcDepTag, allTests, tests[i])
  205. }
  206. mctx.AliasVariation("")
  207. }
  208. }
  209. }
  210. }
  211. type testDecorator struct {
  212. LinkerProperties TestLinkerProperties
  213. InstallerProperties TestInstallerProperties
  214. installer *baseInstaller
  215. linker *baseLinker
  216. }
  217. func (test *testDecorator) gtest() bool {
  218. return BoolDefault(test.LinkerProperties.Gtest, true)
  219. }
  220. func (test *testDecorator) isolated(ctx BaseModuleContext) bool {
  221. return BoolDefault(test.LinkerProperties.Isolated, false)
  222. }
  223. // NOTE: Keep this in sync with cc/cc_test.bzl#gtest_copts
  224. func (test *testDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
  225. if !test.gtest() {
  226. return flags
  227. }
  228. flags.Local.CFlags = append(flags.Local.CFlags, "-DGTEST_HAS_STD_STRING")
  229. if ctx.Host() {
  230. flags.Local.CFlags = append(flags.Local.CFlags, "-O0", "-g")
  231. switch ctx.Os() {
  232. case android.Windows:
  233. flags.Local.CFlags = append(flags.Local.CFlags, "-DGTEST_OS_WINDOWS")
  234. case android.Linux:
  235. flags.Local.CFlags = append(flags.Local.CFlags, "-DGTEST_OS_LINUX")
  236. case android.Darwin:
  237. flags.Local.CFlags = append(flags.Local.CFlags, "-DGTEST_OS_MAC")
  238. }
  239. } else {
  240. flags.Local.CFlags = append(flags.Local.CFlags, "-DGTEST_OS_LINUX_ANDROID")
  241. }
  242. return flags
  243. }
  244. func (test *testDecorator) linkerDeps(ctx BaseModuleContext, deps Deps) Deps {
  245. if test.gtest() {
  246. if ctx.useSdk() && ctx.Device() {
  247. deps.StaticLibs = append(deps.StaticLibs, "libgtest_main_ndk_c++", "libgtest_ndk_c++")
  248. } else if test.isolated(ctx) {
  249. deps.StaticLibs = append(deps.StaticLibs, "libgtest_isolated_main")
  250. // The isolated library requires liblog, but adding it
  251. // as a static library means unit tests cannot override
  252. // liblog functions. Instead make it a shared library
  253. // dependency.
  254. deps.SharedLibs = append(deps.SharedLibs, "liblog")
  255. } else {
  256. deps.StaticLibs = append(deps.StaticLibs, "libgtest_main", "libgtest")
  257. }
  258. }
  259. return deps
  260. }
  261. func (test *testDecorator) linkerInit(ctx BaseModuleContext, linker *baseLinker) {
  262. // 1. Add ../../lib[64] to rpath so that out/host/linux-x86/nativetest/<test dir>/<test> can
  263. // find out/host/linux-x86/lib[64]/library.so
  264. // 2. Add ../../../lib[64] to rpath so that out/host/linux-x86/testcases/<test dir>/<CPU>/<test> can
  265. // also find out/host/linux-x86/lib[64]/library.so
  266. runpaths := []string{"../../lib", "../../../lib"}
  267. for _, runpath := range runpaths {
  268. if ctx.toolchain().Is64Bit() {
  269. runpath += "64"
  270. }
  271. linker.dynamicProperties.RunPaths = append(linker.dynamicProperties.RunPaths, runpath)
  272. }
  273. // add "" to rpath so that test binaries can find libraries in their own test directory
  274. linker.dynamicProperties.RunPaths = append(linker.dynamicProperties.RunPaths, "")
  275. }
  276. func (test *testDecorator) linkerProps() []interface{} {
  277. return []interface{}{&test.LinkerProperties}
  278. }
  279. func (test *testDecorator) installerProps() []interface{} {
  280. return []interface{}{&test.InstallerProperties}
  281. }
  282. func NewTestInstaller() *baseInstaller {
  283. return NewBaseInstaller("nativetest", "nativetest64", InstallInData)
  284. }
  285. type testBinary struct {
  286. *testDecorator
  287. *binaryDecorator
  288. *baseCompiler
  289. Properties TestBinaryProperties
  290. data []android.DataPath
  291. testConfig android.Path
  292. extraTestConfigs android.Paths
  293. }
  294. func (test *testBinary) linkerProps() []interface{} {
  295. props := append(test.testDecorator.linkerProps(), test.binaryDecorator.linkerProps()...)
  296. props = append(props, &test.Properties)
  297. return props
  298. }
  299. func (test *testBinary) linkerInit(ctx BaseModuleContext) {
  300. test.testDecorator.linkerInit(ctx, test.binaryDecorator.baseLinker)
  301. test.binaryDecorator.linkerInit(ctx)
  302. }
  303. func (test *testBinary) linkerDeps(ctx DepsContext, deps Deps) Deps {
  304. deps = test.testDecorator.linkerDeps(ctx, deps)
  305. deps = test.binaryDecorator.linkerDeps(ctx, deps)
  306. deps.DataLibs = append(deps.DataLibs, test.Properties.Data_libs...)
  307. deps.DataBins = append(deps.DataBins, test.Properties.Data_bins...)
  308. return deps
  309. }
  310. func (test *testBinary) linkerFlags(ctx ModuleContext, flags Flags) Flags {
  311. flags = test.binaryDecorator.linkerFlags(ctx, flags)
  312. flags = test.testDecorator.linkerFlags(ctx, flags)
  313. return flags
  314. }
  315. func (test *testBinary) installerProps() []interface{} {
  316. return append(test.baseInstaller.installerProps(), test.testDecorator.installerProps()...)
  317. }
  318. func (test *testBinary) install(ctx ModuleContext, file android.Path) {
  319. dataSrcPaths := android.PathsForModuleSrc(ctx, test.Properties.Data)
  320. for _, dataSrcPath := range dataSrcPaths {
  321. test.data = append(test.data, android.DataPath{SrcPath: dataSrcPath})
  322. }
  323. ctx.VisitDirectDepsWithTag(dataLibDepTag, func(dep android.Module) {
  324. depName := ctx.OtherModuleName(dep)
  325. linkableDep, ok := dep.(LinkableInterface)
  326. if !ok {
  327. ctx.ModuleErrorf("data_lib %q is not a LinkableInterface module", depName)
  328. }
  329. if linkableDep.OutputFile().Valid() {
  330. test.data = append(test.data,
  331. android.DataPath{SrcPath: linkableDep.OutputFile().Path(),
  332. RelativeInstallPath: linkableDep.RelativeInstallPath()})
  333. }
  334. })
  335. ctx.VisitDirectDepsWithTag(dataBinDepTag, func(dep android.Module) {
  336. depName := ctx.OtherModuleName(dep)
  337. linkableDep, ok := dep.(LinkableInterface)
  338. if !ok {
  339. ctx.ModuleErrorf("data_bin %q is not a LinkableInterface module", depName)
  340. }
  341. if linkableDep.OutputFile().Valid() {
  342. test.data = append(test.data,
  343. android.DataPath{SrcPath: linkableDep.OutputFile().Path(),
  344. RelativeInstallPath: linkableDep.RelativeInstallPath()})
  345. }
  346. })
  347. useVendor := ctx.inVendor() || ctx.useVndk()
  348. testInstallBase := getTestInstallBase(useVendor)
  349. configs := getTradefedConfigOptions(ctx, &test.Properties, test.isolated(ctx))
  350. test.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
  351. TestConfigProp: test.Properties.Test_config,
  352. TestConfigTemplateProp: test.Properties.Test_config_template,
  353. TestSuites: test.testDecorator.InstallerProperties.Test_suites,
  354. Config: configs,
  355. AutoGenConfig: test.Properties.Auto_gen_config,
  356. TestInstallBase: testInstallBase,
  357. DeviceTemplate: "${NativeTestConfigTemplate}",
  358. HostTemplate: "${NativeHostTestConfigTemplate}",
  359. })
  360. test.extraTestConfigs = android.PathsForModuleSrc(ctx, test.Properties.Test_options.Extra_test_configs)
  361. test.binaryDecorator.baseInstaller.dir = "nativetest"
  362. test.binaryDecorator.baseInstaller.dir64 = "nativetest64"
  363. if !Bool(test.Properties.No_named_install_directory) {
  364. test.binaryDecorator.baseInstaller.relative = ctx.ModuleName()
  365. } else if String(test.binaryDecorator.baseInstaller.Properties.Relative_install_path) == "" {
  366. ctx.PropertyErrorf("no_named_install_directory", "Module install directory may only be disabled if relative_install_path is set")
  367. }
  368. if ctx.Host() && test.gtest() && test.Properties.Test_options.Unit_test == nil {
  369. test.Properties.Test_options.Unit_test = proptools.BoolPtr(true)
  370. }
  371. test.binaryDecorator.baseInstaller.install(ctx, file)
  372. }
  373. func getTestInstallBase(useVendor bool) string {
  374. // TODO: (b/167308193) Switch to /data/local/tests/unrestricted as the default install base.
  375. testInstallBase := "/data/local/tmp"
  376. if useVendor {
  377. testInstallBase = "/data/local/tests/vendor"
  378. }
  379. return testInstallBase
  380. }
  381. func getTradefedConfigOptions(ctx android.EarlyModuleContext, properties *TestBinaryProperties, isolated bool) []tradefed.Config {
  382. var configs []tradefed.Config
  383. for _, module := range properties.Test_mainline_modules {
  384. configs = append(configs, tradefed.Option{Name: "config-descriptor:metadata", Key: "mainline-param", Value: module})
  385. }
  386. if Bool(properties.Require_root) {
  387. configs = append(configs, tradefed.Object{"target_preparer", "com.android.tradefed.targetprep.RootTargetPreparer", nil})
  388. } else {
  389. var options []tradefed.Option
  390. options = append(options, tradefed.Option{Name: "force-root", Value: "false"})
  391. configs = append(configs, tradefed.Object{"target_preparer", "com.android.tradefed.targetprep.RootTargetPreparer", options})
  392. }
  393. if Bool(properties.Disable_framework) {
  394. var options []tradefed.Option
  395. configs = append(configs, tradefed.Object{"target_preparer", "com.android.tradefed.targetprep.StopServicesSetup", options})
  396. }
  397. if isolated {
  398. configs = append(configs, tradefed.Option{Name: "not-shardable", Value: "true"})
  399. }
  400. if properties.Test_options.Run_test_as != nil {
  401. configs = append(configs, tradefed.Option{Name: "run-test-as", Value: String(properties.Test_options.Run_test_as)})
  402. }
  403. for _, tag := range properties.Test_options.Test_suite_tag {
  404. configs = append(configs, tradefed.Option{Name: "test-suite-tag", Value: tag})
  405. }
  406. if properties.Test_options.Min_shipping_api_level != nil {
  407. if properties.Test_options.Vsr_min_shipping_api_level != nil {
  408. ctx.PropertyErrorf("test_options.min_shipping_api_level", "must not be set at the same time as 'vsr_min_shipping_api_level'.")
  409. }
  410. var options []tradefed.Option
  411. options = append(options, tradefed.Option{Name: "min-api-level", Value: strconv.FormatInt(int64(*properties.Test_options.Min_shipping_api_level), 10)})
  412. configs = append(configs, tradefed.Object{"module_controller", "com.android.tradefed.testtype.suite.module.ShippingApiLevelModuleController", options})
  413. }
  414. if properties.Test_options.Vsr_min_shipping_api_level != nil {
  415. var options []tradefed.Option
  416. options = append(options, tradefed.Option{Name: "vsr-min-api-level", Value: strconv.FormatInt(int64(*properties.Test_options.Vsr_min_shipping_api_level), 10)})
  417. configs = append(configs, tradefed.Object{"module_controller", "com.android.tradefed.testtype.suite.module.ShippingApiLevelModuleController", options})
  418. }
  419. if properties.Test_options.Min_vndk_version != nil {
  420. var options []tradefed.Option
  421. options = append(options, tradefed.Option{Name: "min-api-level", Value: strconv.FormatInt(int64(*properties.Test_options.Min_vndk_version), 10)})
  422. options = append(options, tradefed.Option{Name: "api-level-prop", Value: "ro.vndk.version"})
  423. configs = append(configs, tradefed.Object{"module_controller", "com.android.tradefed.testtype.suite.module.MinApiLevelModuleController", options})
  424. }
  425. return configs
  426. }
  427. func NewTest(hod android.HostOrDeviceSupported, bazelable bool) *Module {
  428. module, binary := newBinary(hod, bazelable)
  429. module.bazelable = bazelable
  430. module.multilib = android.MultilibBoth
  431. binary.baseInstaller = NewTestInstaller()
  432. test := &testBinary{
  433. testDecorator: &testDecorator{
  434. linker: binary.baseLinker,
  435. installer: binary.baseInstaller,
  436. },
  437. binaryDecorator: binary,
  438. baseCompiler: NewBaseCompiler(),
  439. }
  440. module.compiler = test
  441. module.linker = test
  442. module.installer = test
  443. return module
  444. }
  445. type testLibrary struct {
  446. *testDecorator
  447. *libraryDecorator
  448. }
  449. func (test *testLibrary) testLibrary() bool {
  450. return true
  451. }
  452. func (test *testLibrary) linkerProps() []interface{} {
  453. var props []interface{}
  454. props = append(props, test.testDecorator.linkerProps()...)
  455. return append(props, test.libraryDecorator.linkerProps()...)
  456. }
  457. func (test *testLibrary) linkerInit(ctx BaseModuleContext) {
  458. test.testDecorator.linkerInit(ctx, test.libraryDecorator.baseLinker)
  459. test.libraryDecorator.linkerInit(ctx)
  460. }
  461. func (test *testLibrary) linkerDeps(ctx DepsContext, deps Deps) Deps {
  462. deps = test.testDecorator.linkerDeps(ctx, deps)
  463. deps = test.libraryDecorator.linkerDeps(ctx, deps)
  464. return deps
  465. }
  466. func (test *testLibrary) linkerFlags(ctx ModuleContext, flags Flags) Flags {
  467. flags = test.libraryDecorator.linkerFlags(ctx, flags)
  468. flags = test.testDecorator.linkerFlags(ctx, flags)
  469. return flags
  470. }
  471. func (test *testLibrary) installerProps() []interface{} {
  472. return append(test.baseInstaller.installerProps(), test.testDecorator.installerProps()...)
  473. }
  474. func NewTestLibrary(hod android.HostOrDeviceSupported) *Module {
  475. module, library := NewLibrary(android.HostAndDeviceSupported)
  476. library.baseInstaller = NewTestInstaller()
  477. test := &testLibrary{
  478. testDecorator: &testDecorator{
  479. linker: library.baseLinker,
  480. installer: library.baseInstaller,
  481. },
  482. libraryDecorator: library,
  483. }
  484. module.linker = test
  485. module.installer = test
  486. module.bazelable = true
  487. return module
  488. }
  489. type BenchmarkProperties struct {
  490. // list of files or filegroup modules that provide data that should be installed alongside
  491. // the test
  492. Data []string `android:"path"`
  493. // list of compatibility suites (for example "cts", "vts") that the module should be
  494. // installed into.
  495. Test_suites []string `android:"arch_variant"`
  496. // the name of the test configuration (for example "AndroidTest.xml") that should be
  497. // installed with the module.
  498. Test_config *string `android:"path,arch_variant"`
  499. // the name of the test configuration template (for example "AndroidTestTemplate.xml") that
  500. // should be installed with the module.
  501. Test_config_template *string `android:"path,arch_variant"`
  502. // Add RootTargetPreparer to auto generated test config. This guarantees the test to run
  503. // with root permission.
  504. Require_root *bool
  505. // Flag to indicate whether or not to create test config automatically. If AndroidTest.xml
  506. // doesn't exist next to the Android.bp, this attribute doesn't need to be set to true
  507. // explicitly.
  508. Auto_gen_config *bool
  509. }
  510. type benchmarkDecorator struct {
  511. *binaryDecorator
  512. Properties BenchmarkProperties
  513. data android.Paths
  514. testConfig android.Path
  515. }
  516. func (benchmark *benchmarkDecorator) benchmarkBinary() bool {
  517. return true
  518. }
  519. func (benchmark *benchmarkDecorator) linkerInit(ctx BaseModuleContext) {
  520. runpath := "../../lib"
  521. if ctx.toolchain().Is64Bit() {
  522. runpath += "64"
  523. }
  524. benchmark.baseLinker.dynamicProperties.RunPaths = append(benchmark.baseLinker.dynamicProperties.RunPaths, runpath)
  525. benchmark.binaryDecorator.linkerInit(ctx)
  526. }
  527. func (benchmark *benchmarkDecorator) linkerProps() []interface{} {
  528. props := benchmark.binaryDecorator.linkerProps()
  529. props = append(props, &benchmark.Properties)
  530. return props
  531. }
  532. func (benchmark *benchmarkDecorator) linkerDeps(ctx DepsContext, deps Deps) Deps {
  533. deps = benchmark.binaryDecorator.linkerDeps(ctx, deps)
  534. deps.StaticLibs = append(deps.StaticLibs, "libgoogle-benchmark")
  535. return deps
  536. }
  537. func (benchmark *benchmarkDecorator) install(ctx ModuleContext, file android.Path) {
  538. benchmark.data = android.PathsForModuleSrc(ctx, benchmark.Properties.Data)
  539. var configs []tradefed.Config
  540. if Bool(benchmark.Properties.Require_root) {
  541. configs = append(configs, tradefed.Object{"target_preparer", "com.android.tradefed.targetprep.RootTargetPreparer", nil})
  542. }
  543. benchmark.testConfig = tradefed.AutoGenTestConfig(ctx, tradefed.AutoGenTestConfigOptions{
  544. TestConfigProp: benchmark.Properties.Test_config,
  545. TestConfigTemplateProp: benchmark.Properties.Test_config_template,
  546. TestSuites: benchmark.Properties.Test_suites,
  547. Config: configs,
  548. AutoGenConfig: benchmark.Properties.Auto_gen_config,
  549. DeviceTemplate: "${NativeBenchmarkTestConfigTemplate}",
  550. HostTemplate: "${NativeBenchmarkTestConfigTemplate}",
  551. })
  552. benchmark.binaryDecorator.baseInstaller.dir = filepath.Join("benchmarktest", ctx.ModuleName())
  553. benchmark.binaryDecorator.baseInstaller.dir64 = filepath.Join("benchmarktest64", ctx.ModuleName())
  554. benchmark.binaryDecorator.baseInstaller.install(ctx, file)
  555. }
  556. func NewBenchmark(hod android.HostOrDeviceSupported) *Module {
  557. module, binary := newBinary(hod, false)
  558. module.multilib = android.MultilibBoth
  559. binary.baseInstaller = NewBaseInstaller("benchmarktest", "benchmarktest64", InstallInData)
  560. benchmark := &benchmarkDecorator{
  561. binaryDecorator: binary,
  562. }
  563. module.linker = benchmark
  564. module.installer = benchmark
  565. return module
  566. }
  567. type ccTestBazelHandler struct {
  568. module *Module
  569. }
  570. var _ BazelHandler = (*ccTestBazelHandler)(nil)
  571. func (handler *ccTestBazelHandler) QueueBazelCall(ctx android.BaseModuleContext, label string) {
  572. bazelCtx := ctx.Config().BazelContext
  573. bazelCtx.QueueBazelRequest(label, cquery.GetCcUnstrippedInfo, android.GetConfigKey(ctx))
  574. }
  575. func (handler *ccTestBazelHandler) ProcessBazelQueryResponse(ctx android.ModuleContext, label string) {
  576. bazelCtx := ctx.Config().BazelContext
  577. info, err := bazelCtx.GetCcUnstrippedInfo(label, android.GetConfigKey(ctx))
  578. if err != nil {
  579. ctx.ModuleErrorf(err.Error())
  580. return
  581. }
  582. outputFilePath := android.PathForBazelOut(ctx, info.OutputFile)
  583. handler.module.outputFile = android.OptionalPathForPath(outputFilePath)
  584. handler.module.linker.(*testBinary).unstrippedOutputFile = android.PathForBazelOut(ctx, info.UnstrippedOutput)
  585. }
  586. // binaryAttributes contains Bazel attributes corresponding to a cc test
  587. type testBinaryAttributes struct {
  588. binaryAttributes
  589. Gtest bool
  590. Isolated bool
  591. tidyAttributes
  592. tradefed.TestConfigAttributes
  593. }
  594. // testBinaryBp2build is the bp2build converter for cc_test modules. A cc_test's
  595. // dependency graph and compilation/linking steps are functionally similar to a
  596. // cc_binary, but has additional dependencies on test deps like gtest, and
  597. // produces additional runfiles like XML plans for Tradefed orchestration
  598. //
  599. // TODO(b/244432609): handle `isolated` property.
  600. // TODO(b/244432134): handle custom runpaths for tests that assume runfile layouts not
  601. // default to bazel. (see linkerInit function)
  602. func testBinaryBp2build(ctx android.TopDownMutatorContext, m *Module) {
  603. var testBinaryAttrs testBinaryAttributes
  604. testBinaryAttrs.binaryAttributes = binaryBp2buildAttrs(ctx, m)
  605. var data bazel.LabelListAttribute
  606. var tags bazel.StringListAttribute
  607. testBinaryProps := m.GetArchVariantProperties(ctx, &TestBinaryProperties{})
  608. for axis, configToProps := range testBinaryProps {
  609. for config, props := range configToProps {
  610. if p, ok := props.(*TestBinaryProperties); ok {
  611. // Combine data, data_bins and data_libs into a single 'data' attribute.
  612. var combinedData bazel.LabelList
  613. combinedData.Append(android.BazelLabelForModuleSrc(ctx, p.Data))
  614. combinedData.Append(android.BazelLabelForModuleDeps(ctx, p.Data_bins))
  615. combinedData.Append(android.BazelLabelForModuleDeps(ctx, p.Data_libs))
  616. data.SetSelectValue(axis, config, combinedData)
  617. tags.SetSelectValue(axis, config, p.Test_options.Tags)
  618. }
  619. }
  620. }
  621. m.convertTidyAttributes(ctx, &testBinaryAttrs.tidyAttributes)
  622. for _, propIntf := range m.GetProperties() {
  623. if testLinkerProps, ok := propIntf.(*TestLinkerProperties); ok {
  624. testBinaryAttrs.Gtest = proptools.BoolDefault(testLinkerProps.Gtest, true)
  625. testBinaryAttrs.Isolated = proptools.BoolDefault(testLinkerProps.Isolated, true)
  626. break
  627. }
  628. }
  629. for _, testProps := range m.GetProperties() {
  630. if p, ok := testProps.(*TestBinaryProperties); ok {
  631. useVendor := false // TODO Bug: 262914724
  632. testInstallBase := getTestInstallBase(useVendor)
  633. testConfigAttributes := tradefed.GetTestConfigAttributes(
  634. ctx,
  635. p.Test_config,
  636. p.Test_options.Extra_test_configs,
  637. p.Auto_gen_config,
  638. p.Test_options.Test_suite_tag,
  639. p.Test_config_template,
  640. getTradefedConfigOptions(ctx, p, testBinaryAttrs.Isolated),
  641. &testInstallBase,
  642. )
  643. testBinaryAttrs.TestConfigAttributes = testConfigAttributes
  644. }
  645. }
  646. // TODO (b/262914724): convert to tradefed_cc_test and tradefed_cc_test_host
  647. ctx.CreateBazelTargetModule(
  648. bazel.BazelTargetModuleProperties{
  649. Rule_class: "cc_test",
  650. Bzl_load_location: "//build/bazel/rules/cc:cc_test.bzl",
  651. },
  652. android.CommonAttributes{
  653. Name: m.Name(),
  654. Data: data,
  655. Tags: tags,
  656. },
  657. &testBinaryAttrs)
  658. }