blob: ef23080e8d7ae0a83335dfa9c694f843985da5a4 [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
Robert Sloanfe7cd212017-08-07 09:03:39 -070099 "knm", // Knights Mill
Robert Sloan4d1ac502017-02-06 08:36:14 -0800100}
101
Adam Langleye9ada862015-05-11 17:20:37 -0700102func 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 }
116 t.Tests[name] = testResult{
117 Actual: result,
118 Expected: "PASS",
119 IsUnexpected: result != "PASS",
120 }
121 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
138func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
David Benjamin7c0d06c2016-08-11 13:26:41 -0400139 valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
Adam Langleye9ada862015-05-11 17:20:37 -0700140 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
David Benjamin4969cc92016-04-22 15:02:23 -0400149func 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
Adam Langleyf4e42722015-06-04 17:45:09 -0700157func 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
Robert Sloan4d1ac502017-02-06 08:36:14 -0800165func sdeOf(cpu, path string, args ...string) *exec.Cmd {
Robert Sloanb6d070c2017-07-24 08:40:01 -0700166 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)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800176 sdeArgs = append(sdeArgs, args...)
Robert Sloan8ff03552017-06-14 12:40:58 -0700177 return exec.Command(*sdePath, sdeArgs...)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800178}
179
Adam Langleyf4e42722015-06-04 17:45:09 -0700180type 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) {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800189 prog := path.Join(*buildDir, test.args[0])
190 args := test.args[1:]
Adam Langleye9ada862015-05-11 17:20:37 -0700191 var cmd *exec.Cmd
192 if *useValgrind {
193 cmd = valgrindOf(false, prog, args...)
David Benjamin4969cc92016-04-22 15:02:23 -0400194 } else if *useCallgrind {
195 cmd = callgrindOf(prog, args...)
Adam Langleyf4e42722015-06-04 17:45:09 -0700196 } else if *useGDB {
197 cmd = gdbOf(prog, args...)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800198 } else if *useSDE {
199 cmd = sdeOf(test.cpu, prog, args...)
Adam Langleye9ada862015-05-11 17:20:37 -0700200 } else {
201 cmd = exec.Command(prog, args...)
202 }
Robert Sloan5d625782017-02-13 09:55:39 -0800203 var outBuf bytes.Buffer
204 cmd.Stdout = &outBuf
205 cmd.Stderr = &outBuf
Adam Langleyf4e42722015-06-04 17:45:09 -0700206 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 }
Adam Langleye9ada862015-05-11 17:20:37 -0700214
215 if err := cmd.Start(); err != nil {
216 return false, err
217 }
218 if err := cmd.Wait(); err != nil {
Adam Langleyf4e42722015-06-04 17:45:09 -0700219 if exitError, ok := err.(*exec.ExitError); ok {
220 if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
221 return false, errMoreMallocs
222 }
223 }
Robert Sloan5d625782017-02-13 09:55:39 -0800224 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700225 return false, err
226 }
227
228 // Account for Windows line-endings.
Robert Sloan5d625782017-02-13 09:55:39 -0800229 stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
Adam Langleye9ada862015-05-11 17:20:37 -0700230
231 if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
232 (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
233 return true, nil
234 }
David Benjaminf31229b2017-01-25 14:08:15 -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
Robert Sloan5d625782017-02-13 09:55:39 -0800243 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700244 return false, nil
245}
246
Adam Langleyf4e42722015-06-04 17:45:09 -0700247func 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
Robert Sloan572a4e22017-04-17 10:52:19 -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.
Adam Langleye9ada862015-05-11 17:20:37 -0700265func shortTestName(test test) string {
266 var args []string
Robert Sloan4d1ac502017-02-06 08:36:14 -0800267 for _, arg := range test.args {
Robert Sloan8ff03552017-06-14 12:40:58 -0700268 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 -0700269 args = append(args, arg)
270 }
271 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800272 return strings.Join(args, " ") + test.cpuMsg()
Adam Langleye9ada862015-05-11 17:20:37 -0700273}
274
Kenny Rootb8494592015-09-25 02:29:14 +0000275// 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++ {
279 if _, err := os.Stat("BUILDING.md"); err == nil {
280 return
281 }
282 os.Chdir("..")
283 }
284
285 panic("Couldn't find BUILDING.md in a parent directory!")
286}
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)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800296 var testArgs [][]string
297 if err := decoder.Decode(&testArgs); err != nil {
Kenny Rootb8494592015-09-25 02:29:14 +0000298 return nil, err
299 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800300
301 var result []test
302 for _, args := range testArgs {
303 result = append(result, test{args: args})
304 }
Kenny Rootb8494592015-09-25 02:29:14 +0000305 return result, nil
306}
307
David Benjamin4969cc92016-04-22 15:02:23 -0400308func 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
Robert Sloan4d1ac502017-02-06 08:36:14 -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
Robert Sloan8ff03552017-06-14 12:40:58 -0700324func (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
Adam Langleye9ada862015-05-11 17:20:37 -0700398func main() {
399 flag.Parse()
Kenny Rootb8494592015-09-25 02:29:14 +0000400 setWorkingDirectory()
401
David Benjamin4969cc92016-04-22 15:02:23 -0400402 testCases, err := parseTestConfig("util/all_tests.json")
Kenny Rootb8494592015-09-25 02:29:14 +0000403 if err != nil {
404 fmt.Printf("Failed to parse input: %s\n", err)
405 os.Exit(1)
406 }
Adam Langleye9ada862015-05-11 17:20:37 -0700407
David Benjamin4969cc92016-04-22 15:02:23 -0400408 var wg sync.WaitGroup
409 tests := make(chan test, *numWorkers)
410 results := make(chan result, *numWorkers)
411
412 for i := 0; i < *numWorkers; i++ {
413 wg.Add(1)
414 go worker(tests, results, &wg)
415 }
416
417 go func() {
418 for _, test := range testCases {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800419 if *useSDE {
Robert Sloan8ff03552017-06-14 12:40:58 -0700420 // SDE generates plenty of tasks and gets slower
421 // with additional sharding.
Robert Sloan4d1ac502017-02-06 08:36:14 -0800422 for _, cpu := range sdeCPUs {
423 testForCPU := test
424 testForCPU.cpu = cpu
425 tests <- testForCPU
426 }
427 } else {
Robert Sloan8ff03552017-06-14 12:40:58 -0700428 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 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800436 }
David Benjamin4969cc92016-04-22 15:02:23 -0400437 }
438 close(tests)
439
440 wg.Wait()
441 close(results)
442 }()
443
Adam Langleye9ada862015-05-11 17:20:37 -0700444 testOutput := newTestOutput()
445 var failed []test
David Benjamin4969cc92016-04-22 15:02:23 -0400446 for testResult := range results {
447 test := testResult.Test
Robert Sloan4d1ac502017-02-06 08:36:14 -0800448 args := test.args
Adam Langleye9ada862015-05-11 17:20:37 -0700449
Robert Sloan4d1ac502017-02-06 08:36:14 -0800450 fmt.Printf("%s%s\n", strings.Join(args, " "), test.cpuMsg())
Adam Langleye9ada862015-05-11 17:20:37 -0700451 name := shortTestName(test)
David Benjamin4969cc92016-04-22 15:02:23 -0400452 if testResult.Error != nil {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800453 fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
Adam Langleye9ada862015-05-11 17:20:37 -0700454 failed = append(failed, test)
455 testOutput.addResult(name, "CRASHED")
David Benjamin4969cc92016-04-22 15:02:23 -0400456 } else if !testResult.Passed {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800457 fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
Adam Langleye9ada862015-05-11 17:20:37 -0700458 failed = append(failed, test)
459 testOutput.addResult(name, "FAIL")
460 } else {
461 testOutput.addResult(name, "PASS")
462 }
463 }
464
465 if *jsonOutput != "" {
466 if err := testOutput.writeTo(*jsonOutput); err != nil {
467 fmt.Fprintf(os.Stderr, "Error: %s\n", err)
468 }
469 }
470
471 if len(failed) > 0 {
David Benjamin4969cc92016-04-22 15:02:23 -0400472 fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
Adam Langleye9ada862015-05-11 17:20:37 -0700473 for _, test := range failed {
Robert Sloan8ff03552017-06-14 12:40:58 -0700474 fmt.Printf("\t%s%s\n", strings.Join(test.args, " "), test.cpuMsg())
Adam Langleye9ada862015-05-11 17:20:37 -0700475 }
476 os.Exit(1)
477 }
478
479 fmt.Printf("\nAll tests passed!\n")
480}