You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

all_tests.go 13 KiB

Do a cursory conversion of a few tests to GTest. For now, this is the laziest conversion possible. The intent is to just get the build setup ready so that we can get everything working in our consumers. The intended end state is: - The standalone build produces three test targets, one per library: {crypto,ssl,decrepit}_tests. - Each FOO_test is made up of: FOO/**/*_test.cc crypto/test/gtest_main.cc test_support - generate_build_files.py emits variables crypto_test_sources and ssl_test_sources. These variables are populated with FindCFiles, looking for *_test.cc. - The consuming file assembles those variables into the two test targets (plus decrepit) from there. This avoids having generate_build_files.py emit actual build rules. - Our standalone builders, Chromium, and Android just run the top-level test targets using whatever GTest-based reporting story they have. In transition, we start by converting one of two tests in each library to populate the three test targets. Those are added to all_tests.json and all_tests.go hacked to handle them transparently. This keeps our standalone builder working. generate_build_files.py, to start with, populates the new source lists manually and subtracts them out of the old machinery. We emit both for the time being. When this change rolls in, we'll write all the build glue needed to build the GTest-based tests and add it to consumers' continuous builders. Next, we'll subsume a file-based test and get the consumers working with that. (I.e. make sure the GTest targets can depend on a data file.) Once that's all done, we'll be sure all this will work. At that point, we start subsuming the remaining tests into the GTest targets and, asynchronously, rewriting tests to use GTest properly rather than cursory conversion here. When all non-GTest tests are gone, the old generate_build_files.py hooks will be removed, consumers updated to not depend on them, and standalone builders converted to not rely on all_tests.go, which can then be removed. (Unless bits end up being needed as a malloc test driver. I'm thinking we'll want to do something with --gtest_filter.) As part of this CL, I've bumped the CMake requirements (for target_include_directories) and added a few suppressions for warnings that GTest doesn't pass. BUG=129 Change-Id: I881b26b07a8739cc0b52dbb51a30956908e1b71a Reviewed-on: https://boringssl-review.googlesource.com/13232 Reviewed-by: Adam Langley <agl@google.com>
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /* Copyright (c) 2015, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. package main
  15. import (
  16. "bufio"
  17. "bytes"
  18. "encoding/json"
  19. "flag"
  20. "fmt"
  21. "math/rand"
  22. "os"
  23. "os/exec"
  24. "path"
  25. "runtime"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "syscall"
  30. "time"
  31. )
  32. // TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.
  33. var (
  34. useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind")
  35. useCallgrind = flag.Bool("callgrind", false, "If true, run code under valgrind to generate callgrind traces.")
  36. useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
  37. useSDE = flag.Bool("sde", false, "If true, run BoringSSL code under Intel's SDE for each supported chip")
  38. sdePath = flag.String("sde-path", "sde", "The path to find the sde binary.")
  39. buildDir = flag.String("build-dir", "build", "The build directory to run the tests from.")
  40. numWorkers = flag.Int("num-workers", runtime.NumCPU(), "Runs the given number of workers when testing.")
  41. jsonOutput = flag.String("json-output", "", "The file to output JSON results to.")
  42. mallocTest = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
  43. mallocTestDebug = flag.Bool("malloc-test-debug", false, "If true, ask each test to abort rather than fail a malloc. This can be used with a specific value for --malloc-test to identity the malloc failing that is causing problems.")
  44. )
  45. type test struct {
  46. args []string
  47. shard, numShards int
  48. // cpu, if not empty, contains an Intel CPU code to simulate. Run
  49. // `sde64 -help` to get a list of these codes.
  50. cpu string
  51. }
  52. type result struct {
  53. Test test
  54. Passed bool
  55. Error error
  56. }
  57. // testOutput is a representation of Chromium's JSON test result format. See
  58. // https://www.chromium.org/developers/the-json-test-results-format
  59. type testOutput struct {
  60. Version int `json:"version"`
  61. Interrupted bool `json:"interrupted"`
  62. PathDelimiter string `json:"path_delimiter"`
  63. SecondsSinceEpoch float64 `json:"seconds_since_epoch"`
  64. NumFailuresByType map[string]int `json:"num_failures_by_type"`
  65. Tests map[string]testResult `json:"tests"`
  66. }
  67. type testResult struct {
  68. Actual string `json:"actual"`
  69. Expected string `json:"expected"`
  70. IsUnexpected bool `json:"is_unexpected"`
  71. }
  72. // sdeCPUs contains a list of CPU code that we run all tests under when *useSDE
  73. // is true.
  74. var sdeCPUs = []string{
  75. "p4p", // Pentium4 Prescott
  76. "mrm", // Merom
  77. "pnr", // Penryn
  78. "nhm", // Nehalem
  79. "wsm", // Westmere
  80. "snb", // Sandy Bridge
  81. "ivb", // Ivy Bridge
  82. "hsw", // Haswell
  83. "bdw", // Broadwell
  84. "skx", // Skylake Server
  85. "skl", // Skylake Client
  86. "cnl", // Cannonlake
  87. "knl", // Knights Landing
  88. "slt", // Saltwell
  89. "slm", // Silvermont
  90. "glm", // Goldmont
  91. "knm", // Knights Mill
  92. }
  93. func newTestOutput() *testOutput {
  94. return &testOutput{
  95. Version: 3,
  96. PathDelimiter: ".",
  97. SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
  98. NumFailuresByType: make(map[string]int),
  99. Tests: make(map[string]testResult),
  100. }
  101. }
  102. func (t *testOutput) addResult(name, result string) {
  103. if _, found := t.Tests[name]; found {
  104. panic(name)
  105. }
  106. t.Tests[name] = testResult{
  107. Actual: result,
  108. Expected: "PASS",
  109. IsUnexpected: result != "PASS",
  110. }
  111. t.NumFailuresByType[result]++
  112. }
  113. func (t *testOutput) writeTo(name string) error {
  114. file, err := os.Create(name)
  115. if err != nil {
  116. return err
  117. }
  118. defer file.Close()
  119. out, err := json.MarshalIndent(t, "", " ")
  120. if err != nil {
  121. return err
  122. }
  123. _, err = file.Write(out)
  124. return err
  125. }
  126. func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
  127. valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
  128. if dbAttach {
  129. valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
  130. }
  131. valgrindArgs = append(valgrindArgs, path)
  132. valgrindArgs = append(valgrindArgs, args...)
  133. return exec.Command("valgrind", valgrindArgs...)
  134. }
  135. func callgrindOf(path string, args ...string) *exec.Cmd {
  136. valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
  137. valgrindArgs = append(valgrindArgs, path)
  138. valgrindArgs = append(valgrindArgs, args...)
  139. return exec.Command("valgrind", valgrindArgs...)
  140. }
  141. func gdbOf(path string, args ...string) *exec.Cmd {
  142. xtermArgs := []string{"-e", "gdb", "--args"}
  143. xtermArgs = append(xtermArgs, path)
  144. xtermArgs = append(xtermArgs, args...)
  145. return exec.Command("xterm", xtermArgs...)
  146. }
  147. func sdeOf(cpu, path string, args ...string) *exec.Cmd {
  148. sdeArgs := []string{"-" + cpu}
  149. // The kernel's vdso code for gettimeofday sometimes uses the RDTSCP
  150. // instruction. Although SDE has a -chip_check_vsyscall flag that
  151. // excludes such code by default, it does not seem to work. Instead,
  152. // pass the -chip_check_exe_only flag which retains test coverage when
  153. // statically linked and excludes the vdso.
  154. if cpu == "p4p" || cpu == "pnr" || cpu == "mrm" || cpu == "slt" {
  155. sdeArgs = append(sdeArgs, "-chip_check_exe_only")
  156. }
  157. sdeArgs = append(sdeArgs, "--", path)
  158. sdeArgs = append(sdeArgs, args...)
  159. return exec.Command(*sdePath, sdeArgs...)
  160. }
  161. type moreMallocsError struct{}
  162. func (moreMallocsError) Error() string {
  163. return "child process did not exhaust all allocation calls"
  164. }
  165. var errMoreMallocs = moreMallocsError{}
  166. func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
  167. prog := path.Join(*buildDir, test.args[0])
  168. args := test.args[1:]
  169. var cmd *exec.Cmd
  170. if *useValgrind {
  171. cmd = valgrindOf(false, prog, args...)
  172. } else if *useCallgrind {
  173. cmd = callgrindOf(prog, args...)
  174. } else if *useGDB {
  175. cmd = gdbOf(prog, args...)
  176. } else if *useSDE {
  177. cmd = sdeOf(test.cpu, prog, args...)
  178. } else {
  179. cmd = exec.Command(prog, args...)
  180. }
  181. var outBuf bytes.Buffer
  182. cmd.Stdout = &outBuf
  183. cmd.Stderr = &outBuf
  184. if mallocNumToFail >= 0 {
  185. cmd.Env = os.Environ()
  186. cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
  187. if *mallocTestDebug {
  188. cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
  189. }
  190. cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
  191. }
  192. if err := cmd.Start(); err != nil {
  193. return false, err
  194. }
  195. if err := cmd.Wait(); err != nil {
  196. if exitError, ok := err.(*exec.ExitError); ok {
  197. if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
  198. return false, errMoreMallocs
  199. }
  200. }
  201. fmt.Print(string(outBuf.Bytes()))
  202. return false, err
  203. }
  204. // Account for Windows line-endings.
  205. stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
  206. if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
  207. (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
  208. return true, nil
  209. }
  210. // Also accept a googletest-style pass line. This is left here in
  211. // transition until the tests are all converted and this script made
  212. // unnecessary.
  213. if bytes.Contains(stdout, []byte("\n[ PASSED ]")) {
  214. return true, nil
  215. }
  216. fmt.Print(string(outBuf.Bytes()))
  217. return false, nil
  218. }
  219. func runTest(test test) (bool, error) {
  220. if *mallocTest < 0 {
  221. return runTestOnce(test, -1)
  222. }
  223. for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
  224. if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
  225. if err != nil {
  226. err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
  227. }
  228. return passed, err
  229. }
  230. }
  231. }
  232. // setWorkingDirectory walks up directories as needed until the current working
  233. // directory is the top of a BoringSSL checkout.
  234. func setWorkingDirectory() {
  235. for i := 0; i < 64; i++ {
  236. if _, err := os.Stat("BUILDING.md"); err == nil {
  237. return
  238. }
  239. os.Chdir("..")
  240. }
  241. panic("Couldn't find BUILDING.md in a parent directory!")
  242. }
  243. func parseTestConfig(filename string) ([]test, error) {
  244. in, err := os.Open(filename)
  245. if err != nil {
  246. return nil, err
  247. }
  248. defer in.Close()
  249. decoder := json.NewDecoder(in)
  250. var testArgs [][]string
  251. if err := decoder.Decode(&testArgs); err != nil {
  252. return nil, err
  253. }
  254. var result []test
  255. for _, args := range testArgs {
  256. result = append(result, test{args: args})
  257. }
  258. return result, nil
  259. }
  260. func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
  261. defer done.Done()
  262. for test := range tests {
  263. passed, err := runTest(test)
  264. results <- result{test, passed, err}
  265. }
  266. }
  267. func (t test) shortName() string {
  268. return t.args[0] + t.shardMsg() + t.cpuMsg()
  269. }
  270. func (t test) longName() string {
  271. return strings.Join(t.args, " ") + t.cpuMsg()
  272. }
  273. func (t test) shardMsg() string {
  274. if t.numShards == 0 {
  275. return ""
  276. }
  277. return fmt.Sprintf(" [shard %d/%d]", t.shard+1, t.numShards)
  278. }
  279. func (t test) cpuMsg() string {
  280. if len(t.cpu) == 0 {
  281. return ""
  282. }
  283. return fmt.Sprintf(" (for CPU %q)", t.cpu)
  284. }
  285. func (t test) getGTestShards() ([]test, error) {
  286. if *numWorkers == 1 || len(t.args) != 1 {
  287. return []test{t}, nil
  288. }
  289. // Only shard the three GTest-based tests.
  290. if t.args[0] != "crypto/crypto_test" && t.args[0] != "ssl/ssl_test" && t.args[0] != "decrepit/decrepit_test" {
  291. return []test{t}, nil
  292. }
  293. prog := path.Join(*buildDir, t.args[0])
  294. cmd := exec.Command(prog, "--gtest_list_tests")
  295. var stdout bytes.Buffer
  296. cmd.Stdout = &stdout
  297. if err := cmd.Start(); err != nil {
  298. return nil, err
  299. }
  300. if err := cmd.Wait(); err != nil {
  301. return nil, err
  302. }
  303. var group string
  304. var tests []string
  305. scanner := bufio.NewScanner(&stdout)
  306. for scanner.Scan() {
  307. line := scanner.Text()
  308. // Remove the parameter comment and trailing space.
  309. if idx := strings.Index(line, "#"); idx >= 0 {
  310. line = line[:idx]
  311. }
  312. line = strings.TrimSpace(line)
  313. if len(line) == 0 {
  314. continue
  315. }
  316. if line[len(line)-1] == '.' {
  317. group = line
  318. continue
  319. }
  320. if len(group) == 0 {
  321. return nil, fmt.Errorf("found test case %q without group", line)
  322. }
  323. tests = append(tests, group+line)
  324. }
  325. const testsPerShard = 20
  326. if len(tests) <= testsPerShard {
  327. return []test{t}, nil
  328. }
  329. // Slow tests which process large test vector files tend to be grouped
  330. // together, so shuffle the order.
  331. shuffled := make([]string, len(tests))
  332. perm := rand.Perm(len(tests))
  333. for i, j := range perm {
  334. shuffled[i] = tests[j]
  335. }
  336. var shards []test
  337. for i := 0; i < len(shuffled); i += testsPerShard {
  338. n := len(shuffled) - i
  339. if n > testsPerShard {
  340. n = testsPerShard
  341. }
  342. shard := t
  343. shard.args = []string{shard.args[0], "--gtest_filter=" + strings.Join(shuffled[i:i+n], ":")}
  344. shard.shard = len(shards)
  345. shards = append(shards, shard)
  346. }
  347. for i := range shards {
  348. shards[i].numShards = len(shards)
  349. }
  350. return shards, nil
  351. }
  352. func main() {
  353. flag.Parse()
  354. setWorkingDirectory()
  355. testCases, err := parseTestConfig("util/all_tests.json")
  356. if err != nil {
  357. fmt.Printf("Failed to parse input: %s\n", err)
  358. os.Exit(1)
  359. }
  360. var wg sync.WaitGroup
  361. tests := make(chan test, *numWorkers)
  362. results := make(chan result, *numWorkers)
  363. for i := 0; i < *numWorkers; i++ {
  364. wg.Add(1)
  365. go worker(tests, results, &wg)
  366. }
  367. go func() {
  368. for _, test := range testCases {
  369. if *useSDE {
  370. // SDE generates plenty of tasks and gets slower
  371. // with additional sharding.
  372. for _, cpu := range sdeCPUs {
  373. testForCPU := test
  374. testForCPU.cpu = cpu
  375. tests <- testForCPU
  376. }
  377. } else {
  378. shards, err := test.getGTestShards()
  379. if err != nil {
  380. fmt.Printf("Error listing tests: %s\n", err)
  381. os.Exit(1)
  382. }
  383. for _, shard := range shards {
  384. tests <- shard
  385. }
  386. }
  387. }
  388. close(tests)
  389. wg.Wait()
  390. close(results)
  391. }()
  392. testOutput := newTestOutput()
  393. var failed []test
  394. for testResult := range results {
  395. test := testResult.Test
  396. args := test.args
  397. if testResult.Error != nil {
  398. fmt.Printf("%s\n", test.longName())
  399. fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
  400. failed = append(failed, test)
  401. testOutput.addResult(test.longName(), "CRASHED")
  402. } else if !testResult.Passed {
  403. fmt.Printf("%s\n", test.longName())
  404. fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
  405. failed = append(failed, test)
  406. testOutput.addResult(test.longName(), "FAIL")
  407. } else {
  408. fmt.Printf("%s\n", test.shortName())
  409. testOutput.addResult(test.longName(), "PASS")
  410. }
  411. }
  412. if *jsonOutput != "" {
  413. if err := testOutput.writeTo(*jsonOutput); err != nil {
  414. fmt.Fprintf(os.Stderr, "Error: %s\n", err)
  415. }
  416. }
  417. if len(failed) > 0 {
  418. fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
  419. for _, test := range failed {
  420. fmt.Printf("\t%s%s\n", strings.Join(test.args, " "), test.cpuMsg())
  421. }
  422. os.Exit(1)
  423. }
  424. fmt.Printf("\nAll tests passed!\n")
  425. }