blob: 38899bb1785bb59ae099c8a30bde31e96897ed4b [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 (
18 "bytes"
David Benjamin5f237bc2015-02-11 17:14:15 -050019 "encoding/json"
David Benjamin491b9212015-02-11 14:18:45 -050020 "flag"
21 "fmt"
22 "os"
23 "os/exec"
24 "path"
David Benjamin0b635c52015-05-15 19:08:49 -040025 "strconv"
David Benjamin491b9212015-02-11 14:18:45 -050026 "strings"
Steven Valdez32223942016-03-02 11:53:07 -050027 "sync"
David Benjamin0b635c52015-05-15 19:08:49 -040028 "syscall"
David Benjamin5f237bc2015-02-11 17:14:15 -050029 "time"
David Benjamin491b9212015-02-11 14:18:45 -050030)
31
32// TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.
33
34var (
David Benjamin0b635c52015-05-15 19:08:49 -040035 useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind")
36 useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
37 buildDir = flag.String("build-dir", "build", "The build directory to run the tests from.")
Steven Valdez32223942016-03-02 11:53:07 -050038 numWorkers = flag.Int("num-workers", 1, "Runs the given number of workers when testing.")
David Benjamin0b635c52015-05-15 19:08:49 -040039 jsonOutput = flag.String("json-output", "", "The file to output JSON results to.")
40 mallocTest = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
41 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 -050042)
43
44type test []string
45
Steven Valdez32223942016-03-02 11:53:07 -050046type result struct {
47 Test test
48 Passed bool
49 Error error
50}
51
David Benjamin5f237bc2015-02-11 17:14:15 -050052// testOutput is a representation of Chromium's JSON test result format. See
53// https://www.chromium.org/developers/the-json-test-results-format
54type testOutput struct {
55 Version int `json:"version"`
56 Interrupted bool `json:"interrupted"`
57 PathDelimiter string `json:"path_delimiter"`
58 SecondsSinceEpoch float64 `json:"seconds_since_epoch"`
59 NumFailuresByType map[string]int `json:"num_failures_by_type"`
60 Tests map[string]testResult `json:"tests"`
61}
62
63type testResult struct {
David Benjamin7ead6052015-04-04 03:57:26 -040064 Actual string `json:"actual"`
65 Expected string `json:"expected"`
66 IsUnexpected bool `json:"is_unexpected"`
David Benjamin5f237bc2015-02-11 17:14:15 -050067}
68
69func newTestOutput() *testOutput {
70 return &testOutput{
71 Version: 3,
72 PathDelimiter: ".",
73 SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
74 NumFailuresByType: make(map[string]int),
75 Tests: make(map[string]testResult),
76 }
77}
78
79func (t *testOutput) addResult(name, result string) {
80 if _, found := t.Tests[name]; found {
81 panic(name)
82 }
David Benjamin7ead6052015-04-04 03:57:26 -040083 t.Tests[name] = testResult{
84 Actual: result,
85 Expected: "PASS",
86 IsUnexpected: result != "PASS",
87 }
David Benjamin5f237bc2015-02-11 17:14:15 -050088 t.NumFailuresByType[result]++
89}
90
91func (t *testOutput) writeTo(name string) error {
92 file, err := os.Create(name)
93 if err != nil {
94 return err
95 }
96 defer file.Close()
97 out, err := json.MarshalIndent(t, "", " ")
98 if err != nil {
99 return err
100 }
101 _, err = file.Write(out)
102 return err
103}
104
David Benjamin491b9212015-02-11 14:18:45 -0500105func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
106 valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full"}
107 if dbAttach {
108 valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
109 }
110 valgrindArgs = append(valgrindArgs, path)
111 valgrindArgs = append(valgrindArgs, args...)
112
113 return exec.Command("valgrind", valgrindArgs...)
114}
115
David Benjamin0b635c52015-05-15 19:08:49 -0400116func gdbOf(path string, args ...string) *exec.Cmd {
117 xtermArgs := []string{"-e", "gdb", "--args"}
118 xtermArgs = append(xtermArgs, path)
119 xtermArgs = append(xtermArgs, args...)
120
121 return exec.Command("xterm", xtermArgs...)
122}
123
124type moreMallocsError struct{}
125
126func (moreMallocsError) Error() string {
127 return "child process did not exhaust all allocation calls"
128}
129
130var errMoreMallocs = moreMallocsError{}
131
132func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
David Benjamin491b9212015-02-11 14:18:45 -0500133 prog := path.Join(*buildDir, test[0])
134 args := test[1:]
135 var cmd *exec.Cmd
136 if *useValgrind {
137 cmd = valgrindOf(false, prog, args...)
David Benjamin0b635c52015-05-15 19:08:49 -0400138 } else if *useGDB {
139 cmd = gdbOf(prog, args...)
David Benjamin491b9212015-02-11 14:18:45 -0500140 } else {
141 cmd = exec.Command(prog, args...)
142 }
143 var stdoutBuf bytes.Buffer
David Benjamin0b635c52015-05-15 19:08:49 -0400144 var stderrBuf bytes.Buffer
David Benjamin491b9212015-02-11 14:18:45 -0500145 cmd.Stdout = &stdoutBuf
David Benjamin0b635c52015-05-15 19:08:49 -0400146 cmd.Stderr = &stderrBuf
147 if mallocNumToFail >= 0 {
148 cmd.Env = os.Environ()
149 cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
150 if *mallocTestDebug {
151 cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
152 }
153 cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
154 }
David Benjamin491b9212015-02-11 14:18:45 -0500155
156 if err := cmd.Start(); err != nil {
157 return false, err
158 }
159 if err := cmd.Wait(); err != nil {
David Benjamin0b635c52015-05-15 19:08:49 -0400160 if exitError, ok := err.(*exec.ExitError); ok {
161 if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
162 return false, errMoreMallocs
163 }
164 }
165 fmt.Print(string(stderrBuf.Bytes()))
David Benjamin491b9212015-02-11 14:18:45 -0500166 return false, err
167 }
David Benjamin0b635c52015-05-15 19:08:49 -0400168 fmt.Print(string(stderrBuf.Bytes()))
David Benjamin491b9212015-02-11 14:18:45 -0500169
170 // Account for Windows line-endings.
171 stdout := bytes.Replace(stdoutBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
172
173 if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
174 (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
175 return true, nil
176 }
177 return false, nil
178}
179
David Benjamin0b635c52015-05-15 19:08:49 -0400180func runTest(test test) (bool, error) {
181 if *mallocTest < 0 {
182 return runTestOnce(test, -1)
183 }
184
185 for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
186 if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
187 if err != nil {
188 err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
189 }
190 return passed, err
191 }
192 }
193}
194
David Benjamin5c694e32015-05-11 15:58:08 -0400195// shortTestName returns the short name of a test. Except for evp_test, it
196// assumes that any argument which ends in .txt is a path to a data file and not
197// relevant to the test's uniqueness.
David Benjamin5f237bc2015-02-11 17:14:15 -0500198func shortTestName(test test) string {
199 var args []string
200 for _, arg := range test {
David Benjamin5c694e32015-05-11 15:58:08 -0400201 if test[0] == "crypto/evp/evp_test" || !strings.HasSuffix(arg, ".txt") {
David Benjamin5f237bc2015-02-11 17:14:15 -0500202 args = append(args, arg)
203 }
204 }
205 return strings.Join(args, " ")
206}
207
Adam Langley117da412015-06-10 17:32:25 -0700208// setWorkingDirectory walks up directories as needed until the current working
209// directory is the top of a BoringSSL checkout.
210func setWorkingDirectory() {
211 for i := 0; i < 64; i++ {
David Benjamin95aaf4a2015-09-03 12:09:36 -0400212 if _, err := os.Stat("BUILDING.md"); err == nil {
Adam Langley117da412015-06-10 17:32:25 -0700213 return
214 }
215 os.Chdir("..")
216 }
217
David Benjamin95aaf4a2015-09-03 12:09:36 -0400218 panic("Couldn't find BUILDING.md in a parent directory!")
Adam Langley117da412015-06-10 17:32:25 -0700219}
220
221func parseTestConfig(filename string) ([]test, error) {
222 in, err := os.Open(filename)
223 if err != nil {
224 return nil, err
225 }
226 defer in.Close()
227
228 decoder := json.NewDecoder(in)
229 var result []test
230 if err := decoder.Decode(&result); err != nil {
231 return nil, err
232 }
233 return result, nil
234}
235
Steven Valdez32223942016-03-02 11:53:07 -0500236func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
237 defer done.Done()
238 for test := range tests {
239 passed, err := runTest(test)
240 results <- result{test, passed, err}
241 }
242}
243
David Benjamin491b9212015-02-11 14:18:45 -0500244func main() {
245 flag.Parse()
Adam Langley117da412015-06-10 17:32:25 -0700246 setWorkingDirectory()
247
Steven Valdez32223942016-03-02 11:53:07 -0500248 testCases, err := parseTestConfig("util/all_tests.json")
Adam Langley117da412015-06-10 17:32:25 -0700249 if err != nil {
250 fmt.Printf("Failed to parse input: %s\n", err)
251 os.Exit(1)
252 }
David Benjamin491b9212015-02-11 14:18:45 -0500253
Steven Valdez32223942016-03-02 11:53:07 -0500254 var wg sync.WaitGroup
255 tests := make(chan test, *numWorkers)
David Benjamin8b9e7802016-03-02 18:23:21 -0500256 results := make(chan result, *numWorkers)
Steven Valdez32223942016-03-02 11:53:07 -0500257
258 for i := 0; i < *numWorkers; i++ {
David Benjamin8b9e7802016-03-02 18:23:21 -0500259 wg.Add(1)
Steven Valdez32223942016-03-02 11:53:07 -0500260 go worker(tests, results, &wg)
261 }
262
Steven Valdez32223942016-03-02 11:53:07 -0500263 go func() {
David Benjamin8b9e7802016-03-02 18:23:21 -0500264 for _, test := range testCases {
265 tests <- test
266 }
267 close(tests)
268
Steven Valdez32223942016-03-02 11:53:07 -0500269 wg.Wait()
270 close(results)
271 }()
272
David Benjamin5f237bc2015-02-11 17:14:15 -0500273 testOutput := newTestOutput()
David Benjamin491b9212015-02-11 14:18:45 -0500274 var failed []test
Steven Valdez32223942016-03-02 11:53:07 -0500275 for testResult := range results {
276 test := testResult.Test
David Benjamin5f237bc2015-02-11 17:14:15 -0500277
Steven Valdez32223942016-03-02 11:53:07 -0500278 fmt.Printf("%s\n", strings.Join([]string(test), " "))
David Benjamin5f237bc2015-02-11 17:14:15 -0500279 name := shortTestName(test)
Steven Valdez32223942016-03-02 11:53:07 -0500280 if testResult.Error != nil {
281 fmt.Printf("%s failed to complete: %s\n", test[0], testResult.Error)
David Benjamin491b9212015-02-11 14:18:45 -0500282 failed = append(failed, test)
David Benjamin5f237bc2015-02-11 17:14:15 -0500283 testOutput.addResult(name, "CRASHED")
Steven Valdez32223942016-03-02 11:53:07 -0500284 } else if !testResult.Passed {
David Benjamin491b9212015-02-11 14:18:45 -0500285 fmt.Printf("%s failed to print PASS on the last line.\n", test[0])
286 failed = append(failed, test)
David Benjamin5f237bc2015-02-11 17:14:15 -0500287 testOutput.addResult(name, "FAIL")
288 } else {
289 testOutput.addResult(name, "PASS")
David Benjamin491b9212015-02-11 14:18:45 -0500290 }
291 }
292
David Benjamin5f237bc2015-02-11 17:14:15 -0500293 if *jsonOutput != "" {
294 if err := testOutput.writeTo(*jsonOutput); err != nil {
295 fmt.Fprintf(os.Stderr, "Error: %s\n", err)
296 }
297 }
David Benjamin2ab7a862015-04-04 17:02:18 -0400298
299 if len(failed) > 0 {
David Benjamin8b9e7802016-03-02 18:23:21 -0500300 fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
David Benjamin2ab7a862015-04-04 17:02:18 -0400301 for _, test := range failed {
302 fmt.Printf("\t%s\n", strings.Join([]string(test), " "))
303 }
304 os.Exit(1)
305 }
306
307 fmt.Printf("\nAll tests passed!\n")
David Benjamin491b9212015-02-11 14:18:45 -0500308}