You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

320 line
9.0 KiB

  1. /* 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. package main
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "flag"
  19. "fmt"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "syscall"
  27. "time"
  28. )
  29. // TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.
  30. var (
  31. useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind")
  32. useCallgrind = flag.Bool("callgrind", false, "If true, run code under valgrind to generate callgrind traces.")
  33. useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
  34. buildDir = flag.String("build-dir", "build", "The build directory to run the tests from.")
  35. numWorkers = flag.Int("num-workers", 1, "Runs the given number of workers when testing.")
  36. jsonOutput = flag.String("json-output", "", "The file to output JSON results to.")
  37. mallocTest = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
  38. 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.")
  39. )
  40. type test []string
  41. type result struct {
  42. Test test
  43. Passed bool
  44. Error error
  45. }
  46. // testOutput is a representation of Chromium's JSON test result format. See
  47. // https://www.chromium.org/developers/the-json-test-results-format
  48. type testOutput struct {
  49. Version int `json:"version"`
  50. Interrupted bool `json:"interrupted"`
  51. PathDelimiter string `json:"path_delimiter"`
  52. SecondsSinceEpoch float64 `json:"seconds_since_epoch"`
  53. NumFailuresByType map[string]int `json:"num_failures_by_type"`
  54. Tests map[string]testResult `json:"tests"`
  55. }
  56. type testResult struct {
  57. Actual string `json:"actual"`
  58. Expected string `json:"expected"`
  59. IsUnexpected bool `json:"is_unexpected"`
  60. }
  61. func newTestOutput() *testOutput {
  62. return &testOutput{
  63. Version: 3,
  64. PathDelimiter: ".",
  65. SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
  66. NumFailuresByType: make(map[string]int),
  67. Tests: make(map[string]testResult),
  68. }
  69. }
  70. func (t *testOutput) addResult(name, result string) {
  71. if _, found := t.Tests[name]; found {
  72. panic(name)
  73. }
  74. t.Tests[name] = testResult{
  75. Actual: result,
  76. Expected: "PASS",
  77. IsUnexpected: result != "PASS",
  78. }
  79. t.NumFailuresByType[result]++
  80. }
  81. func (t *testOutput) writeTo(name string) error {
  82. file, err := os.Create(name)
  83. if err != nil {
  84. return err
  85. }
  86. defer file.Close()
  87. out, err := json.MarshalIndent(t, "", " ")
  88. if err != nil {
  89. return err
  90. }
  91. _, err = file.Write(out)
  92. return err
  93. }
  94. func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
  95. valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full"}
  96. if dbAttach {
  97. valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
  98. }
  99. valgrindArgs = append(valgrindArgs, path)
  100. valgrindArgs = append(valgrindArgs, args...)
  101. return exec.Command("valgrind", valgrindArgs...)
  102. }
  103. func callgrindOf(path string, args ...string) *exec.Cmd {
  104. valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
  105. valgrindArgs = append(valgrindArgs, path)
  106. valgrindArgs = append(valgrindArgs, args...)
  107. return exec.Command("valgrind", valgrindArgs...)
  108. }
  109. func gdbOf(path string, args ...string) *exec.Cmd {
  110. xtermArgs := []string{"-e", "gdb", "--args"}
  111. xtermArgs = append(xtermArgs, path)
  112. xtermArgs = append(xtermArgs, args...)
  113. return exec.Command("xterm", xtermArgs...)
  114. }
  115. type moreMallocsError struct{}
  116. func (moreMallocsError) Error() string {
  117. return "child process did not exhaust all allocation calls"
  118. }
  119. var errMoreMallocs = moreMallocsError{}
  120. func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
  121. prog := path.Join(*buildDir, test[0])
  122. args := test[1:]
  123. var cmd *exec.Cmd
  124. if *useValgrind {
  125. cmd = valgrindOf(false, prog, args...)
  126. } else if *useCallgrind {
  127. cmd = callgrindOf(prog, args...)
  128. } else if *useGDB {
  129. cmd = gdbOf(prog, args...)
  130. } else {
  131. cmd = exec.Command(prog, args...)
  132. }
  133. var stdoutBuf bytes.Buffer
  134. var stderrBuf bytes.Buffer
  135. cmd.Stdout = &stdoutBuf
  136. cmd.Stderr = &stderrBuf
  137. if mallocNumToFail >= 0 {
  138. cmd.Env = os.Environ()
  139. cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
  140. if *mallocTestDebug {
  141. cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
  142. }
  143. cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
  144. }
  145. if err := cmd.Start(); err != nil {
  146. return false, err
  147. }
  148. if err := cmd.Wait(); err != nil {
  149. if exitError, ok := err.(*exec.ExitError); ok {
  150. if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
  151. return false, errMoreMallocs
  152. }
  153. }
  154. fmt.Print(string(stderrBuf.Bytes()))
  155. return false, err
  156. }
  157. fmt.Print(string(stderrBuf.Bytes()))
  158. // Account for Windows line-endings.
  159. stdout := bytes.Replace(stdoutBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
  160. if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
  161. (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
  162. return true, nil
  163. }
  164. return false, nil
  165. }
  166. func runTest(test test) (bool, error) {
  167. if *mallocTest < 0 {
  168. return runTestOnce(test, -1)
  169. }
  170. for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
  171. if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
  172. if err != nil {
  173. err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
  174. }
  175. return passed, err
  176. }
  177. }
  178. }
  179. // shortTestName returns the short name of a test. Except for evp_test, it
  180. // assumes that any argument which ends in .txt is a path to a data file and not
  181. // relevant to the test's uniqueness.
  182. func shortTestName(test test) string {
  183. var args []string
  184. for _, arg := range test {
  185. if test[0] == "crypto/evp/evp_test" || !strings.HasSuffix(arg, ".txt") {
  186. args = append(args, arg)
  187. }
  188. }
  189. return strings.Join(args, " ")
  190. }
  191. // setWorkingDirectory walks up directories as needed until the current working
  192. // directory is the top of a BoringSSL checkout.
  193. func setWorkingDirectory() {
  194. for i := 0; i < 64; i++ {
  195. if _, err := os.Stat("BUILDING.md"); err == nil {
  196. return
  197. }
  198. os.Chdir("..")
  199. }
  200. panic("Couldn't find BUILDING.md in a parent directory!")
  201. }
  202. func parseTestConfig(filename string) ([]test, error) {
  203. in, err := os.Open(filename)
  204. if err != nil {
  205. return nil, err
  206. }
  207. defer in.Close()
  208. decoder := json.NewDecoder(in)
  209. var result []test
  210. if err := decoder.Decode(&result); err != nil {
  211. return nil, err
  212. }
  213. return result, nil
  214. }
  215. func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
  216. defer done.Done()
  217. for test := range tests {
  218. passed, err := runTest(test)
  219. results <- result{test, passed, err}
  220. }
  221. }
  222. func main() {
  223. flag.Parse()
  224. setWorkingDirectory()
  225. testCases, err := parseTestConfig("util/all_tests.json")
  226. if err != nil {
  227. fmt.Printf("Failed to parse input: %s\n", err)
  228. os.Exit(1)
  229. }
  230. var wg sync.WaitGroup
  231. tests := make(chan test, *numWorkers)
  232. results := make(chan result, *numWorkers)
  233. for i := 0; i < *numWorkers; i++ {
  234. wg.Add(1)
  235. go worker(tests, results, &wg)
  236. }
  237. go func() {
  238. for _, test := range testCases {
  239. tests <- test
  240. }
  241. close(tests)
  242. wg.Wait()
  243. close(results)
  244. }()
  245. testOutput := newTestOutput()
  246. var failed []test
  247. for testResult := range results {
  248. test := testResult.Test
  249. fmt.Printf("%s\n", strings.Join([]string(test), " "))
  250. name := shortTestName(test)
  251. if testResult.Error != nil {
  252. fmt.Printf("%s failed to complete: %s\n", test[0], testResult.Error)
  253. failed = append(failed, test)
  254. testOutput.addResult(name, "CRASHED")
  255. } else if !testResult.Passed {
  256. fmt.Printf("%s failed to print PASS on the last line.\n", test[0])
  257. failed = append(failed, test)
  258. testOutput.addResult(name, "FAIL")
  259. } else {
  260. testOutput.addResult(name, "PASS")
  261. }
  262. }
  263. if *jsonOutput != "" {
  264. if err := testOutput.writeTo(*jsonOutput); err != nil {
  265. fmt.Fprintf(os.Stderr, "Error: %s\n", err)
  266. }
  267. }
  268. if len(failed) > 0 {
  269. fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
  270. for _, test := range failed {
  271. fmt.Printf("\t%s\n", strings.Join([]string(test), " "))
  272. }
  273. os.Exit(1)
  274. }
  275. fmt.Printf("\nAll tests passed!\n")
  276. }