test.go 27 KB

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