gen_esp_err_to_name.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2018 Espressif Systems (Shanghai) PTE LTD
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import os
  17. import argparse
  18. import mmap
  19. import re
  20. import fnmatch
  21. import string
  22. import collections
  23. import textwrap
  24. # list files here which should not be parsed
  25. ignore_files = [ 'components/mdns/test_afl_fuzz_host/esp32_compat.h' ]
  26. # macros from here have higher priorities in case of collisions
  27. priority_headers = [ 'components/esp32/include/esp_err.h' ]
  28. err_dict = collections.defaultdict(list) #identified errors are stored here; mapped by the error code
  29. rev_err_dict = dict() #map of error string to error code
  30. unproc_list = list() #errors with unknown codes which depend on other errors
  31. class ErrItem:
  32. """
  33. Contains information about the error:
  34. - name - error string
  35. - file - relative path inside the IDF project to the file which defines this error
  36. - comment - (optional) comment for the error
  37. - rel_str - (optional) error string which is a base for the error
  38. - rel_off - (optional) offset in relation to the base error
  39. """
  40. def __init__(self, name, file, comment, rel_str = "", rel_off = 0):
  41. self.name = name
  42. self.file = file
  43. self.comment = comment
  44. self.rel_str = rel_str
  45. self.rel_off = rel_off
  46. def __str__(self):
  47. ret = self.name + " from " + self.file
  48. if (self.rel_str != ""):
  49. ret += " is (" + self.rel_str + " + " + str(self.rel_off) + ")"
  50. if self.comment != "":
  51. ret += " // " + self.comment
  52. return ret
  53. def __cmp__(self, other):
  54. if self.file in priority_headers and other.file not in priority_headers:
  55. return -1
  56. elif self.file not in priority_headers and other.file in priority_headers:
  57. return 1
  58. base = "_BASE"
  59. if self.file == other.file:
  60. if self.name.endswith(base) and not(other.name.endswith(base)):
  61. return 1
  62. elif not(self.name.endswith(base)) and other.name.endswith(base):
  63. return -1
  64. self_key = self.file + self.name
  65. other_key = other.file + other.name
  66. if self_key < other_key:
  67. return -1
  68. elif self_key > other_key:
  69. return 1
  70. else:
  71. return 0
  72. class InputError(RuntimeError):
  73. """
  74. Represents and error on the input
  75. """
  76. def __init__(self, p, e):
  77. super(InputError, self).__init__(p + ": " + e)
  78. def process(line, idf_path):
  79. """
  80. Process a line of text from file idf_path (relative to IDF project).
  81. Fills the global list unproc_list and dictionaries err_dict, rev_err_dict
  82. """
  83. if idf_path.endswith(".c"):
  84. # We would not try to include a C file
  85. raise InputError(idf_path, "This line should be in a header file: %s" % line)
  86. words = re.split(r' +', line, 2)
  87. # words[1] is the error name
  88. # words[2] is the rest of the line (value, base + value, comment)
  89. if len(words) < 2:
  90. raise InputError(idf_path, "Error at line %s" % line)
  91. line = ""
  92. todo_str = words[2]
  93. comment = ""
  94. # identify possible comment
  95. m = re.search(r'/\*!<(.+?(?=\*/))', todo_str)
  96. if m:
  97. comment = string.strip(m.group(1))
  98. todo_str = string.strip(todo_str[:m.start()]) # keep just the part before the comment
  99. # identify possible parentheses ()
  100. m = re.search(r'\((.+)\)', todo_str)
  101. if m:
  102. todo_str = m.group(1) #keep what is inside the parentheses
  103. # identify BASE error code, e.g. from the form BASE + 0x01
  104. m = re.search(r'\s*(\w+)\s*\+(.+)', todo_str)
  105. if m:
  106. related = m.group(1) # BASE
  107. todo_str = m.group(2) # keep and process only what is after "BASE +"
  108. # try to match a hexadecimal number
  109. m = re.search(r'0x([0-9A-Fa-f]+)', todo_str)
  110. if m:
  111. num = int(m.group(1), 16)
  112. else:
  113. # Try to match a decimal number. Negative value is possible for some numbers, e.g. ESP_FAIL
  114. m = re.search(r'(-?[0-9]+)', todo_str)
  115. if m:
  116. num = int(m.group(1), 10)
  117. elif re.match(r'\w+', todo_str):
  118. # It is possible that there is no number, e.g. #define ERROR BASE
  119. related = todo_str # BASE error
  120. num = 0 # (BASE + 0)
  121. else:
  122. raise InputError(idf_path, "Cannot parse line %s" % line)
  123. try:
  124. related
  125. except NameError:
  126. # The value of the error is known at this moment because it do not depends on some other BASE error code
  127. err_dict[num].append(ErrItem(words[1], idf_path, comment))
  128. rev_err_dict[words[1]] = num
  129. else:
  130. # Store the information available now and compute the error code later
  131. unproc_list.append(ErrItem(words[1], idf_path, comment, related, num))
  132. def process_remaining_errors():
  133. """
  134. Create errors which could not be processed before because the error code
  135. for the BASE error code wasn't known.
  136. This works for sure only if there is no multiple-time dependency, e.g.:
  137. #define BASE1 0
  138. #define BASE2 (BASE1 + 10)
  139. #define ERROR (BASE2 + 10) - ERROR will be processed successfully only if it processed later than BASE2
  140. """
  141. for item in unproc_list:
  142. if item.rel_str in rev_err_dict:
  143. base_num = rev_err_dict[item.rel_str]
  144. base = err_dict[base_num][0]
  145. num = base_num + item.rel_off
  146. err_dict[num].append(ErrItem(item.name, item.file, item.comment))
  147. rev_err_dict[item.name] = num
  148. else:
  149. print(item.rel_str + " referenced by " + item.name + " in " + item.file + " is unknown")
  150. del unproc_list[:]
  151. def path_to_include(path):
  152. """
  153. Process the path (relative to the IDF project) in a form which can be used
  154. to include in a C file. Using just the filename does not work all the
  155. time because some files are deeper in the tree. This approach tries to
  156. find an 'include' parent directory an include its subdirectories, e.g.
  157. "components/XY/include/esp32/file.h" will be transported into "esp32/file.h"
  158. So this solution works only works when the subdirectory or subdirectories
  159. are inside the "include" directory. Other special cases need to be handled
  160. here when the compiler gives an unknown header file error message.
  161. """
  162. spl_path = string.split(path, os.sep)
  163. try:
  164. i = spl_path.index('include')
  165. except ValueError:
  166. # no include in the path -> use just the filename
  167. return os.path.basename(path)
  168. else:
  169. return str(os.sep).join(spl_path[i+1:]) # subdirectories and filename in "include"
  170. def print_warning(error_list, error_code):
  171. """
  172. Print warning about errors with the same error code
  173. """
  174. print("[WARNING] The following errors have the same code (%d):" % error_code)
  175. for e in error_list:
  176. print(" " + str(e))
  177. def max_string_width():
  178. max = 0
  179. for k in err_dict.keys():
  180. for e in err_dict[k]:
  181. x = len(e.name)
  182. if x > max:
  183. max = x
  184. return max
  185. def generate_output(fin, fout):
  186. """
  187. Writes the output to fout based on th error dictionary err_dict and
  188. template file fin.
  189. """
  190. # make includes unique by using a set
  191. includes = set()
  192. for k in err_dict.keys():
  193. for e in err_dict[k]:
  194. includes.add(path_to_include(e.file))
  195. # The order in a set in non-deterministic therefore it could happen that the
  196. # include order will be different in other machines and false difference
  197. # in the output file could be reported. In order to avoid this, the items
  198. # are sorted in a list.
  199. include_list = list(includes)
  200. include_list.sort()
  201. max_width = max_string_width() + 17 + 1 # length of " ERR_TBL_IT()," with spaces is 17
  202. max_decdig = max(len(str(k)) for k in err_dict.keys())
  203. for line in fin:
  204. if re.match(r'@COMMENT@', line):
  205. fout.write("//Do not edit this file because it is autogenerated by " + os.path.basename(__file__) + "\n")
  206. elif re.match(r'@HEADERS@', line):
  207. for i in include_list:
  208. fout.write("#if __has_include(\"" + i + "\")\n#include \"" + i + "\"\n#endif\n")
  209. elif re.match(r'@ERROR_ITEMS@', line):
  210. last_file = ""
  211. for k in sorted(err_dict.keys()):
  212. if len(err_dict[k]) > 1:
  213. err_dict[k].sort()
  214. print_warning(err_dict[k], k)
  215. for e in err_dict[k]:
  216. if e.file != last_file:
  217. last_file = e.file
  218. fout.write(" // %s\n" % last_file)
  219. table_line = (" ERR_TBL_IT(" + e.name + "), ").ljust(max_width) + "/* " + str(k).rjust(max_decdig)
  220. fout.write("# ifdef %s\n" % e.name)
  221. fout.write(table_line)
  222. hexnum_length = 0
  223. if k > 0: # negative number and zero should be only ESP_FAIL and ESP_OK
  224. hexnum = " 0x%x" % k
  225. hexnum_length = len(hexnum)
  226. fout.write(hexnum)
  227. if e.comment != "":
  228. if len(e.comment) < 50:
  229. fout.write(" %s" % e.comment)
  230. else:
  231. indent = " " * (len(table_line) + hexnum_length + 1)
  232. w = textwrap.wrap(e.comment, width=120, initial_indent = indent, subsequent_indent = indent)
  233. # this couldn't be done with initial_indent because there is no initial_width option
  234. fout.write(" %s" % w[0].strip())
  235. for i in range(1, len(w)):
  236. fout.write("\n%s" % w[i])
  237. fout.write(" */\n# endif\n")
  238. else:
  239. fout.write(line)
  240. def main():
  241. parser = argparse.ArgumentParser(description='ESP32 esp_err_to_name lookup generator for esp_err_t')
  242. parser.add_argument('input', help='Path to the esp_err_to_name.c.in template input.', default=os.environ['IDF_PATH'] + '/components/esp32/esp_err_to_name.c.in', nargs='?')
  243. parser.add_argument('output', help='Path to the esp_err_to_name.c output.', default=os.environ['IDF_PATH'] + '/components/esp32/esp_err_to_name.c', nargs='?')
  244. args = parser.parse_args()
  245. for root, dirnames, filenames in os.walk(os.environ['IDF_PATH']):
  246. for filename in fnmatch.filter(filenames, '*.[ch]'):
  247. full_path = os.path.join(root, filename)
  248. idf_path = os.path.relpath(full_path, os.environ['IDF_PATH'])
  249. if idf_path in ignore_files:
  250. continue
  251. with open(full_path, "r+b") as f:
  252. try:
  253. map = mmap.mmap(f.fileno(), 0, prot=mmap.ACCESS_READ)
  254. except ValueError:
  255. pass # An empty file cannot be mmaped
  256. else:
  257. for line in iter(map.readline, ""):
  258. # match also ESP_OK and ESP_FAIL because some of ESP_ERRs are referencing them
  259. if re.match(r"\s*#define\s+(ESP_ERR_|ESP_OK|ESP_FAIL)", line):
  260. try:
  261. process(str.strip(line), idf_path)
  262. except InputError as e:
  263. print (e)
  264. process_remaining_errors()
  265. with open(args.input, 'r') as fin, open(args.output, 'w') as fout:
  266. generate_output(fin, fout)
  267. if __name__ == "__main__":
  268. main()