blob: d5794fcf4a2859594d2bff073798fd016f5dad89 [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 {
Robert Sloan4562e9d2017-10-02 10:26:51 -070051 args []string
52 shard, numShards int
Robert Sloan4d1ac502017-02-06 08:36:14 -080053 // cpu, if not empty, contains an Intel CPU code to simulate. Run
54 // `sde64 -help` to get a list of these codes.
55 cpu string
56}
Adam Langleye9ada862015-05-11 17:20:37 -070057
David Benjamin4969cc92016-04-22 15:02:23 -040058type result struct {
59 Test test
60 Passed bool
61 Error error
62}
63
Adam Langleye9ada862015-05-11 17:20:37 -070064// testOutput is a representation of Chromium's JSON test result format. See
65// https://www.chromium.org/developers/the-json-test-results-format
66type testOutput struct {
67 Version int `json:"version"`
68 Interrupted bool `json:"interrupted"`
69 PathDelimiter string `json:"path_delimiter"`
70 SecondsSinceEpoch float64 `json:"seconds_since_epoch"`
71 NumFailuresByType map[string]int `json:"num_failures_by_type"`
72 Tests map[string]testResult `json:"tests"`
73}
74
75type testResult struct {
76 Actual string `json:"actual"`
77 Expected string `json:"expected"`
78 IsUnexpected bool `json:"is_unexpected"`
79}
80
Robert Sloan4d1ac502017-02-06 08:36:14 -080081// sdeCPUs contains a list of CPU code that we run all tests under when *useSDE
82// is true.
83var sdeCPUs = []string{
84 "p4p", // Pentium4 Prescott
85 "mrm", // Merom
86 "pnr", // Penryn
87 "nhm", // Nehalem
88 "wsm", // Westmere
89 "snb", // Sandy Bridge
90 "ivb", // Ivy Bridge
91 "hsw", // Haswell
92 "bdw", // Broadwell
93 "skx", // Skylake Server
94 "skl", // Skylake Client
95 "cnl", // Cannonlake
96 "knl", // Knights Landing
97 "slt", // Saltwell
98 "slm", // Silvermont
99 "glm", // Goldmont
Robert Sloanfe7cd212017-08-07 09:03:39 -0700100 "knm", // Knights Mill
Robert Sloan4d1ac502017-02-06 08:36:14 -0800101}
102
Adam Langleye9ada862015-05-11 17:20:37 -0700103func newTestOutput() *testOutput {
104 return &testOutput{
105 Version: 3,
106 PathDelimiter: ".",
107 SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
108 NumFailuresByType: make(map[string]int),
109 Tests: make(map[string]testResult),
110 }
111}
112
113func (t *testOutput) addResult(name, result string) {
114 if _, found := t.Tests[name]; found {
115 panic(name)
116 }
117 t.Tests[name] = testResult{
118 Actual: result,
119 Expected: "PASS",
120 IsUnexpected: result != "PASS",
121 }
122 t.NumFailuresByType[result]++
123}
124
125func (t *testOutput) writeTo(name string) error {
126 file, err := os.Create(name)
127 if err != nil {
128 return err
129 }
130 defer file.Close()
131 out, err := json.MarshalIndent(t, "", " ")
132 if err != nil {
133 return err
134 }
135 _, err = file.Write(out)
136 return err
137}
138
139func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
David Benjamin7c0d06c2016-08-11 13:26:41 -0400140 valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
Adam Langleye9ada862015-05-11 17:20:37 -0700141 if dbAttach {
142 valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
143 }
144 valgrindArgs = append(valgrindArgs, path)
145 valgrindArgs = append(valgrindArgs, args...)
146
147 return exec.Command("valgrind", valgrindArgs...)
148}
149
David Benjamin4969cc92016-04-22 15:02:23 -0400150func callgrindOf(path string, args ...string) *exec.Cmd {
151 valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
152 valgrindArgs = append(valgrindArgs, path)
153 valgrindArgs = append(valgrindArgs, args...)
154
155 return exec.Command("valgrind", valgrindArgs...)
156}
157
Adam Langleyf4e42722015-06-04 17:45:09 -0700158func gdbOf(path string, args ...string) *exec.Cmd {
159 xtermArgs := []string{"-e", "gdb", "--args"}
160 xtermArgs = append(xtermArgs, path)
161 xtermArgs = append(xtermArgs, args...)
162
163 return exec.Command("xterm", xtermArgs...)
164}
165
Robert Sloan4d1ac502017-02-06 08:36:14 -0800166func sdeOf(cpu, path string, args ...string) *exec.Cmd {
Robert Sloanb6d070c2017-07-24 08:40:01 -0700167 sdeArgs := []string{"-" + cpu}
168 // The kernel's vdso code for gettimeofday sometimes uses the RDTSCP
169 // instruction. Although SDE has a -chip_check_vsyscall flag that
170 // excludes such code by default, it does not seem to work. Instead,
171 // pass the -chip_check_exe_only flag which retains test coverage when
172 // statically linked and excludes the vdso.
173 if cpu == "p4p" || cpu == "pnr" || cpu == "mrm" || cpu == "slt" {
174 sdeArgs = append(sdeArgs, "-chip_check_exe_only")
175 }
176 sdeArgs = append(sdeArgs, "--", path)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800177 sdeArgs = append(sdeArgs, args...)
Robert Sloan8ff03552017-06-14 12:40:58 -0700178 return exec.Command(*sdePath, sdeArgs...)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800179}
180
Adam Langleyf4e42722015-06-04 17:45:09 -0700181type moreMallocsError struct{}
182
183func (moreMallocsError) Error() string {
184 return "child process did not exhaust all allocation calls"
185}
186
187var errMoreMallocs = moreMallocsError{}
188
189func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800190 prog := path.Join(*buildDir, test.args[0])
191 args := test.args[1:]
Adam Langleye9ada862015-05-11 17:20:37 -0700192 var cmd *exec.Cmd
193 if *useValgrind {
194 cmd = valgrindOf(false, prog, args...)
David Benjamin4969cc92016-04-22 15:02:23 -0400195 } else if *useCallgrind {
196 cmd = callgrindOf(prog, args...)
Adam Langleyf4e42722015-06-04 17:45:09 -0700197 } else if *useGDB {
198 cmd = gdbOf(prog, args...)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800199 } else if *useSDE {
200 cmd = sdeOf(test.cpu, prog, args...)
Adam Langleye9ada862015-05-11 17:20:37 -0700201 } else {
202 cmd = exec.Command(prog, args...)
203 }
Robert Sloan5d625782017-02-13 09:55:39 -0800204 var outBuf bytes.Buffer
205 cmd.Stdout = &outBuf
206 cmd.Stderr = &outBuf
Adam Langleyf4e42722015-06-04 17:45:09 -0700207 if mallocNumToFail >= 0 {
208 cmd.Env = os.Environ()
209 cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
210 if *mallocTestDebug {
211 cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
212 }
213 cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
214 }
Adam Langleye9ada862015-05-11 17:20:37 -0700215
216 if err := cmd.Start(); err != nil {
217 return false, err
218 }
219 if err := cmd.Wait(); err != nil {
Adam Langleyf4e42722015-06-04 17:45:09 -0700220 if exitError, ok := err.(*exec.ExitError); ok {
221 if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
222 return false, errMoreMallocs
223 }
224 }
Robert Sloan5d625782017-02-13 09:55:39 -0800225 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700226 return false, err
227 }
228
229 // Account for Windows line-endings.
Robert Sloan5d625782017-02-13 09:55:39 -0800230 stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
Adam Langleye9ada862015-05-11 17:20:37 -0700231
232 if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
233 (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
234 return true, nil
235 }
David Benjaminf31229b2017-01-25 14:08:15 -0500236
237 // Also accept a googletest-style pass line. This is left here in
238 // transition until the tests are all converted and this script made
239 // unnecessary.
240 if bytes.Contains(stdout, []byte("\n[ PASSED ]")) {
241 return true, nil
242 }
243
Robert Sloan5d625782017-02-13 09:55:39 -0800244 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700245 return false, nil
246}
247
Adam Langleyf4e42722015-06-04 17:45:09 -0700248func runTest(test test) (bool, error) {
249 if *mallocTest < 0 {
250 return runTestOnce(test, -1)
251 }
252
253 for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
254 if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
255 if err != nil {
256 err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
257 }
258 return passed, err
259 }
260 }
261}
262
Kenny Rootb8494592015-09-25 02:29:14 +0000263// setWorkingDirectory walks up directories as needed until the current working
264// directory is the top of a BoringSSL checkout.
265func setWorkingDirectory() {
266 for i := 0; i < 64; i++ {
267 if _, err := os.Stat("BUILDING.md"); err == nil {
268 return
269 }
270 os.Chdir("..")
271 }
272
273 panic("Couldn't find BUILDING.md in a parent directory!")
274}
275
276func parseTestConfig(filename string) ([]test, error) {
277 in, err := os.Open(filename)
278 if err != nil {
279 return nil, err
280 }
281 defer in.Close()
282
283 decoder := json.NewDecoder(in)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800284 var testArgs [][]string
285 if err := decoder.Decode(&testArgs); err != nil {
Kenny Rootb8494592015-09-25 02:29:14 +0000286 return nil, err
287 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800288
289 var result []test
290 for _, args := range testArgs {
291 result = append(result, test{args: args})
292 }
Kenny Rootb8494592015-09-25 02:29:14 +0000293 return result, nil
294}
295
David Benjamin4969cc92016-04-22 15:02:23 -0400296func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
297 defer done.Done()
298 for test := range tests {
299 passed, err := runTest(test)
300 results <- result{test, passed, err}
301 }
302}
303
Robert Sloan4562e9d2017-10-02 10:26:51 -0700304func (t test) shortName() string {
305 return t.args[0] + t.shardMsg() + t.cpuMsg()
306}
307
308func (t test) longName() string {
309 return strings.Join(t.args, " ") + t.cpuMsg()
310}
311
312func (t test) shardMsg() string {
313 if t.numShards == 0 {
314 return ""
315 }
316
317 return fmt.Sprintf(" [shard %d/%d]", t.shard+1, t.numShards)
318}
319
Robert Sloan4d1ac502017-02-06 08:36:14 -0800320func (t test) cpuMsg() string {
321 if len(t.cpu) == 0 {
322 return ""
323 }
324
325 return fmt.Sprintf(" (for CPU %q)", t.cpu)
326}
327
Robert Sloan8ff03552017-06-14 12:40:58 -0700328func (t test) getGTestShards() ([]test, error) {
329 if *numWorkers == 1 || len(t.args) != 1 {
330 return []test{t}, nil
331 }
332
333 // Only shard the three GTest-based tests.
334 if t.args[0] != "crypto/crypto_test" && t.args[0] != "ssl/ssl_test" && t.args[0] != "decrepit/decrepit_test" {
335 return []test{t}, nil
336 }
337
338 prog := path.Join(*buildDir, t.args[0])
339 cmd := exec.Command(prog, "--gtest_list_tests")
340 var stdout bytes.Buffer
341 cmd.Stdout = &stdout
342 if err := cmd.Start(); err != nil {
343 return nil, err
344 }
345 if err := cmd.Wait(); err != nil {
346 return nil, err
347 }
348
349 var group string
350 var tests []string
351 scanner := bufio.NewScanner(&stdout)
352 for scanner.Scan() {
353 line := scanner.Text()
354
355 // Remove the parameter comment and trailing space.
356 if idx := strings.Index(line, "#"); idx >= 0 {
357 line = line[:idx]
358 }
359 line = strings.TrimSpace(line)
360 if len(line) == 0 {
361 continue
362 }
363
364 if line[len(line)-1] == '.' {
365 group = line
366 continue
367 }
368
369 if len(group) == 0 {
370 return nil, fmt.Errorf("found test case %q without group", line)
371 }
372 tests = append(tests, group+line)
373 }
374
375 const testsPerShard = 20
376 if len(tests) <= testsPerShard {
377 return []test{t}, nil
378 }
379
380 // Slow tests which process large test vector files tend to be grouped
381 // together, so shuffle the order.
382 shuffled := make([]string, len(tests))
383 perm := rand.Perm(len(tests))
384 for i, j := range perm {
385 shuffled[i] = tests[j]
386 }
387
388 var shards []test
389 for i := 0; i < len(shuffled); i += testsPerShard {
390 n := len(shuffled) - i
391 if n > testsPerShard {
392 n = testsPerShard
393 }
394 shard := t
395 shard.args = []string{shard.args[0], "--gtest_filter=" + strings.Join(shuffled[i:i+n], ":")}
Robert Sloan4562e9d2017-10-02 10:26:51 -0700396 shard.shard = len(shards)
Robert Sloan8ff03552017-06-14 12:40:58 -0700397 shards = append(shards, shard)
398 }
399
Robert Sloan4562e9d2017-10-02 10:26:51 -0700400 for i := range shards {
401 shards[i].numShards = len(shards)
402 }
403
Robert Sloan8ff03552017-06-14 12:40:58 -0700404 return shards, nil
405}
406
Adam Langleye9ada862015-05-11 17:20:37 -0700407func main() {
408 flag.Parse()
Kenny Rootb8494592015-09-25 02:29:14 +0000409 setWorkingDirectory()
410
David Benjamin4969cc92016-04-22 15:02:23 -0400411 testCases, err := parseTestConfig("util/all_tests.json")
Kenny Rootb8494592015-09-25 02:29:14 +0000412 if err != nil {
413 fmt.Printf("Failed to parse input: %s\n", err)
414 os.Exit(1)
415 }
Adam Langleye9ada862015-05-11 17:20:37 -0700416
David Benjamin4969cc92016-04-22 15:02:23 -0400417 var wg sync.WaitGroup
418 tests := make(chan test, *numWorkers)
419 results := make(chan result, *numWorkers)
420
421 for i := 0; i < *numWorkers; i++ {
422 wg.Add(1)
423 go worker(tests, results, &wg)
424 }
425
426 go func() {
427 for _, test := range testCases {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800428 if *useSDE {
Robert Sloan8ff03552017-06-14 12:40:58 -0700429 // SDE generates plenty of tasks and gets slower
430 // with additional sharding.
Robert Sloan4d1ac502017-02-06 08:36:14 -0800431 for _, cpu := range sdeCPUs {
432 testForCPU := test
433 testForCPU.cpu = cpu
434 tests <- testForCPU
435 }
436 } else {
Robert Sloan8ff03552017-06-14 12:40:58 -0700437 shards, err := test.getGTestShards()
438 if err != nil {
439 fmt.Printf("Error listing tests: %s\n", err)
440 os.Exit(1)
441 }
442 for _, shard := range shards {
443 tests <- shard
444 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800445 }
David Benjamin4969cc92016-04-22 15:02:23 -0400446 }
447 close(tests)
448
449 wg.Wait()
450 close(results)
451 }()
452
Adam Langleye9ada862015-05-11 17:20:37 -0700453 testOutput := newTestOutput()
454 var failed []test
David Benjamin4969cc92016-04-22 15:02:23 -0400455 for testResult := range results {
456 test := testResult.Test
Robert Sloan4d1ac502017-02-06 08:36:14 -0800457 args := test.args
Adam Langleye9ada862015-05-11 17:20:37 -0700458
David Benjamin4969cc92016-04-22 15:02:23 -0400459 if testResult.Error != nil {
Robert Sloan4562e9d2017-10-02 10:26:51 -0700460 fmt.Printf("%s\n", test.longName())
Robert Sloan4d1ac502017-02-06 08:36:14 -0800461 fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
Adam Langleye9ada862015-05-11 17:20:37 -0700462 failed = append(failed, test)
Robert Sloan4562e9d2017-10-02 10:26:51 -0700463 testOutput.addResult(test.longName(), "CRASHED")
David Benjamin4969cc92016-04-22 15:02:23 -0400464 } else if !testResult.Passed {
Robert Sloan4562e9d2017-10-02 10:26:51 -0700465 fmt.Printf("%s\n", test.longName())
Robert Sloan4d1ac502017-02-06 08:36:14 -0800466 fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
Adam Langleye9ada862015-05-11 17:20:37 -0700467 failed = append(failed, test)
Robert Sloan4562e9d2017-10-02 10:26:51 -0700468 testOutput.addResult(test.longName(), "FAIL")
Adam Langleye9ada862015-05-11 17:20:37 -0700469 } else {
Robert Sloan4562e9d2017-10-02 10:26:51 -0700470 fmt.Printf("%s\n", test.shortName())
471 testOutput.addResult(test.longName(), "PASS")
Adam Langleye9ada862015-05-11 17:20:37 -0700472 }
473 }
474
475 if *jsonOutput != "" {
476 if err := testOutput.writeTo(*jsonOutput); err != nil {
477 fmt.Fprintf(os.Stderr, "Error: %s\n", err)
478 }
479 }
480
481 if len(failed) > 0 {
David Benjamin4969cc92016-04-22 15:02:23 -0400482 fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
Adam Langleye9ada862015-05-11 17:20:37 -0700483 for _, test := range failed {
Robert Sloan8ff03552017-06-14 12:40:58 -0700484 fmt.Printf("\t%s%s\n", strings.Join(test.args, " "), test.cpuMsg())
Adam Langleye9ada862015-05-11 17:20:37 -0700485 }
486 os.Exit(1)
487 }
488
489 fmt.Printf("\nAll tests passed!\n")
490}