25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

385 lines
11 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. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "syscall"
  28. "time"
  29. )
  30. // TODO(davidben): Link tests with the malloc shim and port -malloc-test to this runner.
  31. var (
  32. useValgrind = flag.Bool("valgrind", false, "If true, run code under valgrind")
  33. useCallgrind = flag.Bool("callgrind", false, "If true, run code under valgrind to generate callgrind traces.")
  34. useGDB = flag.Bool("gdb", false, "If true, run BoringSSL code under gdb")
  35. useSDE = flag.Bool("sde", false, "If true, run BoringSSL code under Intel's SDE for each supported chip")
  36. buildDir = flag.String("build-dir", "build", "The build directory to run the tests from.")
  37. numWorkers = flag.Int("num-workers", runtime.NumCPU(), "Runs the given number of workers when testing.")
  38. jsonOutput = flag.String("json-output", "", "The file to output JSON results to.")
  39. mallocTest = flag.Int64("malloc-test", -1, "If non-negative, run each test with each malloc in turn failing from the given number onwards.")
  40. 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.")
  41. )
  42. type test struct {
  43. args []string
  44. // cpu, if not empty, contains an Intel CPU code to simulate. Run
  45. // `sde64 -help` to get a list of these codes.
  46. cpu string
  47. }
  48. type result struct {
  49. Test test
  50. Passed bool
  51. Error error
  52. }
  53. // testOutput is a representation of Chromium's JSON test result format. See
  54. // https://www.chromium.org/developers/the-json-test-results-format
  55. type testOutput struct {
  56. Version int `json:"version"`
  57. Interrupted bool `json:"interrupted"`
  58. PathDelimiter string `json:"path_delimiter"`
  59. SecondsSinceEpoch float64 `json:"seconds_since_epoch"`
  60. NumFailuresByType map[string]int `json:"num_failures_by_type"`
  61. Tests map[string]testResult `json:"tests"`
  62. }
  63. type testResult struct {
  64. Actual string `json:"actual"`
  65. Expected string `json:"expected"`
  66. IsUnexpected bool `json:"is_unexpected"`
  67. }
  68. // sdeCPUs contains a list of CPU code that we run all tests under when *useSDE
  69. // is true.
  70. var sdeCPUs = []string{
  71. "p4p", // Pentium4 Prescott
  72. "mrm", // Merom
  73. "pnr", // Penryn
  74. "nhm", // Nehalem
  75. "wsm", // Westmere
  76. "snb", // Sandy Bridge
  77. "ivb", // Ivy Bridge
  78. "hsw", // Haswell
  79. "bdw", // Broadwell
  80. "skx", // Skylake Server
  81. "skl", // Skylake Client
  82. "cnl", // Cannonlake
  83. "knl", // Knights Landing
  84. "slt", // Saltwell
  85. "slm", // Silvermont
  86. "glm", // Goldmont
  87. }
  88. func newTestOutput() *testOutput {
  89. return &testOutput{
  90. Version: 3,
  91. PathDelimiter: ".",
  92. SecondsSinceEpoch: float64(time.Now().UnixNano()) / float64(time.Second/time.Nanosecond),
  93. NumFailuresByType: make(map[string]int),
  94. Tests: make(map[string]testResult),
  95. }
  96. }
  97. func (t *testOutput) addResult(name, result string) {
  98. if _, found := t.Tests[name]; found {
  99. panic(name)
  100. }
  101. t.Tests[name] = testResult{
  102. Actual: result,
  103. Expected: "PASS",
  104. IsUnexpected: result != "PASS",
  105. }
  106. t.NumFailuresByType[result]++
  107. }
  108. func (t *testOutput) writeTo(name string) error {
  109. file, err := os.Create(name)
  110. if err != nil {
  111. return err
  112. }
  113. defer file.Close()
  114. out, err := json.MarshalIndent(t, "", " ")
  115. if err != nil {
  116. return err
  117. }
  118. _, err = file.Write(out)
  119. return err
  120. }
  121. func valgrindOf(dbAttach bool, path string, args ...string) *exec.Cmd {
  122. valgrindArgs := []string{"--error-exitcode=99", "--track-origins=yes", "--leak-check=full", "--quiet"}
  123. if dbAttach {
  124. valgrindArgs = append(valgrindArgs, "--db-attach=yes", "--db-command=xterm -e gdb -nw %f %p")
  125. }
  126. valgrindArgs = append(valgrindArgs, path)
  127. valgrindArgs = append(valgrindArgs, args...)
  128. return exec.Command("valgrind", valgrindArgs...)
  129. }
  130. func callgrindOf(path string, args ...string) *exec.Cmd {
  131. valgrindArgs := []string{"-q", "--tool=callgrind", "--dump-instr=yes", "--collect-jumps=yes", "--callgrind-out-file=" + *buildDir + "/callgrind/callgrind.out.%p"}
  132. valgrindArgs = append(valgrindArgs, path)
  133. valgrindArgs = append(valgrindArgs, args...)
  134. return exec.Command("valgrind", valgrindArgs...)
  135. }
  136. func gdbOf(path string, args ...string) *exec.Cmd {
  137. xtermArgs := []string{"-e", "gdb", "--args"}
  138. xtermArgs = append(xtermArgs, path)
  139. xtermArgs = append(xtermArgs, args...)
  140. return exec.Command("xterm", xtermArgs...)
  141. }
  142. func sdeOf(cpu, path string, args ...string) *exec.Cmd {
  143. sdeArgs := []string{"-" + cpu, "--", path}
  144. sdeArgs = append(sdeArgs, args...)
  145. return exec.Command("sde", sdeArgs...)
  146. }
  147. type moreMallocsError struct{}
  148. func (moreMallocsError) Error() string {
  149. return "child process did not exhaust all allocation calls"
  150. }
  151. var errMoreMallocs = moreMallocsError{}
  152. func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
  153. prog := path.Join(*buildDir, test.args[0])
  154. args := test.args[1:]
  155. var cmd *exec.Cmd
  156. if *useValgrind {
  157. cmd = valgrindOf(false, prog, args...)
  158. } else if *useCallgrind {
  159. cmd = callgrindOf(prog, args...)
  160. } else if *useGDB {
  161. cmd = gdbOf(prog, args...)
  162. } else if *useSDE {
  163. cmd = sdeOf(test.cpu, prog, args...)
  164. } else {
  165. cmd = exec.Command(prog, args...)
  166. }
  167. var outBuf bytes.Buffer
  168. cmd.Stdout = &outBuf
  169. cmd.Stderr = &outBuf
  170. if mallocNumToFail >= 0 {
  171. cmd.Env = os.Environ()
  172. cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
  173. if *mallocTestDebug {
  174. cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
  175. }
  176. cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
  177. }
  178. if err := cmd.Start(); err != nil {
  179. return false, err
  180. }
  181. if err := cmd.Wait(); err != nil {
  182. if exitError, ok := err.(*exec.ExitError); ok {
  183. if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
  184. return false, errMoreMallocs
  185. }
  186. }
  187. fmt.Print(string(outBuf.Bytes()))
  188. return false, err
  189. }
  190. // Account for Windows line-endings.
  191. stdout := bytes.Replace(outBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)
  192. if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
  193. (len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
  194. return true, nil
  195. }
  196. // Also accept a googletest-style pass line. This is left here in
  197. // transition until the tests are all converted and this script made
  198. // unnecessary.
  199. if bytes.Contains(stdout, []byte("\n[ PASSED ]")) {
  200. return true, nil
  201. }
  202. fmt.Print(string(outBuf.Bytes()))
  203. return false, nil
  204. }
  205. func runTest(test test) (bool, error) {
  206. if *mallocTest < 0 {
  207. return runTestOnce(test, -1)
  208. }
  209. for mallocNumToFail := int64(*mallocTest); ; mallocNumToFail++ {
  210. if passed, err := runTestOnce(test, mallocNumToFail); err != errMoreMallocs {
  211. if err != nil {
  212. err = fmt.Errorf("at malloc %d: %s", mallocNumToFail, err)
  213. }
  214. return passed, err
  215. }
  216. }
  217. }
  218. // shortTestName returns the short name of a test. Except for evp_test and
  219. // cipher_test, it assumes that any argument which ends in .txt is a path to a
  220. // data file and not relevant to the test's uniqueness.
  221. func shortTestName(test test) string {
  222. var args []string
  223. for _, arg := range test.args {
  224. if test.args[0] == "crypto/evp/evp_test" || test.args[0] == "crypto/cipher/cipher_test" || test.args[0] == "crypto/cipher/aead_test" || !strings.HasSuffix(arg, ".txt") {
  225. args = append(args, arg)
  226. }
  227. }
  228. return strings.Join(args, " ") + test.cpuMsg()
  229. }
  230. // setWorkingDirectory walks up directories as needed until the current working
  231. // directory is the top of a BoringSSL checkout.
  232. func setWorkingDirectory() {
  233. for i := 0; i < 64; i++ {
  234. if _, err := os.Stat("BUILDING.md"); err == nil {
  235. return
  236. }
  237. os.Chdir("..")
  238. }
  239. panic("Couldn't find BUILDING.md in a parent directory!")
  240. }
  241. func parseTestConfig(filename string) ([]test, error) {
  242. in, err := os.Open(filename)
  243. if err != nil {
  244. return nil, err
  245. }
  246. defer in.Close()
  247. decoder := json.NewDecoder(in)
  248. var testArgs [][]string
  249. if err := decoder.Decode(&testArgs); err != nil {
  250. return nil, err
  251. }
  252. var result []test
  253. for _, args := range testArgs {
  254. result = append(result, test{args: args})
  255. }
  256. return result, nil
  257. }
  258. func worker(tests <-chan test, results chan<- result, done *sync.WaitGroup) {
  259. defer done.Done()
  260. for test := range tests {
  261. passed, err := runTest(test)
  262. results <- result{test, passed, err}
  263. }
  264. }
  265. func (t test) cpuMsg() string {
  266. if len(t.cpu) == 0 {
  267. return ""
  268. }
  269. return fmt.Sprintf(" (for CPU %q)", t.cpu)
  270. }
  271. func main() {
  272. flag.Parse()
  273. setWorkingDirectory()
  274. testCases, err := parseTestConfig("util/all_tests.json")
  275. if err != nil {
  276. fmt.Printf("Failed to parse input: %s\n", err)
  277. os.Exit(1)
  278. }
  279. var wg sync.WaitGroup
  280. tests := make(chan test, *numWorkers)
  281. results := make(chan result, *numWorkers)
  282. for i := 0; i < *numWorkers; i++ {
  283. wg.Add(1)
  284. go worker(tests, results, &wg)
  285. }
  286. go func() {
  287. for _, test := range testCases {
  288. if *useSDE {
  289. for _, cpu := range sdeCPUs {
  290. testForCPU := test
  291. testForCPU.cpu = cpu
  292. tests <- testForCPU
  293. }
  294. } else {
  295. tests <- test
  296. }
  297. }
  298. close(tests)
  299. wg.Wait()
  300. close(results)
  301. }()
  302. testOutput := newTestOutput()
  303. var failed []test
  304. for testResult := range results {
  305. test := testResult.Test
  306. args := test.args
  307. fmt.Printf("%s%s\n", strings.Join(args, " "), test.cpuMsg())
  308. name := shortTestName(test)
  309. if testResult.Error != nil {
  310. fmt.Printf("%s failed to complete: %s\n", args[0], testResult.Error)
  311. failed = append(failed, test)
  312. testOutput.addResult(name, "CRASHED")
  313. } else if !testResult.Passed {
  314. fmt.Printf("%s failed to print PASS on the last line.\n", args[0])
  315. failed = append(failed, test)
  316. testOutput.addResult(name, "FAIL")
  317. } else {
  318. testOutput.addResult(name, "PASS")
  319. }
  320. }
  321. if *jsonOutput != "" {
  322. if err := testOutput.writeTo(*jsonOutput); err != nil {
  323. fmt.Fprintf(os.Stderr, "Error: %s\n", err)
  324. }
  325. }
  326. if len(failed) > 0 {
  327. fmt.Printf("\n%d of %d tests failed:\n", len(failed), len(testCases))
  328. for _, test := range failed {
  329. fmt.Printf("\t%s%s\n", strings.Join(test.args, ""), test.cpuMsg())
  330. }
  331. os.Exit(1)
  332. }
  333. fmt.Printf("\nAll tests passed!\n")
  334. }