Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

491 рядки
13 KiB

  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. }