test.go 27 KB

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