blob: ef23080e8d7ae0a83335dfa9c694f843985da5a4 [file] [log] [blame]
David Benjamin491b9212015-02-11 14:18:45 -05001/* 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 (
David Benjamin3d14a152017-06-07 14:02:03 -040018 "bufio"
David Benjamin491b9212015-02-11 14:18:45 -050019 "bytes"
David Benjamin5f237bc2015-02-11 17:14:15 -050020 "encoding/json"
David Benjamin491b9212015-02-11 14:18:45 -050021 "flag"
22 "fmt"
David Benjamin3d14a152017-06-07 14:02:03 -040023 "math/rand"
David Benjamin491b9212015-02-11 14:18:45 -050024 "os"
25 "os/exec"
26 "path"
Adam Langley31fa5a42017-04-11 17:07:27 -070027 "runtime"
David Benjamin0b635c52015-05-15 19:08:49 -040028 "strconv"
David Benjamin491b9212015-02-11 14:18:45 -050029 "strings"
Steven Valdez32223942016-03-02 11:53:07 -050030 "sync"
David Benjamin0b635c52015-05-15 19:08:49 -040031 "syscall"
David Benjamin5f237bc2015-02-11 17:14:15 -050032 "time"
David Benjamin491b9212015-02-11 14:18:45 -050033)
34
35// TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.
36
37var (
David Benjamin0b635c52015-05-15 19:08:49 -040038 useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind")
Steven Valdezab14a4a2016-02-29 16:58:26 -050039 useCallgrind = flag.Bool("callgrind", false, "If true, run code under valgrind to generate callgrind traces.")
David Benjamin0b635c52015-05-15 19:08:49 -040040 useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
Adam Langleye212f272017-02-03 08:52:21 -080041 useSDE = flag.Bool("sde", false, "If true, run BoringSSL code under Intel's SDE for each supported chip")
David Benjamin799676c2017-05-10 16:56:02 -040042 sdePath = flag.String("sde-path", "sde", "The path to find the sde binary.")
David Benjamin0b635c52015-05-15 19:08:49 -040043 buildDir = flag.String("build-dir", "build", "The build directory to run the tests from.")
Adam Langley31fa5a42017-04-11 17:07:27 -070044 numWorkers = flag.Int("num-workers", runtime.NumCPU(), "Runs the given number of workers when testing.")
David Benjamin0b635c52015-05-15 19:08:49 -040045 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.")
David Benjamin491b9212015-02-11 14:18:45 -050048)
49
Adam Langleye212f272017-02-03 08:52:21 -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}
David Benjamin491b9212015-02-11 14:18:45 -050056
Steven Valdez32223942016-03-02 11:53:07 -050057type result struct {
58 Test test
59 Passed bool
60 Error error
61}
62
David Benjamin5f237bc2015-02-11 17:14:15 -050063// 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 {
David Benjamin7ead6052015-04-04 03:57:26 -040075 Actual string `json:"actual"`
76 Expected string `json:"expected"`
77 IsUnexpected bool `json:"is_unexpected"`
David Benjamin5f237bc2015-02-11 17:14:15 -050078}
79
Adam Langleye212f272017-02-03 08:52:21 -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
David Benjamind4e37952017-07-25 16:59:58 -040099 "knm", // Knights Mill
Adam Langleye212f272017-02-03 08:52:21 -0800100}
101
David Benjamin5f237bc2015-02-11 17:14:15 -0500102func newTestOutput() *testOutput {
103 return &testOutput{
104 Version: 3,
105 PathDelimiter: ".",
106 SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
107 NumFailuresByType: make(map[string]int),
108 Tests: make(map[string]testResult),
109 }
110}
111
112func (t *testOutput) addResult(name, result string) {
113 if _, found := t.Tests[name]; found {
114 panic(name)
115 }
David Benjamin7ead6052015-04-04 03:57:26 -0400116 t.Tests[name] = testResult{
117 Actual: result,
118 Expected: "PASS",
119 IsUnexpected: result != "PASS",
120 }
David Benjamin5f237bc2015-02-11 17:14:15 -0500121 t.NumFailuresByType[result]++
122}
123
124func (t *testOutput) writeTo(name string) error {
125 file, err := os.Create(name)
126 if err != nil {
127 return err
128 }
129 defer file.Close()
130 out, err := json.MarshalIndent(t, "", " ")
131 if err != nil {
132 return err
133 }
134 _, err = file.Write(out)
135 return err
136}
137
David Benjamin491b9212015-02-11 14:18:45 -0500138func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
David Benjamind2ba8892016-09-20 19:41:04 -0400139 valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
David Benjamin491b9212015-02-11 14:18:45 -0500140 if dbAttach {
141 valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
142 }
143 valgrindArgs = append(valgrindArgs, path)
144 valgrindArgs = append(valgrindArgs, args...)
145
146 return exec.Command("valgrind", valgrindArgs...)
147}
148
Steven Valdezab14a4a2016-02-29 16:58:26 -0500149func callgrindOf(path string, args ...string) *exec.Cmd {
150 valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
151 valgrindArgs = append(valgrindArgs, path)
152 valgrindArgs = append(valgrindArgs, args...)
153
154 return exec.Command("valgrind", valgrindArgs...)
155}
156
David Benjamin0b635c52015-05-15 19:08:49 -0400157func gdbOf(path string, args ...string) *exec.Cmd {
158 xtermArgs := []string{"-e", "gdb", "--args"}
159 xtermArgs = append(xtermArgs, path)
160 xtermArgs = append(xtermArgs, args...)
161
162 return exec.Command("xterm", xtermArgs...)
163}
164
Adam Langleye212f272017-02-03 08:52:21 -0800165func sdeOf(cpu, path string, args ...string) *exec.Cmd {
David Benjaminc5304e42017-07-17 16:15:16 -0400166 sdeArgs := []string{"-" + cpu}
167 // The kernel's vdso code for gettimeofday sometimes uses the RDTSCP
168 // instruction. Although SDE has a -chip_check_vsyscall flag that
169 // excludes such code by default, it does not seem to work. Instead,
170 // pass the -chip_check_exe_only flag which retains test coverage when
171 // statically linked and excludes the vdso.
172 if cpu == "p4p" || cpu == "pnr" || cpu == "mrm" || cpu == "slt" {
173 sdeArgs = append(sdeArgs, "-chip_check_exe_only")
174 }
175 sdeArgs = append(sdeArgs, "--", path)
Adam Langleye212f272017-02-03 08:52:21 -0800176 sdeArgs = append(sdeArgs, args...)
David Benjamin799676c2017-05-10 16:56:02 -0400177 return exec.Command(*sdePath, sdeArgs...)
Adam Langleye212f272017-02-03 08:52:21 -0800178}
179
David Benjamin0b635c52015-05-15 19:08:49 -0400180type moreMallocsError struct{}
181
182func (moreMallocsError) Error() string {
183 return "child process did not exhaust all allocation calls"
184}
185
186var errMoreMallocs = moreMallocsError{}
187
188func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
Adam Langleye212f272017-02-03 08:52:21 -0800189 prog := path.Join(*buildDir, test.args[0])
190 args := test.args[1:]
David Benjamin491b9212015-02-11 14:18:45 -0500191 var cmd *exec.Cmd
192 if *useValgrind {
193 cmd = valgrindOf(false, prog, args...)
Steven Valdezab14a4a2016-02-29 16:58:26 -0500194 } else if *useCallgrind {
195 cmd = callgrindOf(prog, args...)
David Benjamin0b635c52015-05-15 19:08:49 -0400196 } else if *useGDB {
197 cmd = gdbOf(prog, args...)
Adam Langleye212f272017-02-03 08:52:21 -0800198 } else if *useSDE {
199 cmd = sdeOf(test.cpu, prog, args...)
David Benjamin491b9212015-02-11 14:18:45 -0500200 } else {
201 cmd = exec.Command(prog, args...)
202 }
David Benjamin634b0e32017-02-04 11:14:57 -0500203 var outBuf bytes.Buffer
204 cmd.Stdout = &outBuf
205 cmd.Stderr = &outBuf
David Benjamin0b635c52015-05-15 19:08:49 -0400206 if mallocNumToFail >= 0 {
207 cmd.Env = os.Environ()
208 cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
209 if *mallocTestDebug {
210 cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
211 }
212 cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
213 }
David Benjamin491b9212015-02-11 14:18:45 -0500214
215 if err := cmd.Start(); err != nil {
216 return false, err
217 }
218 if err := cmd.Wait(); err != nil {
David Benjamin0b635c52015-05-15 19:08:49 -0400219 if exitError, ok := err.(*exec.ExitError); ok {
220 if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
221 return false, errMoreMallocs
222 }
223 }
David Benjamin634b0e32017-02-04 11:14:57 -0500224 fmt.Print(string(outBuf.Bytes()))
David Benjamin491b9212015-02-11 14:18:45 -0500225 return false, err
226 }
227
228 // Account for Windows line-endings.
David Benjamin634b0e32017-02-04 11:14:57 -0500229 stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
David Benjamin491b9212015-02-11 14:18:45 -0500230
231 if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
232 (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
233 return true, nil
234 }
David Benjamin96628432017-01-19 19:05:47 -0500235
236 // Also accept a googletest-style pass line. This is left here in
237 // transition until the tests are all converted and this script made
238 // unnecessary.
239 if bytes.Contains(stdout, []byte("\n[ PASSED ]")) {
240 return true, nil
241 }
242
David Benjamin634b0e32017-02-04 11:14:57 -0500243 fmt.Print(string(outBuf.Bytes()))
David Benjamin491b9212015-02-11 14:18:45 -0500244 return false, nil
245}
246
David Benjamin0b635c52015-05-15 19:08:49 -0400247func runTest(test test) (bool, error) {
248 if *mallocTest < 0 {
249 return runTestOnce(test, -1)
250 }
251
252 for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
253 if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
254 if err != nil {
255 err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
256 }
257 return passed, err
258 }
259 }
260}
261
Martin Kreichgauer23aff6b2017-04-11 08:53:08 -0700262// shortTestName returns the short name of a test. Except for evp_test and
263// cipher_test, it assumes that any argument which ends in .txt is a path to a
264// data file and not relevant to the test's uniqueness.
David Benjamin5f237bc2015-02-11 17:14:15 -0500265func shortTestName(test test) string {
266 var args []string
Adam Langleye212f272017-02-03 08:52:21 -0800267 for _, arg := range test.args {
David Benjamin3d14a152017-06-07 14:02:03 -0400268 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=") {
David Benjamin5f237bc2015-02-11 17:14:15 -0500269 args = append(args, arg)
270 }
271 }
Adam Langleye212f272017-02-03 08:52:21 -0800272 return strings.Join(args, " ") + test.cpuMsg()
David Benjamin5f237bc2015-02-11 17:14:15 -0500273}
274
Adam Langley117da412015-06-10 17:32:25 -0700275// setWorkingDirectory walks up directories as needed until the current working
276// directory is the top of a BoringSSL checkout.
277func setWorkingDirectory() {
278 for i := 0; i < 64; i++ {
David Benjamin95aaf4a2015-09-03 12:09:36 -0400279 if _, err := os.Stat("BUILDING.md"); err == nil {
Adam Langley117da412015-06-10 17:32:25 -0700280 return
281 }
282 os.Chdir("..")
283 }
284
David Benjamin95aaf4a2015-09-03 12:09:36 -0400285 panic("Couldn't find BUILDING.md in a parent directory!")
Adam Langley117da412015-06-10 17:32:25 -0700286}
287
288func parseTestConfig(filename string) ([]test, error) {
289 in, err := os.Open(filename)
290 if err != nil {
291 return nil, err
292 }
293 defer in.Close()
294
295 decoder := json.NewDecoder(in)
Adam Langleye212f272017-02-03 08:52:21 -0800296 var testArgs [][]string
297 if err := decoder.Decode(&testArgs); err != nil {
Adam Langley117da412015-06-10 17:32:25 -0700298 return nil, err
299 }
Adam Langleye212f272017-02-03 08:52:21 -0800300
301 var result []test
302 for _, args := range testArgs {
303 result = append(result, test{args: args})
304 }
Adam Langley117da412015-06-10 17:32:25 -0700305 return result, nil
306}
307
Steven Valdez32223942016-03-02 11:53:07 -0500308func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
309 defer done.Done()
310 for test := range tests {
311 passed, err := runTest(test)
312 results <- result{test, passed, err}
313 }
314}
315
Adam Langleye212f272017-02-03 08:52:21 -0800316func (t test) cpuMsg() string {
317 if len(t.cpu) == 0 {
318 return ""
319 }
320
321 return fmt.Sprintf(" (for CPU %q)", t.cpu)
322}
323
David Benjamin3d14a152017-06-07 14:02:03 -0400324func (t test) getGTestShards() ([]test, error) {
325 if *numWorkers == 1 || len(t.args) != 1 {
326 return []test{t}, nil
327 }
328
329 // Only shard the three GTest-based tests.
330 if t.args[0] != "crypto/crypto_test" && t.args[0] != "ssl/ssl_test" && t.args[0] != "decrepit/decrepit_test" {
331 return []test{t}, nil
332 }
333
334 prog := path.Join(*buildDir, t.args[0])
335 cmd := exec.Command(prog, "--gtest_list_tests")
336 var stdout bytes.Buffer
337 cmd.Stdout = &stdout
338 if err := cmd.Start(); err != nil {
339 return nil, err
340 }
341 if err := cmd.Wait(); err != nil {
342 return nil, err
343 }
344
345 var group string
346 var tests []string
347 scanner := bufio.NewScanner(&stdout)
348 for scanner.Scan() {
349 line := scanner.Text()
350
351 // Remove the parameter comment and trailing space.
352 if idx := strings.Index(line, "#"); idx >= 0 {
353 line = line[:idx]
354 }
355 line = strings.TrimSpace(line)
356 if len(line) == 0 {
357 continue
358 }
359
360 if line[len(line)-1] == '.' {
361 group = line
362 continue
363 }
364
365 if len(group) == 0 {
366 return nil, fmt.Errorf("found test case %q without group", line)
367 }
368 tests = append(tests, group+line)
369 }
370
371 const testsPerShard = 20
372 if len(tests) <= testsPerShard {
373 return []test{t}, nil
374 }
375
376 // Slow tests which process large test vector files tend to be grouped
377 // together, so shuffle the order.
378 shuffled := make([]string, len(tests))
379 perm := rand.Perm(len(tests))
380 for i, j := range perm {
381 shuffled[i] = tests[j]
382 }
383
384 var shards []test
385 for i := 0; i < len(shuffled); i += testsPerShard {
386 n := len(shuffled) - i
387 if n > testsPerShard {
388 n = testsPerShard
389 }
390 shard := t
391 shard.args = []string{shard.args[0], "--gtest_filter=" + strings.Join(shuffled[i:i+n], ":")}
392 shards = append(shards, shard)
393 }
394
395 return shards, nil
396}
397
David Benjamin491b9212015-02-11 14:18:45 -0500398func main() {
399 flag.Parse()
Adam Langley117da412015-06-10 17:32:25 -0700400 setWorkingDirectory()
401
Steven Valdez32223942016-03-02 11:53:07 -0500402 testCases, err := parseTestConfig("util/all_tests.json")
Adam Langley117da412015-06-10 17:32:25 -0700403 if err != nil {
404 fmt.Printf("Failed to parse input: %s\n", err)
405 os.Exit(1)
406 }
David Benjamin491b9212015-02-11 14:18:45 -0500407
Steven Valdez32223942016-03-02 11:53:07 -0500408 var wg sync.WaitGroup
409 tests := make(chan test, *numWorkers)
David Benjamin8b9e7802016-03-02 18:23:21 -0500410 results := make(chan result, *numWorkers)
Steven Valdez32223942016-03-02 11:53:07 -0500411
412 for i := 0; i < *numWorkers; i++ {
David Benjamin8b9e7802016-03-02 18:23:21 -0500413 wg.Add(1)
Steven Valdez32223942016-03-02 11:53:07 -0500414 go worker(tests, results, &wg)
415 }
416
Steven Valdez32223942016-03-02 11:53:07 -0500417 go func() {
David Benjamin8b9e7802016-03-02 18:23:21 -0500418 for _, test := range testCases {
Adam Langleye212f272017-02-03 08:52:21 -0800419 if *useSDE {
David Benjamin3d14a152017-06-07 14:02:03 -0400420 // SDE generates plenty of tasks and gets slower
421 // with additional sharding.
Adam Langleye212f272017-02-03 08:52:21 -0800422 for _, cpu := range sdeCPUs {
423 testForCPU := test
424 testForCPU.cpu = cpu
425 tests <- testForCPU
426 }
427 } else {
David Benjamin3d14a152017-06-07 14:02:03 -0400428 shards, err := test.getGTestShards()
429 if err != nil {
430 fmt.Printf("Error listing tests: %s\n", err)
431 os.Exit(1)
432 }
433 for _, shard := range shards {
434 tests <- shard
435 }
Adam Langleye212f272017-02-03 08:52:21 -0800436 }
David Benjamin8b9e7802016-03-02 18:23:21 -0500437 }
438 close(tests)
439
Steven Valdez32223942016-03-02 11:53:07 -0500440 wg.Wait()
441 close(results)
442 }()
443
David Benjamin5f237bc2015-02-11 17:14:15 -0500444 testOutput := newTestOutput()
David Benjamin491b9212015-02-11 14:18:45 -0500445 var failed []test
Steven Valdez32223942016-03-02 11:53:07 -0500446 for testResult := range results {
447 test := testResult.Test
Adam Langleye212f272017-02-03 08:52:21 -0800448 args := test.args
David Benjamin5f237bc2015-02-11 17:14:15 -0500449
Adam Langleye212f272017-02-03 08:52:21 -0800450 fmt.Printf("%s%s\n", strings.Join(args, " "), test.cpuMsg())
David Benjamin5f237bc2015-02-11 17:14:15 -0500451 name := shortTestName(test)
Steven Valdez32223942016-03-02 11:53:07 -0500452 if testResult.Error != nil {
Adam Langleye212f272017-02-03 08:52:21 -0800453 fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
David Benjamin491b9212015-02-11 14:18:45 -0500454 failed = append(failed, test)
David Benjamin5f237bc2015-02-11 17:14:15 -0500455 testOutput.addResult(name, "CRASHED")
Steven Valdez32223942016-03-02 11:53:07 -0500456 } else if !testResult.Passed {
Adam Langleye212f272017-02-03 08:52:21 -0800457 fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
David Benjamin491b9212015-02-11 14:18:45 -0500458 failed = append(failed, test)
David Benjamin5f237bc2015-02-11 17:14:15 -0500459 testOutput.addResult(name, "FAIL")
460 } else {
461 testOutput.addResult(name, "PASS")
David Benjamin491b9212015-02-11 14:18:45 -0500462 }
463 }
464
David Benjamin5f237bc2015-02-11 17:14:15 -0500465 if *jsonOutput != "" {
466 if err := testOutput.writeTo(*jsonOutput); err != nil {
467 fmt.Fprintf(os.Stderr, "Error: %s\n", err)
468 }
469 }
David Benjamin2ab7a862015-04-04 17:02:18 -0400470
471 if len(failed) > 0 {
David Benjamin8b9e7802016-03-02 18:23:21 -0500472 fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
David Benjamin2ab7a862015-04-04 17:02:18 -0400473 for _, test := range failed {
Adam Langleye5adaef2017-05-02 14:48:47 -0700474 fmt.Printf("\t%s%s\n", strings.Join(test.args, " "), test.cpuMsg())
David Benjamin2ab7a862015-04-04 17:02:18 -0400475 }
476 os.Exit(1)
477 }
478
479 fmt.Printf("\nAll tests passed!\n")
David Benjamin491b9212015-02-11 14:18:45 -0500480}