Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

443 wiersze
9.6 KiB

  1. // Copyright (c) 2014, 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. "bufio"
  17. "errors"
  18. "flag"
  19. "fmt"
  20. "io"
  21. "os"
  22. "path/filepath"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "unicode"
  27. )
  28. var resetFlag *bool = flag.Bool("reset", false, "If true, ignore current assignments and reassign from scratch")
  29. func makeErrors(reset bool) error {
  30. dirName, err := os.Getwd()
  31. if err != nil {
  32. return err
  33. }
  34. lib := filepath.Base(dirName)
  35. headerPath, err := findHeader(lib + ".h")
  36. if err != nil {
  37. return err
  38. }
  39. sourcePath := lib + "_error.c"
  40. headerFile, err := os.Open(headerPath)
  41. if err != nil {
  42. if os.IsNotExist(err) {
  43. return fmt.Errorf("No header %s. Run in the right directory or touch the file.", headerPath)
  44. }
  45. return err
  46. }
  47. prefix := strings.ToUpper(lib)
  48. functions, reasons, err := parseHeader(prefix, headerFile)
  49. headerFile.Close()
  50. if reset {
  51. err = nil
  52. functions = make(map[string]int)
  53. reasons = make(map[string]int)
  54. }
  55. if err != nil {
  56. return err
  57. }
  58. dir, err := os.Open(".")
  59. if err != nil {
  60. return err
  61. }
  62. defer dir.Close()
  63. filenames, err := dir.Readdirnames(-1)
  64. if err != nil {
  65. return err
  66. }
  67. for _, name := range filenames {
  68. if !strings.HasSuffix(name, ".c") {
  69. continue
  70. }
  71. if err := addFunctionsAndReasons(functions, reasons, name, prefix); err != nil {
  72. return err
  73. }
  74. }
  75. assignNewValues(functions)
  76. assignNewValues(reasons)
  77. headerFile, err = os.Open(headerPath)
  78. if err != nil {
  79. return err
  80. }
  81. defer headerFile.Close()
  82. newHeaderFile, err := os.OpenFile(headerPath+".tmp", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
  83. if err != nil {
  84. return err
  85. }
  86. defer newHeaderFile.Close()
  87. if err := writeHeaderFile(newHeaderFile, headerFile, prefix, functions, reasons); err != nil {
  88. return err
  89. }
  90. os.Rename(headerPath+".tmp", headerPath)
  91. sourceFile, err := os.OpenFile(sourcePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
  92. if err != nil {
  93. return err
  94. }
  95. defer sourceFile.Close()
  96. fmt.Fprintf(sourceFile, `/* Copyright (c) 2014, Google Inc.
  97. *
  98. * Permission to use, copy, modify, and/or distribute this software for any
  99. * purpose with or without fee is hereby granted, provided that the above
  100. * copyright notice and this permission notice appear in all copies.
  101. *
  102. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  103. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  104. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  105. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  106. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  107. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  108. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  109. #include <openssl/err.h>
  110. #include <openssl/%s.h>
  111. const ERR_STRING_DATA %s_error_string_data[] = {
  112. `, lib, prefix)
  113. outputStrings(sourceFile, lib, typeFunctions, functions)
  114. outputStrings(sourceFile, lib, typeReasons, reasons)
  115. sourceFile.WriteString(" {0, NULL},\n};\n")
  116. return nil
  117. }
  118. func findHeader(basename string) (path string, err error) {
  119. includeDir := filepath.Join("..", "include")
  120. fi, err := os.Stat(includeDir)
  121. if err != nil && os.IsNotExist(err) {
  122. includeDir = filepath.Join("..", includeDir)
  123. fi, err = os.Stat(includeDir)
  124. }
  125. if err != nil {
  126. return "", errors.New("cannot find path to include directory")
  127. }
  128. if !fi.IsDir() {
  129. return "", errors.New("include node is not a directory")
  130. }
  131. return filepath.Join(includeDir, "openssl", basename), nil
  132. }
  133. type assignment struct {
  134. key string
  135. value int
  136. }
  137. type assignmentsSlice []assignment
  138. func (a assignmentsSlice) Len() int {
  139. return len(a)
  140. }
  141. func (a assignmentsSlice) Less(i, j int) bool {
  142. return a[i].value < a[j].value
  143. }
  144. func (a assignmentsSlice) Swap(i, j int) {
  145. a[i], a[j] = a[j], a[i]
  146. }
  147. func outputAssignments(w io.Writer, assignments map[string]int) {
  148. var sorted assignmentsSlice
  149. for key, value := range assignments {
  150. sorted = append(sorted, assignment{key, value})
  151. }
  152. sort.Sort(sorted)
  153. for _, assignment := range sorted {
  154. fmt.Fprintf(w, "#define %s %d\n", assignment.key, assignment.value)
  155. }
  156. }
  157. func parseDefineLine(line, lib string) (typ int, key string, value int, ok bool) {
  158. if !strings.HasPrefix(line, "#define ") {
  159. return
  160. }
  161. fields := strings.Fields(line)
  162. if len(fields) != 3 {
  163. return
  164. }
  165. funcPrefix := lib + "_F_"
  166. reasonPrefix := lib + "_R_"
  167. key = fields[1]
  168. switch {
  169. case strings.HasPrefix(key, funcPrefix):
  170. typ = typeFunctions
  171. case strings.HasPrefix(key, reasonPrefix):
  172. typ = typeReasons
  173. default:
  174. return
  175. }
  176. var err error
  177. if value, err = strconv.Atoi(fields[2]); err != nil {
  178. return
  179. }
  180. ok = true
  181. return
  182. }
  183. func writeHeaderFile(w io.Writer, headerFile io.Reader, lib string, functions, reasons map[string]int) error {
  184. var last []byte
  185. var haveLast, sawDefine bool
  186. newLine := []byte("\n")
  187. scanner := bufio.NewScanner(headerFile)
  188. for scanner.Scan() {
  189. line := scanner.Text()
  190. _, _, _, ok := parseDefineLine(line, lib)
  191. if ok {
  192. sawDefine = true
  193. continue
  194. }
  195. if haveLast {
  196. w.Write(last)
  197. w.Write(newLine)
  198. }
  199. if len(line) > 0 || !sawDefine {
  200. last = []byte(line)
  201. haveLast = true
  202. } else {
  203. haveLast = false
  204. }
  205. sawDefine = false
  206. }
  207. if err := scanner.Err(); err != nil {
  208. return err
  209. }
  210. outputAssignments(w, functions)
  211. outputAssignments(w, reasons)
  212. w.Write(newLine)
  213. if haveLast {
  214. w.Write(last)
  215. w.Write(newLine)
  216. }
  217. return nil
  218. }
  219. const (
  220. typeFunctions = iota
  221. typeReasons
  222. )
  223. func outputStrings(w io.Writer, lib string, ty int, assignments map[string]int) {
  224. lib = strings.ToUpper(lib)
  225. prefixLen := len(lib + "_F_")
  226. keys := make([]string, 0, len(assignments))
  227. for key := range assignments {
  228. keys = append(keys, key)
  229. }
  230. sort.Strings(keys)
  231. for _, key := range keys {
  232. var pack string
  233. if ty == typeFunctions {
  234. pack = key + ", 0"
  235. } else {
  236. pack = "0, " + key
  237. }
  238. fmt.Fprintf(w, " {ERR_PACK(ERR_LIB_%s, %s), \"%s\"},\n", lib, pack, key[prefixLen:])
  239. }
  240. }
  241. func assignNewValues(assignments map[string]int) {
  242. max := 99
  243. for _, value := range assignments {
  244. if value > max {
  245. max = value
  246. }
  247. }
  248. max++
  249. for key, value := range assignments {
  250. if value == -1 {
  251. assignments[key] = max
  252. max++
  253. }
  254. }
  255. }
  256. func handleDeclareMacro(line, join, macroName string, m map[string]int) {
  257. if i := strings.Index(line, macroName); i >= 0 {
  258. contents := line[i+len(macroName):]
  259. if i := strings.Index(contents, ")"); i >= 0 {
  260. contents = contents[:i]
  261. args := strings.Split(contents, ",")
  262. for i := range args {
  263. args[i] = strings.TrimSpace(args[i])
  264. }
  265. if len(args) != 2 {
  266. panic("Bad macro line: " + line)
  267. }
  268. token := args[0] + join + args[1]
  269. if _, ok := m[token]; !ok {
  270. m[token] = -1
  271. }
  272. }
  273. }
  274. }
  275. func addFunctionsAndReasons(functions, reasons map[string]int, filename, prefix string) error {
  276. file, err := os.Open(filename)
  277. if err != nil {
  278. return err
  279. }
  280. defer file.Close()
  281. prefix += "_"
  282. reasonPrefix := prefix + "R_"
  283. var currentFunction string
  284. scanner := bufio.NewScanner(file)
  285. for scanner.Scan() {
  286. line := scanner.Text()
  287. if len(line) > 0 && unicode.IsLetter(rune(line[0])) {
  288. /* Function start */
  289. fields := strings.Fields(line)
  290. for _, field := range fields {
  291. if i := strings.Index(field, "("); i != -1 {
  292. f := field[:i]
  293. // The return type of some functions is
  294. // a macro that contains a "(".
  295. if f == "STACK_OF" {
  296. continue
  297. }
  298. currentFunction = f
  299. for len(currentFunction) > 0 && currentFunction[0] == '*' {
  300. currentFunction = currentFunction[1:]
  301. }
  302. break
  303. }
  304. }
  305. }
  306. if strings.Contains(line, "OPENSSL_PUT_ERROR(") {
  307. functionToken := prefix + "F_" + currentFunction
  308. if _, ok := functions[functionToken]; !ok {
  309. functions[functionToken] = -1
  310. }
  311. }
  312. handleDeclareMacro(line, "_R_", "OPENSSL_DECLARE_ERROR_REASON(", reasons)
  313. handleDeclareMacro(line, "_F_", "OPENSSL_DECLARE_ERROR_FUNCTION(", functions)
  314. for len(line) > 0 {
  315. i := strings.Index(line, prefix)
  316. if i == -1 {
  317. break
  318. }
  319. line = line[i:]
  320. end := strings.IndexFunc(line, func(r rune) bool {
  321. return !(r == '_' || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9'))
  322. })
  323. if end == -1 {
  324. end = len(line)
  325. }
  326. var token string
  327. token, line = line[:end], line[end:]
  328. switch {
  329. case strings.HasPrefix(token, reasonPrefix):
  330. if _, ok := reasons[token]; !ok {
  331. reasons[token] = -1
  332. }
  333. }
  334. }
  335. }
  336. return scanner.Err()
  337. }
  338. func parseHeader(lib string, file io.Reader) (functions, reasons map[string]int, err error) {
  339. functions = make(map[string]int)
  340. reasons = make(map[string]int)
  341. scanner := bufio.NewScanner(file)
  342. for scanner.Scan() {
  343. typ, key, value, ok := parseDefineLine(scanner.Text(), lib)
  344. if !ok {
  345. continue
  346. }
  347. switch typ {
  348. case typeFunctions:
  349. functions[key] = value
  350. case typeReasons:
  351. reasons[key] = value
  352. default:
  353. panic("internal error")
  354. }
  355. }
  356. err = scanner.Err()
  357. return
  358. }
  359. func main() {
  360. flag.Parse()
  361. if err := makeErrors(*resetFlag); err != nil {
  362. fmt.Fprintf(os.Stderr, "%s\n", err)
  363. os.Exit(1)
  364. }
  365. }