blob: fbee0ff7e91d3eeab0b2e6b3770b16d57c38488e [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 (
18 "bytes"
19 "encoding/json"
20 "flag"
21 "fmt"
22 "os"
23 "os/exec"
24 "path"
Robert Sloan572a4e22017-04-17 10:52:19 -070025 "runtime"
Adam Langleyf4e42722015-06-04 17:45:09 -070026 "strconv"
Adam Langleye9ada862015-05-11 17:20:37 -070027 "strings"
David Benjamin4969cc92016-04-22 15:02:23 -040028 "sync"
Adam Langleyf4e42722015-06-04 17:45:09 -070029 "syscall"
Adam Langleye9ada862015-05-11 17:20:37 -070030 "time"
31)
32
33// TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.
34
35var (
Adam Langleyf4e42722015-06-04 17:45:09 -070036 useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind")
David Benjamin4969cc92016-04-22 15:02:23 -040037 useCallgrind = flag.Bool("callgrind", false, "If true, run code under valgrind to generate callgrind traces.")
Adam Langleyf4e42722015-06-04 17:45:09 -070038 useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
Robert Sloan4d1ac502017-02-06 08:36:14 -080039 useSDE = flag.Bool("sde", false, "If true, run BoringSSL code under Intel's SDE for each supported chip")
Adam Langleyf4e42722015-06-04 17:45:09 -070040 buildDir = flag.String("build-dir", "build", "The build directory to run the tests from.")
Robert Sloan572a4e22017-04-17 10:52:19 -070041 numWorkers = flag.Int("num-workers", runtime.NumCPU(), "Runs the given number of workers when testing.")
Adam Langleyf4e42722015-06-04 17:45:09 -070042 jsonOutput = flag.String("json-output", "", "The file to output JSON results to.")
43 mallocTest = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
44 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 -070045)
46
Robert Sloan4d1ac502017-02-06 08:36:14 -080047type test struct {
48 args []string
49 // cpu, if not empty, contains an Intel CPU code to simulate. Run
50 // `sde64 -help` to get a list of these codes.
51 cpu string
52}
Adam Langleye9ada862015-05-11 17:20:37 -070053
David Benjamin4969cc92016-04-22 15:02:23 -040054type result struct {
55 Test test
56 Passed bool
57 Error error
58}
59
Adam Langleye9ada862015-05-11 17:20:37 -070060// testOutput is a representation of Chromium's JSON test result format. See
61// https://www.chromium.org/developers/the-json-test-results-format
62type testOutput struct {
63 Version int `json:"version"`
64 Interrupted bool `json:"interrupted"`
65 PathDelimiter string `json:"path_delimiter"`
66 SecondsSinceEpoch float64 `json:"seconds_since_epoch"`
67 NumFailuresByType map[string]int `json:"num_failures_by_type"`
68 Tests map[string]testResult `json:"tests"`
69}
70
71type testResult struct {
72 Actual string `json:"actual"`
73 Expected string `json:"expected"`
74 IsUnexpected bool `json:"is_unexpected"`
75}
76
Robert Sloan4d1ac502017-02-06 08:36:14 -080077// sdeCPUs contains a list of CPU code that we run all tests under when *useSDE
78// is true.
79var sdeCPUs = []string{
80 "p4p", // Pentium4 Prescott
81 "mrm", // Merom
82 "pnr", // Penryn
83 "nhm", // Nehalem
84 "wsm", // Westmere
85 "snb", // Sandy Bridge
86 "ivb", // Ivy Bridge
87 "hsw", // Haswell
88 "bdw", // Broadwell
89 "skx", // Skylake Server
90 "skl", // Skylake Client
91 "cnl", // Cannonlake
92 "knl", // Knights Landing
93 "slt", // Saltwell
94 "slm", // Silvermont
95 "glm", // Goldmont
96}
97
Adam Langleye9ada862015-05-11 17:20:37 -070098func newTestOutput() *testOutput {
99 return &testOutput{
100 Version: 3,
101 PathDelimiter: ".",
102 SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
103 NumFailuresByType: make(map[string]int),
104 Tests: make(map[string]testResult),
105 }
106}
107
108func (t *testOutput) addResult(name, result string) {
109 if _, found := t.Tests[name]; found {
110 panic(name)
111 }
112 t.Tests[name] = testResult{
113 Actual: result,
114 Expected: "PASS",
115 IsUnexpected: result != "PASS",
116 }
117 t.NumFailuresByType[result]++
118}
119
120func (t *testOutput) writeTo(name string) error {
121 file, err := os.Create(name)
122 if err != nil {
123 return err
124 }
125 defer file.Close()
126 out, err := json.MarshalIndent(t, "", " ")
127 if err != nil {
128 return err
129 }
130 _, err = file.Write(out)
131 return err
132}
133
134func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
David Benjamin7c0d06c2016-08-11 13:26:41 -0400135 valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
Adam Langleye9ada862015-05-11 17:20:37 -0700136 if dbAttach {
137 valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
138 }
139 valgrindArgs = append(valgrindArgs, path)
140 valgrindArgs = append(valgrindArgs, args...)
141
142 return exec.Command("valgrind", valgrindArgs...)
143}
144
David Benjamin4969cc92016-04-22 15:02:23 -0400145func callgrindOf(path string, args ...string) *exec.Cmd {
146 valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
147 valgrindArgs = append(valgrindArgs, path)
148 valgrindArgs = append(valgrindArgs, args...)
149
150 return exec.Command("valgrind", valgrindArgs...)
151}
152
Adam Langleyf4e42722015-06-04 17:45:09 -0700153func gdbOf(path string, args ...string) *exec.Cmd {
154 xtermArgs := []string{"-e", "gdb", "--args"}
155 xtermArgs = append(xtermArgs, path)
156 xtermArgs = append(xtermArgs, args...)
157
158 return exec.Command("xterm", xtermArgs...)
159}
160
Robert Sloan4d1ac502017-02-06 08:36:14 -0800161func sdeOf(cpu, path string, args ...string) *exec.Cmd {
162 sdeArgs := []string{"-" + cpu, "--", path}
163 sdeArgs = append(sdeArgs, args...)
164 return exec.Command("sde", sdeArgs...)
165}
166
Adam Langleyf4e42722015-06-04 17:45:09 -0700167type moreMallocsError struct{}
168
169func (moreMallocsError) Error() string {
170 return "child process did not exhaust all allocation calls"
171}
172
173var errMoreMallocs = moreMallocsError{}
174
175func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800176 prog := path.Join(*buildDir, test.args[0])
177 args := test.args[1:]
Adam Langleye9ada862015-05-11 17:20:37 -0700178 var cmd *exec.Cmd
179 if *useValgrind {
180 cmd = valgrindOf(false, prog, args...)
David Benjamin4969cc92016-04-22 15:02:23 -0400181 } else if *useCallgrind {
182 cmd = callgrindOf(prog, args...)
Adam Langleyf4e42722015-06-04 17:45:09 -0700183 } else if *useGDB {
184 cmd = gdbOf(prog, args...)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800185 } else if *useSDE {
186 cmd = sdeOf(test.cpu, prog, args...)
Adam Langleye9ada862015-05-11 17:20:37 -0700187 } else {
188 cmd = exec.Command(prog, args...)
189 }
Robert Sloan5d625782017-02-13 09:55:39 -0800190 var outBuf bytes.Buffer
191 cmd.Stdout = &outBuf
192 cmd.Stderr = &outBuf
Adam Langleyf4e42722015-06-04 17:45:09 -0700193 if mallocNumToFail >= 0 {
194 cmd.Env = os.Environ()
195 cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
196 if *mallocTestDebug {
197 cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
198 }
199 cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
200 }
Adam Langleye9ada862015-05-11 17:20:37 -0700201
202 if err := cmd.Start(); err != nil {
203 return false, err
204 }
205 if err := cmd.Wait(); err != nil {
Adam Langleyf4e42722015-06-04 17:45:09 -0700206 if exitError, ok := err.(*exec.ExitError); ok {
207 if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
208 return false, errMoreMallocs
209 }
210 }
Robert Sloan5d625782017-02-13 09:55:39 -0800211 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700212 return false, err
213 }
214
215 // Account for Windows line-endings.
Robert Sloan5d625782017-02-13 09:55:39 -0800216 stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
Adam Langleye9ada862015-05-11 17:20:37 -0700217
218 if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
219 (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
220 return true, nil
221 }
David Benjaminf31229b2017-01-25 14:08:15 -0500222
223 // Also accept a googletest-style pass line. This is left here in
224 // transition until the tests are all converted and this script made
225 // unnecessary.
226 if bytes.Contains(stdout, []byte("\n[ PASSED ]")) {
227 return true, nil
228 }
229
Robert Sloan5d625782017-02-13 09:55:39 -0800230 fmt.Print(string(outBuf.Bytes()))
Adam Langleye9ada862015-05-11 17:20:37 -0700231 return false, nil
232}
233
Adam Langleyf4e42722015-06-04 17:45:09 -0700234func runTest(test test) (bool, error) {
235 if *mallocTest < 0 {
236 return runTestOnce(test, -1)
237 }
238
239 for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
240 if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
241 if err != nil {
242 err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
243 }
244 return passed, err
245 }
246 }
247}
248
Robert Sloan572a4e22017-04-17 10:52:19 -0700249// shortTestName returns the short name of a test. Except for evp_test and
250// cipher_test, it assumes that any argument which ends in .txt is a path to a
251// data file and not relevant to the test's uniqueness.
Adam Langleye9ada862015-05-11 17:20:37 -0700252func shortTestName(test test) string {
253 var args []string
Robert Sloan4d1ac502017-02-06 08:36:14 -0800254 for _, arg := range test.args {
Robert Sloan572a4e22017-04-17 10:52:19 -0700255 if test.args[0] == "crypto/evp/evp_test" || test.args[0] == "crypto/cipher/cipher_test" || !strings.HasSuffix(arg, ".txt") {
Adam Langleye9ada862015-05-11 17:20:37 -0700256 args = append(args, arg)
257 }
258 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800259 return strings.Join(args, " ") + test.cpuMsg()
Adam Langleye9ada862015-05-11 17:20:37 -0700260}
261
Kenny Rootb8494592015-09-25 02:29:14 +0000262// setWorkingDirectory walks up directories as needed until the current working
263// directory is the top of a BoringSSL checkout.
264func setWorkingDirectory() {
265 for i := 0; i < 64; i++ {
266 if _, err := os.Stat("BUILDING.md"); err == nil {
267 return
268 }
269 os.Chdir("..")
270 }
271
272 panic("Couldn't find BUILDING.md in a parent directory!")
273}
274
275func parseTestConfig(filename string) ([]test, error) {
276 in, err := os.Open(filename)
277 if err != nil {
278 return nil, err
279 }
280 defer in.Close()
281
282 decoder := json.NewDecoder(in)
Robert Sloan4d1ac502017-02-06 08:36:14 -0800283 var testArgs [][]string
284 if err := decoder.Decode(&testArgs); err != nil {
Kenny Rootb8494592015-09-25 02:29:14 +0000285 return nil, err
286 }
Robert Sloan4d1ac502017-02-06 08:36:14 -0800287
288 var result []test
289 for _, args := range testArgs {
290 result = append(result, test{args: args})
291 }
Kenny Rootb8494592015-09-25 02:29:14 +0000292 return result, nil
293}
294
David Benjamin4969cc92016-04-22 15:02:23 -0400295func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
296 defer done.Done()
297 for test := range tests {
298 passed, err := runTest(test)
299 results <- result{test, passed, err}
300 }
301}
302
Robert Sloan4d1ac502017-02-06 08:36:14 -0800303func (t test) cpuMsg() string {
304 if len(t.cpu) == 0 {
305 return ""
306 }
307
308 return fmt.Sprintf(" (for CPU %q)", t.cpu)
309}
310
Adam Langleye9ada862015-05-11 17:20:37 -0700311func main() {
312 flag.Parse()
Kenny Rootb8494592015-09-25 02:29:14 +0000313 setWorkingDirectory()
314
David Benjamin4969cc92016-04-22 15:02:23 -0400315 testCases, err := parseTestConfig("util/all_tests.json")
Kenny Rootb8494592015-09-25 02:29:14 +0000316 if err != nil {
317 fmt.Printf("Failed to parse input: %s\n", err)
318 os.Exit(1)
319 }
Adam Langleye9ada862015-05-11 17:20:37 -0700320
David Benjamin4969cc92016-04-22 15:02:23 -0400321 var wg sync.WaitGroup
322 tests := make(chan test, *numWorkers)
323 results := make(chan result, *numWorkers)
324
325 for i := 0; i < *numWorkers; i++ {
326 wg.Add(1)
327 go worker(tests, results, &wg)
328 }
329
330 go func() {
331 for _, test := range testCases {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800332 if *useSDE {
333 for _, cpu := range sdeCPUs {
334 testForCPU := test
335 testForCPU.cpu = cpu
336 tests <- testForCPU
337 }
338 } else {
339 tests <- test
340 }
David Benjamin4969cc92016-04-22 15:02:23 -0400341 }
342 close(tests)
343
344 wg.Wait()
345 close(results)
346 }()
347
Adam Langleye9ada862015-05-11 17:20:37 -0700348 testOutput := newTestOutput()
349 var failed []test
David Benjamin4969cc92016-04-22 15:02:23 -0400350 for testResult := range results {
351 test := testResult.Test
Robert Sloan4d1ac502017-02-06 08:36:14 -0800352 args := test.args
Adam Langleye9ada862015-05-11 17:20:37 -0700353
Robert Sloan4d1ac502017-02-06 08:36:14 -0800354 fmt.Printf("%s%s\n", strings.Join(args, " "), test.cpuMsg())
Adam Langleye9ada862015-05-11 17:20:37 -0700355 name := shortTestName(test)
David Benjamin4969cc92016-04-22 15:02:23 -0400356 if testResult.Error != nil {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800357 fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
Adam Langleye9ada862015-05-11 17:20:37 -0700358 failed = append(failed, test)
359 testOutput.addResult(name, "CRASHED")
David Benjamin4969cc92016-04-22 15:02:23 -0400360 } else if !testResult.Passed {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800361 fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
Adam Langleye9ada862015-05-11 17:20:37 -0700362 failed = append(failed, test)
363 testOutput.addResult(name, "FAIL")
364 } else {
365 testOutput.addResult(name, "PASS")
366 }
367 }
368
369 if *jsonOutput != "" {
370 if err := testOutput.writeTo(*jsonOutput); err != nil {
371 fmt.Fprintf(os.Stderr, "Error: %s\n", err)
372 }
373 }
374
375 if len(failed) > 0 {
David Benjamin4969cc92016-04-22 15:02:23 -0400376 fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
Adam Langleye9ada862015-05-11 17:20:37 -0700377 for _, test := range failed {
Robert Sloan4d1ac502017-02-06 08:36:14 -0800378 fmt.Printf("\t%s%s\n", strings.Join(test.args, ""), test.cpuMsg())
Adam Langleye9ada862015-05-11 17:20:37 -0700379 }
380 os.Exit(1)
381 }
382
383 fmt.Printf("\nAll tests passed!\n")
384}