blob: d5794fcf4a2859594d2bff073798fd016f5dad89 [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 {
David Benjaminced6e762017-09-28 15:17:05 -040051 args []string
52 shard, numShards int
Adam Langleye212f272017-02-03 08:52:21 -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}
David Benjamin491b9212015-02-11 14:18:45 -050057
Steven Valdez32223942016-03-02 11:53:07 -050058type result struct {
59 Test test
60 Passed bool
61 Error error
62}
63
David Benjamin5f237bc2015-02-11 17:14:15 -050064// 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 {
David Benjamin7ead6052015-04-04 03:57:26 -040076 Actual string `json:"actual"`
77 Expected string `json:"expected"`
78 IsUnexpected bool `json:"is_unexpected"`
David Benjamin5f237bc2015-02-11 17:14:15 -050079}
80
Adam Langleye212f272017-02-03 08:52:21 -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
David Benjamind4e37952017-07-25 16:59:58 -0400100 "knm", // Knights Mill
Adam Langleye212f272017-02-03 08:52:21 -0800101}
102
David Benjamin5f237bc2015-02-11 17:14:15 -0500103func 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 }
David Benjamin7ead6052015-04-04 03:57:26 -0400117 t.Tests[name] = testResult{
118 Actual: result,
119 Expected: "PASS",
120 IsUnexpected: result != "PASS",
121 }
David Benjamin5f237bc2015-02-11 17:14:15 -0500122 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
David Benjamin491b9212015-02-11 14:18:45 -0500139func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
David Benjamind2ba8892016-09-20 19:41:04 -0400140 valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
David Benjamin491b9212015-02-11 14:18:45 -0500141 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
Steven Valdezab14a4a2016-02-29 16:58:26 -0500150func 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
David Benjamin0b635c52015-05-15 19:08:49 -0400158func 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
Adam Langleye212f272017-02-03 08:52:21 -0800166func sdeOf(cpu, path string, args ...string) *exec.Cmd {
David Benjaminc5304e42017-07-17 16:15:16 -0400167 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)
Adam Langleye212f272017-02-03 08:52:21 -0800177 sdeArgs = append(sdeArgs, args...)
David Benjamin799676c2017-05-10 16:56:02 -0400178 return exec.Command(*sdePath, sdeArgs...)
Adam Langleye212f272017-02-03 08:52:21 -0800179}
180
David Benjamin0b635c52015-05-15 19:08:49 -0400181type 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) {
Adam Langleye212f272017-02-03 08:52:21 -0800190 prog := path.Join(*buildDir, test.args[0])
191 args := test.args[1:]
David Benjamin491b9212015-02-11 14:18:45 -0500192 var cmd *exec.Cmd
193 if *useValgrind {
194 cmd = valgrindOf(false, prog, args...)
Steven Valdezab14a4a2016-02-29 16:58:26 -0500195 } else if *useCallgrind {
196 cmd = callgrindOf(prog, args...)
David Benjamin0b635c52015-05-15 19:08:49 -0400197 } else if *useGDB {
198 cmd = gdbOf(prog, args...)
Adam Langleye212f272017-02-03 08:52:21 -0800199 } else if *useSDE {
200 cmd = sdeOf(test.cpu, prog, args...)
David Benjamin491b9212015-02-11 14:18:45 -0500201 } else {
202 cmd = exec.Command(prog, args...)
203 }
David Benjamin634b0e32017-02-04 11:14:57 -0500204 var outBuf bytes.Buffer
205 cmd.Stdout = &outBuf
206 cmd.Stderr = &outBuf
David Benjamin0b635c52015-05-15 19:08:49 -0400207 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 }
David Benjamin491b9212015-02-11 14:18:45 -0500215
216 if err := cmd.Start(); err != nil {
217 return false, err
218 }
219 if err := cmd.Wait(); err != nil {
David Benjamin0b635c52015-05-15 19:08:49 -0400220 if exitError, ok := err.(*exec.ExitError); ok {
221 if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
222 return false, errMoreMallocs
223 }
224 }
David Benjamin634b0e32017-02-04 11:14:57 -0500225 fmt.Print(string(outBuf.Bytes()))
David Benjamin491b9212015-02-11 14:18:45 -0500226 return false, err
227 }
228
229 // Account for Windows line-endings.
David Benjamin634b0e32017-02-04 11:14:57 -0500230 stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
David Benjamin491b9212015-02-11 14:18:45 -0500231
232 if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
233 (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
234 return true, nil
235 }
David Benjamin96628432017-01-19 19:05:47 -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
David Benjamin634b0e32017-02-04 11:14:57 -0500244 fmt.Print(string(outBuf.Bytes()))
David Benjamin491b9212015-02-11 14:18:45 -0500245 return false, nil
246}
247
David Benjamin0b635c52015-05-15 19:08:49 -0400248func 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
Adam Langley117da412015-06-10 17:32:25 -0700263// 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++ {
David Benjamin95aaf4a2015-09-03 12:09:36 -0400267 if _, err := os.Stat("BUILDING.md"); err == nil {
Adam Langley117da412015-06-10 17:32:25 -0700268 return
269 }
270 os.Chdir("..")
271 }
272
David Benjamin95aaf4a2015-09-03 12:09:36 -0400273 panic("Couldn't find BUILDING.md in a parent directory!")
Adam Langley117da412015-06-10 17:32:25 -0700274}
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)
Adam Langleye212f272017-02-03 08:52:21 -0800284 var testArgs [][]string
285 if err := decoder.Decode(&testArgs); err != nil {
Adam Langley117da412015-06-10 17:32:25 -0700286 return nil, err
287 }
Adam Langleye212f272017-02-03 08:52:21 -0800288
289 var result []test
290 for _, args := range testArgs {
291 result = append(result, test{args: args})
292 }
Adam Langley117da412015-06-10 17:32:25 -0700293 return result, nil
294}
295
Steven Valdez32223942016-03-02 11:53:07 -0500296func 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
David Benjaminced6e762017-09-28 15:17:05 -0400304func (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
Adam Langleye212f272017-02-03 08:52:21 -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
David Benjamin3d14a152017-06-07 14:02:03 -0400328func (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], ":")}
David Benjaminced6e762017-09-28 15:17:05 -0400396 shard.shard = len(shards)
David Benjamin3d14a152017-06-07 14:02:03 -0400397 shards = append(shards, shard)
398 }
399
David Benjaminced6e762017-09-28 15:17:05 -0400400 for i := range shards {
401 shards[i].numShards = len(shards)
402 }
403
David Benjamin3d14a152017-06-07 14:02:03 -0400404 return shards, nil
405}
406
David Benjamin491b9212015-02-11 14:18:45 -0500407func main() {
408 flag.Parse()
Adam Langley117da412015-06-10 17:32:25 -0700409 setWorkingDirectory()
410
Steven Valdez32223942016-03-02 11:53:07 -0500411 testCases, err := parseTestConfig("util/all_tests.json")
Adam Langley117da412015-06-10 17:32:25 -0700412 if err != nil {
413 fmt.Printf("Failed to parse input: %s\n", err)
414 os.Exit(1)
415 }
David Benjamin491b9212015-02-11 14:18:45 -0500416
Steven Valdez32223942016-03-02 11:53:07 -0500417 var wg sync.WaitGroup
418 tests := make(chan test, *numWorkers)
David Benjamin8b9e7802016-03-02 18:23:21 -0500419 results := make(chan result, *numWorkers)
Steven Valdez32223942016-03-02 11:53:07 -0500420
421 for i := 0; i < *numWorkers; i++ {
David Benjamin8b9e7802016-03-02 18:23:21 -0500422 wg.Add(1)
Steven Valdez32223942016-03-02 11:53:07 -0500423 go worker(tests, results, &wg)
424 }
425
Steven Valdez32223942016-03-02 11:53:07 -0500426 go func() {
David Benjamin8b9e7802016-03-02 18:23:21 -0500427 for _, test := range testCases {
Adam Langleye212f272017-02-03 08:52:21 -0800428 if *useSDE {
David Benjamin3d14a152017-06-07 14:02:03 -0400429 // SDE generates plenty of tasks and gets slower
430 // with additional sharding.
Adam Langleye212f272017-02-03 08:52:21 -0800431 for _, cpu := range sdeCPUs {
432 testForCPU := test
433 testForCPU.cpu = cpu
434 tests <- testForCPU
435 }
436 } else {
David Benjamin3d14a152017-06-07 14:02:03 -0400437 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 }
Adam Langleye212f272017-02-03 08:52:21 -0800445 }
David Benjamin8b9e7802016-03-02 18:23:21 -0500446 }
447 close(tests)
448
Steven Valdez32223942016-03-02 11:53:07 -0500449 wg.Wait()
450 close(results)
451 }()
452
David Benjamin5f237bc2015-02-11 17:14:15 -0500453 testOutput := newTestOutput()
David Benjamin491b9212015-02-11 14:18:45 -0500454 var failed []test
Steven Valdez32223942016-03-02 11:53:07 -0500455 for testResult := range results {
456 test := testResult.Test
Adam Langleye212f272017-02-03 08:52:21 -0800457 args := test.args
David Benjamin5f237bc2015-02-11 17:14:15 -0500458
Steven Valdez32223942016-03-02 11:53:07 -0500459 if testResult.Error != nil {
David Benjaminced6e762017-09-28 15:17:05 -0400460 fmt.Printf("%s\n", test.longName())
Adam Langleye212f272017-02-03 08:52:21 -0800461 fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
David Benjamin491b9212015-02-11 14:18:45 -0500462 failed = append(failed, test)
David Benjaminced6e762017-09-28 15:17:05 -0400463 testOutput.addResult(test.longName(), "CRASHED")
Steven Valdez32223942016-03-02 11:53:07 -0500464 } else if !testResult.Passed {
David Benjaminced6e762017-09-28 15:17:05 -0400465 fmt.Printf("%s\n", test.longName())
Adam Langleye212f272017-02-03 08:52:21 -0800466 fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
David Benjamin491b9212015-02-11 14:18:45 -0500467 failed = append(failed, test)
David Benjaminced6e762017-09-28 15:17:05 -0400468 testOutput.addResult(test.longName(), "FAIL")
David Benjamin5f237bc2015-02-11 17:14:15 -0500469 } else {
David Benjaminced6e762017-09-28 15:17:05 -0400470 fmt.Printf("%s\n", test.shortName())
471 testOutput.addResult(test.longName(), "PASS")
David Benjamin491b9212015-02-11 14:18:45 -0500472 }
473 }
474
David Benjamin5f237bc2015-02-11 17:14:15 -0500475 if *jsonOutput != "" {
476 if err := testOutput.writeTo(*jsonOutput); err != nil {
477 fmt.Fprintf(os.Stderr, "Error: %s\n", err)
478 }
479 }
David Benjamin2ab7a862015-04-04 17:02:18 -0400480
481 if len(failed) > 0 {
David Benjamin8b9e7802016-03-02 18:23:21 -0500482 fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
David Benjamin2ab7a862015-04-04 17:02:18 -0400483 for _, test := range failed {
Adam Langleye5adaef2017-05-02 14:48:47 -0700484 fmt.Printf("\t%s%s\n", strings.Join(test.args, " "), test.cpuMsg())
David Benjamin2ab7a862015-04-04 17:02:18 -0400485 }
486 os.Exit(1)
487 }
488
489 fmt.Printf("\nAll tests passed!\n")
David Benjamin491b9212015-02-11 14:18:45 -0500490}