No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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