blob: d3f9203a82b470be10ffab068d834feae590f69e [file] [log] [blame]
Adam Langleye9ada862015-05-11 17:20:37 -07001/* 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
15package main
16
17import (
Robert Sloan8ff03552017-06-14 12:40:58 -070018 "bufio"
Adam Langleye9ada862015-05-11 17:20:37 -070019 "bytes"
20 "encoding/json"
21 "flag"
22 "fmt"
Robert Sloan8ff03552017-06-14 12:40:58 -070023 "math/rand"
Adam Langleye9ada862015-05-11 17:20:37 -070024 "os"
25 "os/exec"
26 "path"
Robert Sloan572a4e22017-04-17 10:52:19 -070027 "runtime"
Adam Langleyf4e42722015-06-04 17:45:09 -070028 "strconv"
Adam Langleye9ada862015-05-11 17:20:37 -070029 "strings"
David Benjamin4969cc92016-04-22 15:02:23 -040030 "sync"
Adam Langleyf4e42722015-06-04 17:45:09 -070031 "syscall"
Adam Langleye9ada862015-05-11 17:20:37 -070032 "time"
33)
34
35// TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.
36
37var (
Adam Langleyf4e42722015-06-04 17:45:09 -070038 useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind")
David Benjamin4969cc92016-04-22 15:02:23 -040039 useCallgrind = flag.Bool("callgrind", false, "If true, run code under valgrind to generate callgrind traces.")
Adam Langleyf4e42722015-06-04 17:45:09 -070040 useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
Robert Sloan4d1ac502017-02-06 08:36:14 -080041 useSDE = flag.Bool("sde", false, "If true, run BoringSSL code under Intel's SDE for each supported chip")
Robert Sloan8ff03552017-06-14 12:40:58 -070042 sdePath = flag.String("sde-path", "sde", "The path to find the sde binary.")
Adam Langleyf4e42722015-06-04 17:45:09 -070043 buildDir = flag.String("build-dir", "build", "The build directory to run the tests from.")
Robert Sloan572a4e22017-04-17 10:52:19 -070044 numWorkers = flag.Int("num-workers", runtime.NumCPU(), "Runs the given number of workers when testing.")
Adam Langleyf4e42722015-06-04 17:45:09 -070045 jsonOutput = flag.String("json-output", "", "The file to output JSON results to.")
46 mallocTest = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
47 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.")
Adam Langleye9ada862015-05-11 17:20:37 -070048)
49
Robert Sloan4d1ac502017-02-06 08:36:14 -080050type test struct {
51 args []string
52 // cpu, if not empty, contains an Intel CPU code to simulate. Run
53 // `sde64 -help` to get a list of these codes.
54 cpu string
55}
Adam Langleye9ada862015-05-11 17:20:37 -070056
David Benjamin4969cc92016-04-22 15:02:23 -040057type result struct {
58 Test test
59 Passed bool
60 Error error
61}
62
Adam Langleye9ada862015-05-11 17:20:37 -070063// testOutput is a representation of Chromium's JSON test result format. See
64// https://www.chromium.org/developers/the-json-test-results-format
65type testOutput struct {
66 Version int `json:"version"`
67 Interrupted bool `json:"interrupted"`
68 PathDelimiter string `json:"path_delimiter"`
69 SecondsSinceEpoch float64 `json:"seconds_since_epoch"`
70 NumFailuresByType map[string]int `json:"num_failures_by_type"`
71 Tests map[string]testResult `json:"tests"`
72}
73
74type testResult struct {
75 Actual string `json:"actual"`
76 Expected string `json:"expected"`
77 IsUnexpected bool `json:"is_unexpected"`
78}
79
Robert Sloan4d1ac502017-02-06 08:36:14 -080080// sdeCPUs contains a list of CPU code that we run all tests under when *useSDE
81// is true.
82var sdeCPUs = []string{
83 "p4p", // Pentium4 Prescott
84 "mrm", // Merom
85 "pnr", // Penryn
86 "nhm", // Nehalem
87 "wsm", // Westmere
88 "snb", // Sandy Bridge
89 "ivb", // Ivy Bridge
90 "hsw", // Haswell
91 "bdw", // Broadwell
92 "skx", // Skylake Server
93 "skl", // Skylake Client
94 "cnl", // Cannonlake
95 "knl", // Knights Landing
96 "slt", // Saltwell
97 "slm", // Silvermont
98 "glm", // Goldmont
99}
100
Adam Langleye9ada862015-05-11 17:20:37 -0700101func newTestOutput() *testOutput {
102 return &testOutput{
103 Version: 3,
104 PathDelimiter: ".",
105 SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
106 NumFailuresByType: make(map[string]int),
107 Tests: make(map[string]testResult),
108 }
109}
110
111func (t *testOutput) addResult(name, result string) {
112 if _, found := t.Tests[name]; found {
113 panic(name)
114 }
115 t.Tests[name] = testResult{
116 Actual: result,
117 Expected: "PASS",
118 IsUnexpected: result != "PASS",
119 }
120 t.NumFailuresByType[result]++
121}
122
123func (t *testOutput) writeTo(name string) error {
124 file, err := os.Create(name)
125 if err != nil {
126 return err
127 }
128 defer file.Close()
129 out, err := json.MarshalIndent(t, "", " ")
130 if err != nil {
131 return err
132 }
133 _, err = file.Write(out)
134 return err
135}
136
137func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
David Benjamin7c0d06c2016-08-11 13:26:41 -0400138 valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
Adam Langleye9ada862015-05-11 17:20:37 -0700139 if dbAttach {
140 valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
141 }
142 valgrindArgs = append(valgrindArgs, path)
143 valgrindArgs = append(valgrindArgs, args...)
144
145 return exec.Command("valgrind", valgrindArgs...)
146}
147
David Benjamin4969cc92016-04-22 15:02:23 -0400148func callgrindOf(path string, args ...string) *exec.Cmd {
149 valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
150 valgrindArgs = append(valgrindArgs, path)
151 valgrindArgs = append(valgrindArgs, args...)
152
153 return exec.Command("valgrind", valgrindArgs...)
154}
155
Adam Langleyf4e42722015-06-04 17:45:09 -0700156func gdbOf(path string, args ...string) *exec.Cmd {
157 xtermArgs := []string{"-e", "gdb", "--args"}
158 xtermArgs = append(xtermArgs, path)
159 xtermArgs = append(xtermArgs, args...)
160
161 return exec.Command("xterm", xtermArgs...)
162}
163
Robert Sloan4d1ac502017-02-06 08:36:14 -0800164func sdeOf(cpu, path string, args ...string) *exec.Cmd {
Robert Sloanb6d070c2017-07-24 08:40:01 -0700165 sdeArgs := []string{"-" + cpu}
166 // The kernel's vdso code for gettimeofday sometimes uses the RDTSCP
167 // instruction. Although SDE has a -chip_check_vsyscall flag that
168 // excludes such code by default, it does not seem to work. Instead,
169 // pass the -chip_check_exe_only flag which retains test coverage when
170 // statically linked and excludes the vdso.
171 if cpu == "p4p" || cpu == "pnr" || cpu == "mrm" || cpu == "slt" {
172 sdeArgs = append(sdeArgs, "-chip_check_exe_only")
173 }
174 sdeArgs = append(sdeArgs, "--", path)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800175 sdeArgs = append(sdeArgs, args...)
Robert Sloan8ff03552017-06-14 12:40:58 -0700176 return exec.Command(*sdePath, sdeArgs...)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800177}
178
Adam Langleyf4e42722015-06-04 17:45:09 -0700179type moreMallocsError struct{}
180
181func (moreMallocsError) Error() string {
182 return "child process did not exhaust all allocation calls"
183}
184
185var errMoreMallocs = moreMallocsError{}
186
187func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800188 prog := path.Join(*buildDir, test.args[0])
189 args := test.args[1:]
Adam Langleye9ada862015-05-11 17:20:37 -0700190 var cmd *exec.Cmd
191 if *useValgrind {
192 cmd = valgrindOf(false, prog, args...)
David Benjamin4969cc92016-04-22 15:02:23 -0400193 } else if *useCallgrind {
194 cmd = callgrindOf(prog, args...)
Adam Langleyf4e42722015-06-04 17:45:09 -0700195 } else if *useGDB {
196 cmd = gdbOf(prog, args...)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800197 } else if *useSDE {
198 cmd = sdeOf(test.cpu, prog, args...)
Adam Langleye9ada862015-05-11 17:20:37 -0700199 } else {
200 cmd = exec.Command(prog, args...)
201 }
Robert Sloan5d625782017-02-13 09:55:39 -0800202 var outBuf bytes.Buffer
203 cmd.Stdout = &outBuf
204 cmd.Stderr = &outBuf
Adam Langleyf4e42722015-06-04 17:45:09 -0700205 if mallocNumToFail >= 0 {
206 cmd.Env = os.Environ()
207 cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
208 if *mallocTestDebug {
209 cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
210 }
211 cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
212 }
Adam Langleye9ada862015-05-11 17:20:37 -0700213
214 if err := cmd.Start(); err != nil {
215 return false, err
216 }
217 if err := cmd.Wait(); err != nil {
Adam Langleyf4e42722015-06-04 17:45:09 -0700218 if exitError, ok := err.(*exec.ExitError); ok {
219 if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
220 return false, errMoreMallocs
221 }
222 }
Robert Sloan5d625782017-02-13 09:55:39 -0800223 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700224 return false, err
225 }
226
227 // Account for Windows line-endings.
Robert Sloan5d625782017-02-13 09:55:39 -0800228 stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
Adam Langleye9ada862015-05-11 17:20:37 -0700229
230 if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
231 (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
232 return true, nil
233 }
David Benjaminf31229b2017-01-25 14:08:15 -0500234
235 // Also accept a googletest-style pass line. This is left here in
236 // transition until the tests are all converted and this script made
237 // unnecessary.
238 if bytes.Contains(stdout, []byte("\n[ PASSED ]")) {
239 return true, nil
240 }
241
Robert Sloan5d625782017-02-13 09:55:39 -0800242 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700243 return false, nil
244}
245
Adam Langleyf4e42722015-06-04 17:45:09 -0700246func runTest(test test) (bool, error) {
247 if *mallocTest < 0 {
248 return runTestOnce(test, -1)
249 }
250
251 for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
252 if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
253 if err != nil {
254 err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
255 }
256 return passed, err
257 }
258 }
259}
260
Robert Sloan572a4e22017-04-17 10:52:19 -0700261// shortTestName returns the short name of a test. Except for evp_test and
262// cipher_test, it assumes that any argument which ends in .txt is a path to a
263// data file and not relevant to the test's uniqueness.
Adam Langleye9ada862015-05-11 17:20:37 -0700264func shortTestName(test test) string {
265 var args []string
Robert Sloan4d1ac502017-02-06 08:36:14 -0800266 for _, arg := range test.args {
Robert Sloan8ff03552017-06-14 12:40:58 -0700267 if test.args[0] == "crypto/evp/evp_test" || test.args[0] == "crypto/cipher_extra/cipher_test" || test.args[0] == "crypto/cipher_extra/aead_test" || !strings.HasSuffix(arg, ".txt") || strings.HasPrefix(arg, "--gtest_filter=") {
Adam Langleye9ada862015-05-11 17:20:37 -0700268 args = append(args, arg)
269 }
270 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800271 return strings.Join(args, " ") + test.cpuMsg()
Adam Langleye9ada862015-05-11 17:20:37 -0700272}
273
Kenny Rootb8494592015-09-25 02:29:14 +0000274// setWorkingDirectory walks up directories as needed until the current working
275// directory is the top of a BoringSSL checkout.
276func setWorkingDirectory() {
277 for i := 0; i < 64; i++ {
278 if _, err := os.Stat("BUILDING.md"); err == nil {
279 return
280 }
281 os.Chdir("..")
282 }
283
284 panic("Couldn't find BUILDING.md in a parent directory!")
285}
286
287func parseTestConfig(filename string) ([]test, error) {
288 in, err := os.Open(filename)
289 if err != nil {
290 return nil, err
291 }
292 defer in.Close()
293
294 decoder := json.NewDecoder(in)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800295 var testArgs [][]string
296 if err := decoder.Decode(&testArgs); err != nil {
Kenny Rootb8494592015-09-25 02:29:14 +0000297 return nil, err
298 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800299
300 var result []test
301 for _, args := range testArgs {
302 result = append(result, test{args: args})
303 }
Kenny Rootb8494592015-09-25 02:29:14 +0000304 return result, nil
305}
306
David Benjamin4969cc92016-04-22 15:02:23 -0400307func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
308 defer done.Done()
309 for test := range tests {
310 passed, err := runTest(test)
311 results <- result{test, passed, err}
312 }
313}
314
Robert Sloan4d1ac502017-02-06 08:36:14 -0800315func (t test) cpuMsg() string {
316 if len(t.cpu) == 0 {
317 return ""
318 }
319
320 return fmt.Sprintf(" (for CPU %q)", t.cpu)
321}
322
Robert Sloan8ff03552017-06-14 12:40:58 -0700323func (t test) getGTestShards() ([]test, error) {
324 if *numWorkers == 1 || len(t.args) != 1 {
325 return []test{t}, nil
326 }
327
328 // Only shard the three GTest-based tests.
329 if t.args[0] != "crypto/crypto_test" && t.args[0] != "ssl/ssl_test" && t.args[0] != "decrepit/decrepit_test" {
330 return []test{t}, nil
331 }
332
333 prog := path.Join(*buildDir, t.args[0])
334 cmd := exec.Command(prog, "--gtest_list_tests")
335 var stdout bytes.Buffer
336 cmd.Stdout = &stdout
337 if err := cmd.Start(); err != nil {
338 return nil, err
339 }
340 if err := cmd.Wait(); err != nil {
341 return nil, err
342 }
343
344 var group string
345 var tests []string
346 scanner := bufio.NewScanner(&stdout)
347 for scanner.Scan() {
348 line := scanner.Text()
349
350 // Remove the parameter comment and trailing space.
351 if idx := strings.Index(line, "#"); idx >= 0 {
352 line = line[:idx]
353 }
354 line = strings.TrimSpace(line)
355 if len(line) == 0 {
356 continue
357 }
358
359 if line[len(line)-1] == '.' {
360 group = line
361 continue
362 }
363
364 if len(group) == 0 {
365 return nil, fmt.Errorf("found test case %q without group", line)
366 }
367 tests = append(tests, group+line)
368 }
369
370 const testsPerShard = 20
371 if len(tests) <= testsPerShard {
372 return []test{t}, nil
373 }
374
375 // Slow tests which process large test vector files tend to be grouped
376 // together, so shuffle the order.
377 shuffled := make([]string, len(tests))
378 perm := rand.Perm(len(tests))
379 for i, j := range perm {
380 shuffled[i] = tests[j]
381 }
382
383 var shards []test
384 for i := 0; i < len(shuffled); i += testsPerShard {
385 n := len(shuffled) - i
386 if n > testsPerShard {
387 n = testsPerShard
388 }
389 shard := t
390 shard.args = []string{shard.args[0], "--gtest_filter=" + strings.Join(shuffled[i:i+n], ":")}
391 shards = append(shards, shard)
392 }
393
394 return shards, nil
395}
396
Adam Langleye9ada862015-05-11 17:20:37 -0700397func main() {
398 flag.Parse()
Kenny Rootb8494592015-09-25 02:29:14 +0000399 setWorkingDirectory()
400
David Benjamin4969cc92016-04-22 15:02:23 -0400401 testCases, err := parseTestConfig("util/all_tests.json")
Kenny Rootb8494592015-09-25 02:29:14 +0000402 if err != nil {
403 fmt.Printf("Failed to parse input: %s\n", err)
404 os.Exit(1)
405 }
Adam Langleye9ada862015-05-11 17:20:37 -0700406
David Benjamin4969cc92016-04-22 15:02:23 -0400407 var wg sync.WaitGroup
408 tests := make(chan test, *numWorkers)
409 results := make(chan result, *numWorkers)
410
411 for i := 0; i < *numWorkers; i++ {
412 wg.Add(1)
413 go worker(tests, results, &wg)
414 }
415
416 go func() {
417 for _, test := range testCases {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800418 if *useSDE {
Robert Sloan8ff03552017-06-14 12:40:58 -0700419 // SDE generates plenty of tasks and gets slower
420 // with additional sharding.
Robert Sloan4d1ac502017-02-06 08:36:14 -0800421 for _, cpu := range sdeCPUs {
422 testForCPU := test
423 testForCPU.cpu = cpu
424 tests <- testForCPU
425 }
426 } else {
Robert Sloan8ff03552017-06-14 12:40:58 -0700427 shards, err := test.getGTestShards()
428 if err != nil {
429 fmt.Printf("Error listing tests: %s\n", err)
430 os.Exit(1)
431 }
432 for _, shard := range shards {
433 tests <- shard
434 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800435 }
David Benjamin4969cc92016-04-22 15:02:23 -0400436 }
437 close(tests)
438
439 wg.Wait()
440 close(results)
441 }()
442
Adam Langleye9ada862015-05-11 17:20:37 -0700443 testOutput := newTestOutput()
444 var failed []test
David Benjamin4969cc92016-04-22 15:02:23 -0400445 for testResult := range results {
446 test := testResult.Test
Robert Sloan4d1ac502017-02-06 08:36:14 -0800447 args := test.args
Adam Langleye9ada862015-05-11 17:20:37 -0700448
Robert Sloan4d1ac502017-02-06 08:36:14 -0800449 fmt.Printf("%s%s\n", strings.Join(args, " "), test.cpuMsg())
Adam Langleye9ada862015-05-11 17:20:37 -0700450 name := shortTestName(test)
David Benjamin4969cc92016-04-22 15:02:23 -0400451 if testResult.Error != nil {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800452 fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
Adam Langleye9ada862015-05-11 17:20:37 -0700453 failed = append(failed, test)
454 testOutput.addResult(name, "CRASHED")
David Benjamin4969cc92016-04-22 15:02:23 -0400455 } else if !testResult.Passed {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800456 fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
Adam Langleye9ada862015-05-11 17:20:37 -0700457 failed = append(failed, test)
458 testOutput.addResult(name, "FAIL")
459 } else {
460 testOutput.addResult(name, "PASS")
461 }
462 }
463
464 if *jsonOutput != "" {
465 if err := testOutput.writeTo(*jsonOutput); err != nil {
466 fmt.Fprintf(os.Stderr, "Error: %s\n", err)
467 }
468 }
469
470 if len(failed) > 0 {
David Benjamin4969cc92016-04-22 15:02:23 -0400471 fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
Adam Langleye9ada862015-05-11 17:20:37 -0700472 for _, test := range failed {
Robert Sloan8ff03552017-06-14 12:40:58 -0700473 fmt.Printf("\t%s%s\n", strings.Join(test.args, " "), test.cpuMsg())
Adam Langleye9ada862015-05-11 17:20:37 -0700474 }
475 os.Exit(1)
476 }
477
478 fmt.Printf("\nAll tests passed!\n")
479}