romlib_generator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2019, Arm Limited. All rights reserved.
  3. #
  4. # SPDX-License-Identifier: BSD-3-Clause
  5. """
  6. This module contains a set of classes and a runner that can generate code for the romlib module
  7. based on the templates in the 'templates' directory.
  8. """
  9. import argparse
  10. import os
  11. import re
  12. import subprocess
  13. import string
  14. import sys
  15. class IndexFileParser:
  16. """
  17. Parses the contents of the index file into the items and dependencies variables. It
  18. also resolves included files in the index files recursively with circular inclusion detection.
  19. """
  20. def __init__(self):
  21. self.items = []
  22. self.dependencies = {}
  23. self.include_chain = []
  24. def add_dependency(self, parent, dependency):
  25. """ Adds a dependency into the dependencies variable. """
  26. if parent in self.dependencies:
  27. self.dependencies[parent].append(dependency)
  28. else:
  29. self.dependencies[parent] = [dependency]
  30. def get_dependencies(self, parent):
  31. """ Gets all the recursive dependencies of a parent file. """
  32. parent = os.path.normpath(parent)
  33. if parent in self.dependencies:
  34. direct_deps = self.dependencies[parent]
  35. deps = direct_deps
  36. for direct_dep in direct_deps:
  37. deps += self.get_dependencies(direct_dep)
  38. return deps
  39. return []
  40. def parse(self, file_name):
  41. """ Opens and parses index file. """
  42. file_name = os.path.normpath(file_name)
  43. if file_name not in self.include_chain:
  44. self.include_chain.append(file_name)
  45. self.dependencies[file_name] = []
  46. else:
  47. raise Exception("Circular dependency detected: " + file_name)
  48. with open(file_name, "r") as index_file:
  49. for line in index_file.readlines():
  50. line_elements = line.split()
  51. if line.startswith("#") or not line_elements:
  52. # Comment or empty line
  53. continue
  54. if line_elements[0] == "reserved":
  55. # Reserved slot in the jump table
  56. self.items.append({"type": "reserved"})
  57. elif line_elements[0] == "include" and len(line_elements) > 1:
  58. # Include other index file
  59. included_file = os.path.normpath(line_elements[1])
  60. self.add_dependency(file_name, included_file)
  61. self.parse(included_file)
  62. elif len(line_elements) > 1:
  63. # Library function
  64. library_name = line_elements[0]
  65. function_name = line_elements[1]
  66. patch = bool(len(line_elements) > 2 and line_elements[2] == "patch")
  67. self.items.append({"type": "function", "library_name": library_name,
  68. "function_name": function_name, "patch": patch})
  69. else:
  70. raise Exception("Invalid line: '" + line + "'")
  71. self.include_chain.pop()
  72. class RomlibApplication:
  73. """ Base class of romlib applications. """
  74. TEMPLATE_DIR = os.path.dirname(os.path.realpath(__file__)) + "/templates/"
  75. def __init__(self, prog):
  76. self.args = argparse.ArgumentParser(prog=prog, description=self.__doc__)
  77. self.config = None
  78. def parse_arguments(self, argv):
  79. """ Parses the arguments that should come from the command line arguments. """
  80. self.config = self.args.parse_args(argv)
  81. def build_template(self, name, mapping=None, remove_comment=False):
  82. """
  83. Loads a template and builds it with the defined mapping. Template paths are always relative
  84. to this script.
  85. """
  86. with open(self.TEMPLATE_DIR + name, "r") as template_file:
  87. if remove_comment:
  88. # Removing copyright comment to make the generated code more readable when the
  89. # template is inserted multiple times into the output.
  90. template_lines = template_file.readlines()
  91. end_of_comment_line = 0
  92. for index, line in enumerate(template_lines):
  93. if line.find("*/") != -1:
  94. end_of_comment_line = index
  95. break
  96. template_data = "".join(template_lines[end_of_comment_line + 1:])
  97. else:
  98. template_data = template_file.read()
  99. template = string.Template(template_data)
  100. return template.substitute(mapping)
  101. class IndexPreprocessor(RomlibApplication):
  102. """ Removes empty and comment lines from the index file and resolves includes. """
  103. def __init__(self, prog):
  104. RomlibApplication.__init__(self, prog)
  105. self.args.add_argument("-o", "--output", help="Output file", metavar="output",
  106. default="jmpvar.s")
  107. self.args.add_argument("--deps", help="Dependency file")
  108. self.args.add_argument("file", help="Input file")
  109. def main(self):
  110. """
  111. After parsing the input index file it generates a clean output with all includes resolved.
  112. Using --deps option it also outputs the dependencies in makefile format like gcc's with -M.
  113. """
  114. index_file_parser = IndexFileParser()
  115. index_file_parser.parse(self.config.file)
  116. with open(self.config.output, "w") as output_file:
  117. for item in index_file_parser.items:
  118. if item["type"] == "function":
  119. patch = "\tpatch" if item["patch"] else ""
  120. output_file.write(
  121. item["library_name"] + "\t" + item["function_name"] + patch + "\n")
  122. else:
  123. output_file.write("reserved\n")
  124. if self.config.deps:
  125. with open(self.config.deps, "w") as deps_file:
  126. deps = [self.config.file] + index_file_parser.get_dependencies(self.config.file)
  127. deps_file.write(self.config.output + ": " + " \\\n".join(deps) + "\n")
  128. class TableGenerator(RomlibApplication):
  129. """ Generates the jump table by parsing the index file. """
  130. def __init__(self, prog):
  131. RomlibApplication.__init__(self, prog)
  132. self.args.add_argument("-o", "--output", help="Output file", metavar="output",
  133. default="jmpvar.s")
  134. self.args.add_argument("--bti", help="Branch Target Identification", type=int)
  135. self.args.add_argument("file", help="Input file")
  136. def main(self):
  137. """
  138. Inserts the jmptbl definition and the jump entries into the output file. Also can insert
  139. BTI related code before entries if --bti option set. It can output a dependency file of the
  140. included index files. This can be directly included in makefiles.
  141. """
  142. index_file_parser = IndexFileParser()
  143. index_file_parser.parse(self.config.file)
  144. with open(self.config.output, "w") as output_file:
  145. output_file.write(self.build_template("jmptbl_header.S"))
  146. bti = "_bti" if self.config.bti == 1 else ""
  147. for item in index_file_parser.items:
  148. template_name = "jmptbl_entry_" + item["type"] + bti + ".S"
  149. output_file.write(self.build_template(template_name, item, True))
  150. class LinkArgs(RomlibApplication):
  151. """ Generates the link arguments to wrap functions. """
  152. def __init__(self, prog):
  153. RomlibApplication.__init__(self, prog)
  154. self.args.add_argument("file", help="Input file")
  155. def main(self):
  156. index_file_parser = IndexFileParser()
  157. index_file_parser.parse(self.config.file)
  158. fns = [item["function_name"] for item in index_file_parser.items
  159. if not item["patch"] and item["type"] != "reserved"]
  160. print(" ".join("-Wl,--wrap " + f for f in fns))
  161. class WrapperGenerator(RomlibApplication):
  162. """
  163. Generates a wrapper function for each entry in the index file except for the ones that contain
  164. the keyword patch. The generated wrapper file is called <lib>_<fn_name>.s.
  165. """
  166. def __init__(self, prog):
  167. RomlibApplication.__init__(self, prog)
  168. self.args.add_argument("-b", help="Build directory", default=".", metavar="build")
  169. self.args.add_argument("--bti", help="Branch Target Identification", type=int)
  170. self.args.add_argument("--list", help="Only list assembly files", action="store_true")
  171. self.args.add_argument("file", help="Input file")
  172. def main(self):
  173. """
  174. Iterates through the items in the parsed index file and builds the template for each entry.
  175. """
  176. index_file_parser = IndexFileParser()
  177. index_file_parser.parse(self.config.file)
  178. bti = "_bti" if self.config.bti == 1 else ""
  179. function_offset = 0
  180. files = []
  181. for item_index in range(0, len(index_file_parser.items)):
  182. item = index_file_parser.items[item_index]
  183. if item["type"] == "reserved" or item["patch"]:
  184. continue
  185. if not self.config.list:
  186. # The jump instruction is 4 bytes but BTI requires and extra instruction so
  187. # this makes it 8 bytes per entry.
  188. function_offset = item_index * (8 if self.config.bti else 4)
  189. item["function_offset"] = function_offset
  190. files.append(self.build_template("wrapper" + bti + ".S", item))
  191. if self.config.list:
  192. print(self.config.b + "/wrappers.s")
  193. else:
  194. with open(self.config.b + "/wrappers.s", "w") as asm_file:
  195. asm_file.write("\n".join(files))
  196. class VariableGenerator(RomlibApplication):
  197. """ Generates the jump table global variable with the absolute address in ROM. """
  198. def __init__(self, prog):
  199. RomlibApplication.__init__(self, prog)
  200. self.args.add_argument("-o", "--output", help="Output file", metavar="output",
  201. default="jmpvar.s")
  202. self.args.add_argument("file", help="Input file")
  203. def main(self):
  204. """
  205. Runs nm -a command on the input file and inserts the address of the .text section into the
  206. template as the ROM address of the jmp_table.
  207. """
  208. symbols = subprocess.check_output(["nm", "-a", self.config.file])
  209. matching_symbol = re.search("([0-9A-Fa-f]+) . \\.text", str(symbols))
  210. if not matching_symbol:
  211. raise Exception("No '.text' section was found in %s" % self.config.file)
  212. mapping = {"jmptbl_address": matching_symbol.group(1)}
  213. with open(self.config.output, "w") as output_file:
  214. output_file.write(self.build_template("jmptbl_glob_var.S", mapping))
  215. if __name__ == "__main__":
  216. APPS = {"genvar": VariableGenerator, "pre": IndexPreprocessor,
  217. "gentbl": TableGenerator, "genwrappers": WrapperGenerator,
  218. "link-flags": LinkArgs}
  219. if len(sys.argv) < 2 or sys.argv[1] not in APPS:
  220. print("usage: romlib_generator.py [%s] [args]" % "|".join(APPS.keys()), file=sys.stderr)
  221. sys.exit(1)
  222. APP = APPS[sys.argv[1]]("romlib_generator.py " + sys.argv[1])
  223. APP.parse_arguments(sys.argv[2:])
  224. try:
  225. APP.main()
  226. sys.exit(0)
  227. except FileNotFoundError as file_not_found_error:
  228. print(file_not_found_error, file=sys.stderr)
  229. except subprocess.CalledProcessError as called_process_error:
  230. print(called_process_error.output, file=sys.stderr)
  231. sys.exit(1)