make-target-delegates.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #!/usr/bin/env python3
  2. # Copyright (C) 2013-2022 Free Software Foundation, Inc.
  3. #
  4. # This file is part of GDB.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. # Usage:
  19. # make-target-delegates.py
  20. import re
  21. import gdbcopyright
  22. # The line we search for in target.h that marks where we should start
  23. # looking for methods.
  24. TRIGGER = re.compile(r"^struct target_ops$")
  25. # The end of the methods part.
  26. ENDER = re.compile(r"^\s*};$")
  27. # Match a C symbol.
  28. SYMBOL = "[a-zA-Z_][a-zA-Z0-9_]*"
  29. # Match the name part of a method in struct target_ops.
  30. NAME_PART = r"(?P<name>" + SYMBOL + ")\s"
  31. # Match the arguments to a method.
  32. ARGS_PART = r"(?P<args>\(.*\))"
  33. # We strip the indentation so here we only need the caret.
  34. INTRO_PART = r"^"
  35. POINTER_PART = r"\s*(\*)?\s*"
  36. # Match a C++ symbol, including scope operators and template
  37. # parameters. E.g., 'std::vector<something>'.
  38. CP_SYMBOL = r"[a-zA-Z_][a-zA-Z0-9_<>:]*"
  39. # Match the return type when it is "ordinary".
  40. SIMPLE_RETURN_PART = r"((struct|class|enum|union)\s+)?" + CP_SYMBOL
  41. # Match a return type.
  42. RETURN_PART = r"((const|volatile)\s+)?(" + SIMPLE_RETURN_PART + ")" + POINTER_PART
  43. # Match "virtual".
  44. VIRTUAL_PART = r"virtual\s"
  45. # Match the TARGET_DEFAULT_* attribute for a method.
  46. TARGET_DEFAULT_PART = r"TARGET_DEFAULT_(?P<style>[A-Z_]+)\s*\((?P<default_arg>.*)\)"
  47. # Match the arguments and trailing attribute of a method definition.
  48. # Note we don't match the trailing ";".
  49. METHOD_TRAILER = r"\s*" + TARGET_DEFAULT_PART + "$"
  50. # Match an entire method definition.
  51. METHOD = re.compile(
  52. INTRO_PART
  53. + VIRTUAL_PART
  54. + "(?P<return_type>"
  55. + RETURN_PART
  56. + ")"
  57. + NAME_PART
  58. + ARGS_PART
  59. + METHOD_TRAILER
  60. )
  61. # Regular expression used to dissect argument types.
  62. ARGTYPES = re.compile(
  63. "^("
  64. + r"(?P<E>enum\s+"
  65. + SYMBOL
  66. + r"\s*)("
  67. + SYMBOL
  68. + ")?"
  69. + r"|(?P<T>.*(enum\s+)?"
  70. + SYMBOL
  71. + r".*(\s|\*|&))"
  72. + SYMBOL
  73. + ")$"
  74. )
  75. # Match TARGET_DEBUG_PRINTER in an argument type.
  76. # This must match the whole "sub-expression" including the parens.
  77. TARGET_DEBUG_PRINTER = r"\s*TARGET_DEBUG_PRINTER\s*\((?P<arg>[^)]*)\)\s*"
  78. def scan_target_h():
  79. found_trigger = False
  80. all_the_text = ""
  81. with open("target.h", "r") as target_h:
  82. for line in target_h:
  83. line = line.strip()
  84. if not found_trigger:
  85. if TRIGGER.match(line):
  86. found_trigger = True
  87. elif "{" in line:
  88. # Skip the open brace.
  89. pass
  90. elif ENDER.match(line):
  91. break
  92. else:
  93. # Strip // comments.
  94. line = re.split("//", line)[0]
  95. all_the_text = all_the_text + " " + line
  96. if not found_trigger:
  97. raise "Could not find trigger line"
  98. # Now strip out the C comments.
  99. all_the_text = re.sub(r"/\*(.*?)\*/", "", all_the_text)
  100. # Replace sequences whitespace with a single space character.
  101. # We need the space because the method may have been split
  102. # between multiple lines, like e.g.:
  103. #
  104. # virtual std::vector<long_type_name>
  105. # my_long_method_name ()
  106. # TARGET_DEFAULT_IGNORE ();
  107. #
  108. # If we didn't preserve the space, then we'd end up with:
  109. #
  110. # virtual std::vector<long_type_name>my_long_method_name ()TARGET_DEFAULT_IGNORE ()
  111. #
  112. # ... which wouldn't later be parsed correctly.
  113. all_the_text = re.sub(r"\s+", " ", all_the_text)
  114. return all_the_text.split(";")
  115. # Parse arguments into a list.
  116. def parse_argtypes(typestr):
  117. # Remove the outer parens.
  118. typestr = re.sub(r"^\((.*)\)$", r"\1", typestr)
  119. result = []
  120. for item in re.split(r",\s*", typestr):
  121. if item == "void" or item == "":
  122. continue
  123. m = ARGTYPES.match(item)
  124. if m:
  125. if m.group("E"):
  126. onetype = m.group("E")
  127. else:
  128. onetype = m.group("T")
  129. else:
  130. onetype = item
  131. result.append(onetype.strip())
  132. return result
  133. # Write function header given name, return type, and argtypes.
  134. # Returns a list of actual argument names.
  135. def write_function_header(f, decl, name, return_type, argtypes):
  136. print(return_type, file=f, end="")
  137. if decl:
  138. if not return_type.endswith("*"):
  139. print(" ", file=f, end="")
  140. else:
  141. print("", file=f)
  142. print(name + " (", file=f, end="")
  143. argdecls = []
  144. actuals = []
  145. for i in range(len(argtypes)):
  146. val = re.sub(TARGET_DEBUG_PRINTER, "", argtypes[i])
  147. if not val.endswith("*") and not val.endswith("&"):
  148. val = val + " "
  149. vname = "arg" + str(i)
  150. val = val + vname
  151. argdecls.append(val)
  152. actuals.append(vname)
  153. print(", ".join(argdecls) + ")", file=f, end="")
  154. if decl:
  155. print(" override;", file=f)
  156. else:
  157. print("\n{", file=f)
  158. return actuals
  159. # Write out a declaration.
  160. def write_declaration(f, name, return_type, argtypes):
  161. write_function_header(f, True, name, return_type, argtypes)
  162. # Write out a delegation function.
  163. def write_delegator(f, name, return_type, argtypes):
  164. names = write_function_header(
  165. f, False, "target_ops::" + name, return_type, argtypes
  166. )
  167. print(" ", file=f, end="")
  168. if return_type != "void":
  169. print("return ", file=f, end="")
  170. print("this->beneath ()->" + name + " (", file=f, end="")
  171. print(", ".join(names), file=f, end="")
  172. print(");", file=f)
  173. print("}\n", file=f)
  174. # Write out a default function.
  175. def write_tdefault(f, content, style, name, return_type, argtypes):
  176. name = "dummy_target::" + name
  177. names = write_function_header(f, False, name, return_type, argtypes)
  178. if style == "FUNC":
  179. print(" ", file=f, end="")
  180. if return_type != "void":
  181. print("return ", file=f, end="")
  182. print(content + " (", file=f, end="")
  183. names.insert(0, "this")
  184. print(", ".join(names) + ");", file=f)
  185. elif style == "RETURN":
  186. print(" return " + content + ";", file=f)
  187. elif style == "NORETURN":
  188. print(" " + content + ";", file=f)
  189. elif style == "IGNORE":
  190. # Nothing.
  191. pass
  192. else:
  193. raise "unrecognized style: " + style
  194. print("}\n", file=f)
  195. def munge_type(typename):
  196. m = re.search(TARGET_DEBUG_PRINTER, typename)
  197. if m:
  198. return m.group("arg")
  199. typename = typename.rstrip()
  200. typename = re.sub("[ ()<>:]", "_", typename)
  201. typename = re.sub("[*]", "p", typename)
  202. typename = re.sub("&", "r", typename)
  203. # Identifers with double underscores are reserved to the C++
  204. # implementation.
  205. typename = re.sub("_+", "_", typename)
  206. # Avoid ending the function name with underscore, for
  207. # cosmetics. Trailing underscores appear after munging types
  208. # with template parameters, like e.g. "foo<int>".
  209. typename = re.sub("_+$", "", typename)
  210. return "target_debug_print_" + typename
  211. # Write out a debug method.
  212. def write_debugmethod(f, content, name, return_type, argtypes):
  213. debugname = "debug_target::" + name
  214. names = write_function_header(f, False, debugname, return_type, argtypes)
  215. if return_type != "void":
  216. print(" " + return_type + " result;", file=f)
  217. print(
  218. ' gdb_printf (gdb_stdlog, "-> %s->'
  219. + name
  220. + ' (...)\\n", this->beneath ()->shortname ());',
  221. file=f,
  222. )
  223. # Delegate to the beneath target.
  224. print(" ", file=f, end="")
  225. if return_type != "void":
  226. print("result = ", file=f, end="")
  227. print("this->beneath ()->" + name + " (", file=f, end="")
  228. print(", ".join(names), file=f, end="")
  229. print(");", file=f)
  230. # Now print the arguments.
  231. print(
  232. ' gdb_printf (gdb_stdlog, "<- %s->'
  233. + name
  234. + ' (", this->beneath ()->shortname ());',
  235. file=f,
  236. )
  237. for i in range(len(argtypes)):
  238. if i > 0:
  239. print(' gdb_puts (", ", gdb_stdlog);', file=f)
  240. printer = munge_type(argtypes[i])
  241. print(" " + printer + " (" + names[i] + ");", file=f)
  242. if return_type != "void":
  243. print(' gdb_puts (") = ", gdb_stdlog);', file=f)
  244. printer = munge_type(return_type)
  245. print(" " + printer + " (result);", file=f)
  246. print(' gdb_puts ("\\n", gdb_stdlog);', file=f)
  247. else:
  248. print(' gdb_puts (")\\n", gdb_stdlog);', file=f)
  249. if return_type != "void":
  250. print(" return result;", file=f)
  251. print("}\n", file=f)
  252. def print_class(f, class_name, delegators, entries):
  253. print("struct " + class_name + " : public target_ops", file=f)
  254. print("{", file=f)
  255. print(" const target_info &info () const override;", file=f)
  256. print("", file=f)
  257. print(" strata stratum () const override;", file=f)
  258. print("", file=f)
  259. for name in delegators:
  260. return_type = entries[name]["return_type"]
  261. argtypes = entries[name]["argtypes"]
  262. print(" ", file=f, end="")
  263. write_declaration(f, name, return_type, argtypes)
  264. print("};\n", file=f)
  265. delegators = []
  266. entries = {}
  267. for current_line in scan_target_h():
  268. # See comments in scan_target_h. Here we strip away the leading
  269. # and trailing whitespace.
  270. current_line = current_line.strip()
  271. m = METHOD.match(current_line)
  272. if not m:
  273. continue
  274. data = m.groupdict()
  275. data["argtypes"] = parse_argtypes(data["args"])
  276. data["return_type"] = data["return_type"].strip()
  277. entries[data["name"]] = data
  278. delegators.append(data["name"])
  279. with open("target-delegates.c", "w") as f:
  280. print(
  281. gdbcopyright.copyright(
  282. "make-target-delegates.py", "Boilerplate target methods for GDB"
  283. ),
  284. file=f,
  285. )
  286. print_class(f, "dummy_target", delegators, entries)
  287. print_class(f, "debug_target", delegators, entries)
  288. for name in delegators:
  289. tdefault = entries[name]["default_arg"]
  290. return_type = entries[name]["return_type"]
  291. style = entries[name]["style"]
  292. argtypes = entries[name]["argtypes"]
  293. write_delegator(f, name, return_type, argtypes)
  294. write_tdefault(f, tdefault, style, name, return_type, argtypes)
  295. write_debugmethod(f, tdefault, name, return_type, argtypes)