gentpl.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. #! /usr/bin/python
  2. # GRUB -- GRand Unified Bootloader
  3. # Copyright (C) 2010,2011,2012,2013 Free Software Foundation, Inc.
  4. #
  5. # GRUB is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # GRUB is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  17. from __future__ import print_function
  18. __metaclass__ = type
  19. from optparse import OptionParser
  20. import re
  21. #
  22. # This is the python script used to generate Makefile.*.am
  23. #
  24. GRUB_PLATFORMS = [ "emu", "i386_pc", "i386_efi", "i386_qemu", "i386_coreboot",
  25. "i386_multiboot", "i386_ieee1275", "x86_64_efi",
  26. "i386_xen", "x86_64_xen", "i386_xen_pvh",
  27. "mips_loongson", "sparc64_ieee1275",
  28. "powerpc_ieee1275", "mips_arc", "ia64_efi",
  29. "mips_qemu_mips", "arm_uboot", "arm_efi", "arm64_efi",
  30. "arm_coreboot", "riscv32_efi", "riscv64_efi" ]
  31. GROUPS = {}
  32. GROUPS["common"] = GRUB_PLATFORMS[:]
  33. # Groups based on CPU
  34. GROUPS["i386"] = [ "i386_pc", "i386_efi", "i386_qemu", "i386_coreboot", "i386_multiboot", "i386_ieee1275" ]
  35. GROUPS["x86_64"] = [ "x86_64_efi" ]
  36. GROUPS["x86"] = GROUPS["i386"] + GROUPS["x86_64"]
  37. GROUPS["mips"] = [ "mips_loongson", "mips_qemu_mips", "mips_arc" ]
  38. GROUPS["sparc64"] = [ "sparc64_ieee1275" ]
  39. GROUPS["powerpc"] = [ "powerpc_ieee1275" ]
  40. GROUPS["arm"] = [ "arm_uboot", "arm_efi", "arm_coreboot" ]
  41. GROUPS["arm64"] = [ "arm64_efi" ]
  42. GROUPS["riscv32"] = [ "riscv32_efi" ]
  43. GROUPS["riscv64"] = [ "riscv64_efi" ]
  44. # Groups based on firmware
  45. GROUPS["efi"] = [ "i386_efi", "x86_64_efi", "ia64_efi", "arm_efi", "arm64_efi",
  46. "riscv32_efi", "riscv64_efi" ]
  47. GROUPS["ieee1275"] = [ "i386_ieee1275", "sparc64_ieee1275", "powerpc_ieee1275" ]
  48. GROUPS["uboot"] = [ "arm_uboot" ]
  49. GROUPS["xen"] = [ "i386_xen", "x86_64_xen" ]
  50. GROUPS["coreboot"] = [ "i386_coreboot", "arm_coreboot" ]
  51. # emu is a special case so many core functionality isn't needed on this platform
  52. GROUPS["noemu"] = GRUB_PLATFORMS[:]; GROUPS["noemu"].remove("emu")
  53. # Groups based on hardware features
  54. GROUPS["cmos"] = GROUPS["x86"][:] + ["mips_loongson", "mips_qemu_mips",
  55. "sparc64_ieee1275", "powerpc_ieee1275"]
  56. GROUPS["cmos"].remove("i386_efi"); GROUPS["cmos"].remove("x86_64_efi");
  57. GROUPS["pci"] = GROUPS["x86"] + ["mips_loongson"]
  58. GROUPS["usb"] = GROUPS["pci"] + ["arm_coreboot"]
  59. # If gfxterm is main output console integrate it into kernel
  60. GROUPS["videoinkernel"] = ["mips_loongson", "i386_coreboot", "arm_coreboot" ]
  61. GROUPS["videomodules"] = GRUB_PLATFORMS[:];
  62. for i in GROUPS["videoinkernel"]: GROUPS["videomodules"].remove(i)
  63. # Similar for terminfo
  64. GROUPS["terminfoinkernel"] = [ "emu", "mips_loongson", "mips_arc", "mips_qemu_mips", "i386_xen_pvh" ] + GROUPS["xen"] + GROUPS["ieee1275"] + GROUPS["uboot"];
  65. GROUPS["terminfomodule"] = GRUB_PLATFORMS[:];
  66. for i in GROUPS["terminfoinkernel"]: GROUPS["terminfomodule"].remove(i)
  67. # Flattened Device Trees (FDT)
  68. GROUPS["fdt"] = [ "arm64_efi", "arm_uboot", "arm_efi", "riscv32_efi", "riscv64_efi" ]
  69. # Needs software helpers for division
  70. # Must match GRUB_DIVISION_IN_SOFTWARE in misc.h
  71. GROUPS["softdiv"] = GROUPS["arm"] + ["ia64_efi"] + GROUPS["riscv32"]
  72. GROUPS["no_softdiv"] = GRUB_PLATFORMS[:]
  73. for i in GROUPS["softdiv"]: GROUPS["no_softdiv"].remove(i)
  74. # Miscellaneous groups scheduled to disappear in future
  75. GROUPS["i386_coreboot_multiboot_qemu"] = ["i386_coreboot", "i386_multiboot", "i386_qemu"]
  76. GROUPS["nopc"] = GRUB_PLATFORMS[:]; GROUPS["nopc"].remove("i386_pc")
  77. #
  78. # Create platform => groups reverse map, where groups covering that
  79. # platform are ordered by their sizes
  80. #
  81. RMAP = {}
  82. for platform in GRUB_PLATFORMS:
  83. # initialize with platform itself as a group
  84. RMAP[platform] = [ platform ]
  85. for k in GROUPS.keys():
  86. v = GROUPS[k]
  87. # skip groups that don't cover this platform
  88. if platform not in v: continue
  89. bigger = []
  90. smaller = []
  91. # partition currently known groups based on their size
  92. for group in RMAP[platform]:
  93. if group in GRUB_PLATFORMS: smaller.append(group)
  94. elif len(GROUPS[group]) < len(v): smaller.append(group)
  95. else: bigger.append(group)
  96. # insert in the middle
  97. RMAP[platform] = smaller + [ k ] + bigger
  98. #
  99. # Input
  100. #
  101. # We support a subset of the AutoGen definitions file syntax. Specifically,
  102. # compound names are disallowed; some preprocessing directives are
  103. # disallowed (though #if/#endif are allowed; note that, like AutoGen, #if
  104. # skips everything to the next #endif regardless of the value of the
  105. # conditional); and shell-generated strings, Scheme-generated strings, and
  106. # here strings are disallowed.
  107. class AutogenToken:
  108. (autogen, definitions, eof, var_name, other_name, string, number,
  109. semicolon, equals, comma, lbrace, rbrace, lbracket, rbracket) = range(14)
  110. class AutogenState:
  111. (init, need_def, need_tpl, need_semi, need_name, have_name, need_value,
  112. need_idx, need_rbracket, indx_name, have_value, done) = range(12)
  113. class AutogenParseError(Exception):
  114. def __init__(self, message, path, line):
  115. super(AutogenParseError, self).__init__(message)
  116. self.path = path
  117. self.line = line
  118. def __str__(self):
  119. return (
  120. super(AutogenParseError, self).__str__() +
  121. " at file %s line %d" % (self.path, self.line))
  122. class AutogenDefinition(list):
  123. def __getitem__(self, key):
  124. try:
  125. return super(AutogenDefinition, self).__getitem__(key)
  126. except TypeError:
  127. for name, value in self:
  128. if name == key:
  129. return value
  130. def __contains__(self, key):
  131. for name, value in self:
  132. if name == key:
  133. return True
  134. return False
  135. def get(self, key, default):
  136. for name, value in self:
  137. if name == key:
  138. return value
  139. else:
  140. return default
  141. def find_all(self, key):
  142. for name, value in self:
  143. if name == key:
  144. yield value
  145. class AutogenParser:
  146. def __init__(self):
  147. self.definitions = AutogenDefinition()
  148. self.def_stack = [("", self.definitions)]
  149. self.curdef = None
  150. self.new_name = None
  151. self.cur_path = None
  152. self.cur_line = 0
  153. @staticmethod
  154. def is_unquotable_char(c):
  155. return (ord(c) in range(ord("!"), ord("~") + 1) and
  156. c not in "#,;<=>[\\]`{}?*'\"()")
  157. @staticmethod
  158. def is_value_name_char(c):
  159. return c in ":^-_" or c.isalnum()
  160. def error(self, message):
  161. raise AutogenParseError(message, self.cur_file, self.cur_line)
  162. def read_tokens(self, f):
  163. data = f.read()
  164. end = len(data)
  165. offset = 0
  166. while offset < end:
  167. while offset < end and data[offset].isspace():
  168. if data[offset] == "\n":
  169. self.cur_line += 1
  170. offset += 1
  171. if offset >= end:
  172. break
  173. c = data[offset]
  174. if c == "#":
  175. offset += 1
  176. try:
  177. end_directive = data.index("\n", offset)
  178. directive = data[offset:end_directive]
  179. offset = end_directive
  180. except ValueError:
  181. directive = data[offset:]
  182. offset = end
  183. name, value = directive.split(None, 1)
  184. if name == "if":
  185. try:
  186. end_if = data.index("\n#endif", offset)
  187. new_offset = end_if + len("\n#endif")
  188. self.cur_line += data[offset:new_offset].count("\n")
  189. offset = new_offset
  190. except ValueError:
  191. self.error("#if without matching #endif")
  192. else:
  193. self.error("Unhandled directive '#%s'" % name)
  194. elif c == "{":
  195. yield AutogenToken.lbrace, c
  196. offset += 1
  197. elif c == "=":
  198. yield AutogenToken.equals, c
  199. offset += 1
  200. elif c == "}":
  201. yield AutogenToken.rbrace, c
  202. offset += 1
  203. elif c == "[":
  204. yield AutogenToken.lbracket, c
  205. offset += 1
  206. elif c == "]":
  207. yield AutogenToken.rbracket, c
  208. offset += 1
  209. elif c == ";":
  210. yield AutogenToken.semicolon, c
  211. offset += 1
  212. elif c == ",":
  213. yield AutogenToken.comma, c
  214. offset += 1
  215. elif c in ("'", '"'):
  216. s = []
  217. while True:
  218. offset += 1
  219. if offset >= end:
  220. self.error("EOF in quoted string")
  221. if data[offset] == "\n":
  222. self.cur_line += 1
  223. if data[offset] == "\\":
  224. offset += 1
  225. if offset >= end:
  226. self.error("EOF in quoted string")
  227. if data[offset] == "\n":
  228. self.cur_line += 1
  229. # Proper escaping unimplemented; this can be filled
  230. # out if needed.
  231. s.append("\\")
  232. s.append(data[offset])
  233. elif data[offset] == c:
  234. offset += 1
  235. break
  236. else:
  237. s.append(data[offset])
  238. yield AutogenToken.string, "".join(s)
  239. elif c == "/":
  240. offset += 1
  241. if data[offset] == "*":
  242. offset += 1
  243. try:
  244. end_comment = data.index("*/", offset)
  245. new_offset = end_comment + len("*/")
  246. self.cur_line += data[offset:new_offset].count("\n")
  247. offset = new_offset
  248. except ValueError:
  249. self.error("/* without matching */")
  250. elif data[offset] == "/":
  251. try:
  252. offset = data.index("\n", offset)
  253. except ValueError:
  254. pass
  255. elif (c.isdigit() or
  256. (c == "-" and offset < end - 1 and
  257. data[offset + 1].isdigit())):
  258. end_number = offset + 1
  259. while end_number < end and data[end_number].isdigit():
  260. end_number += 1
  261. yield AutogenToken.number, data[offset:end_number]
  262. offset = end_number
  263. elif self.is_unquotable_char(c):
  264. end_name = offset
  265. while (end_name < end and
  266. self.is_value_name_char(data[end_name])):
  267. end_name += 1
  268. if end_name < end and self.is_unquotable_char(data[end_name]):
  269. while (end_name < end and
  270. self.is_unquotable_char(data[end_name])):
  271. end_name += 1
  272. yield AutogenToken.other_name, data[offset:end_name]
  273. offset = end_name
  274. else:
  275. s = data[offset:end_name]
  276. if s.lower() == "autogen":
  277. yield AutogenToken.autogen, s
  278. elif s.lower() == "definitions":
  279. yield AutogenToken.definitions, s
  280. else:
  281. yield AutogenToken.var_name, s
  282. offset = end_name
  283. else:
  284. self.error("Invalid input character '%s'" % c)
  285. yield AutogenToken.eof, None
  286. def do_need_name_end(self, token):
  287. if len(self.def_stack) > 1:
  288. self.error("Definition blocks were left open")
  289. def do_need_name_var_name(self, token):
  290. self.new_name = token
  291. def do_end_block(self, token):
  292. if len(self.def_stack) <= 1:
  293. self.error("Too many close braces")
  294. new_name, parent_def = self.def_stack.pop()
  295. parent_def.append((new_name, self.curdef))
  296. self.curdef = parent_def
  297. def do_empty_val(self, token):
  298. self.curdef.append((self.new_name, ""))
  299. def do_str_value(self, token):
  300. self.curdef.append((self.new_name, token))
  301. def do_start_block(self, token):
  302. self.def_stack.append((self.new_name, self.curdef))
  303. self.curdef = AutogenDefinition()
  304. def do_indexed_name(self, token):
  305. self.new_name = token
  306. def read_definitions_file(self, f):
  307. self.curdef = self.definitions
  308. self.cur_line = 0
  309. state = AutogenState.init
  310. # The following transition table was reduced from the Autogen
  311. # documentation:
  312. # info -f autogen -n 'Full Syntax'
  313. transitions = {
  314. AutogenState.init: {
  315. AutogenToken.autogen: (AutogenState.need_def, None),
  316. },
  317. AutogenState.need_def: {
  318. AutogenToken.definitions: (AutogenState.need_tpl, None),
  319. },
  320. AutogenState.need_tpl: {
  321. AutogenToken.var_name: (AutogenState.need_semi, None),
  322. AutogenToken.other_name: (AutogenState.need_semi, None),
  323. AutogenToken.string: (AutogenState.need_semi, None),
  324. },
  325. AutogenState.need_semi: {
  326. AutogenToken.semicolon: (AutogenState.need_name, None),
  327. },
  328. AutogenState.need_name: {
  329. AutogenToken.autogen: (AutogenState.need_def, None),
  330. AutogenToken.eof: (AutogenState.done, self.do_need_name_end),
  331. AutogenToken.var_name: (
  332. AutogenState.have_name, self.do_need_name_var_name),
  333. AutogenToken.rbrace: (
  334. AutogenState.have_value, self.do_end_block),
  335. },
  336. AutogenState.have_name: {
  337. AutogenToken.semicolon: (
  338. AutogenState.need_name, self.do_empty_val),
  339. AutogenToken.equals: (AutogenState.need_value, None),
  340. AutogenToken.lbracket: (AutogenState.need_idx, None),
  341. },
  342. AutogenState.need_value: {
  343. AutogenToken.var_name: (
  344. AutogenState.have_value, self.do_str_value),
  345. AutogenToken.other_name: (
  346. AutogenState.have_value, self.do_str_value),
  347. AutogenToken.string: (
  348. AutogenState.have_value, self.do_str_value),
  349. AutogenToken.number: (
  350. AutogenState.have_value, self.do_str_value),
  351. AutogenToken.lbrace: (
  352. AutogenState.need_name, self.do_start_block),
  353. },
  354. AutogenState.need_idx: {
  355. AutogenToken.var_name: (
  356. AutogenState.need_rbracket, self.do_indexed_name),
  357. AutogenToken.number: (
  358. AutogenState.need_rbracket, self.do_indexed_name),
  359. },
  360. AutogenState.need_rbracket: {
  361. AutogenToken.rbracket: (AutogenState.indx_name, None),
  362. },
  363. AutogenState.indx_name: {
  364. AutogenToken.semicolon: (
  365. AutogenState.need_name, self.do_empty_val),
  366. AutogenToken.equals: (AutogenState.need_value, None),
  367. },
  368. AutogenState.have_value: {
  369. AutogenToken.semicolon: (AutogenState.need_name, None),
  370. AutogenToken.comma: (AutogenState.need_value, None),
  371. },
  372. }
  373. for code, token in self.read_tokens(f):
  374. if code in transitions[state]:
  375. state, handler = transitions[state][code]
  376. if handler is not None:
  377. handler(token)
  378. else:
  379. self.error(
  380. "Parse error in state %s: unexpected token '%s'" % (
  381. state, token))
  382. if state == AutogenState.done:
  383. break
  384. def read_definitions(self, path):
  385. self.cur_file = path
  386. with open(path) as f:
  387. self.read_definitions_file(f)
  388. defparser = AutogenParser()
  389. #
  390. # Output
  391. #
  392. outputs = {}
  393. def output(s, section=''):
  394. if s == "":
  395. return
  396. outputs.setdefault(section, [])
  397. outputs[section].append(s)
  398. def write_output(section=''):
  399. for s in outputs.get(section, []):
  400. print(s, end='')
  401. #
  402. # Global variables
  403. #
  404. def gvar_add(var, value):
  405. output(var + " += " + value + "\n")
  406. #
  407. # Per PROGRAM/SCRIPT variables
  408. #
  409. seen_vars = set()
  410. def vars_init(defn, *var_list):
  411. name = defn['name']
  412. if name not in seen_target and name not in seen_vars:
  413. for var in var_list:
  414. output(var + " = \n", section='decl')
  415. seen_vars.add(name)
  416. def var_set(var, value):
  417. output(var + " = " + value + "\n")
  418. def var_add(var, value):
  419. output(var + " += " + value + "\n")
  420. #
  421. # Variable names and rules
  422. #
  423. canonical_name_re = re.compile(r'[^0-9A-Za-z@_]')
  424. canonical_name_suffix = ""
  425. def set_canonical_name_suffix(suffix):
  426. global canonical_name_suffix
  427. canonical_name_suffix = suffix
  428. def cname(defn):
  429. return canonical_name_re.sub('_', defn['name'] + canonical_name_suffix)
  430. def rule(target, source, cmd):
  431. if cmd[0] == "\n":
  432. output("\n" + target + ": " + source + cmd.replace("\n", "\n\t") + "\n")
  433. else:
  434. output("\n" + target + ": " + source + "\n\t" + cmd.replace("\n", "\n\t") + "\n")
  435. #
  436. # Handle keys with platform names as values, for example:
  437. #
  438. # kernel = {
  439. # nostrip = emu;
  440. # ...
  441. # }
  442. #
  443. def platform_tagged(defn, platform, tag):
  444. for value in defn.find_all(tag):
  445. for group in RMAP[platform]:
  446. if value == group:
  447. return True
  448. return False
  449. def if_platform_tagged(defn, platform, tag, snippet_if, snippet_else=None):
  450. if platform_tagged(defn, platform, tag):
  451. return snippet_if
  452. elif snippet_else is not None:
  453. return snippet_else
  454. #
  455. # Handle tagged values
  456. #
  457. # module = {
  458. # extra_dist = ...
  459. # extra_dist = ...
  460. # ...
  461. # };
  462. #
  463. def foreach_value(defn, tag, closure):
  464. r = []
  465. for value in defn.find_all(tag):
  466. r.append(closure(value))
  467. return ''.join(r)
  468. #
  469. # Handle best matched values for a platform, for example:
  470. #
  471. # module = {
  472. # cflags = '-Wall';
  473. # emu_cflags = '-Wall -DGRUB_EMU=1';
  474. # ...
  475. # }
  476. #
  477. def foreach_platform_specific_value(defn, platform, suffix, nonetag, closure):
  478. r = []
  479. for group in RMAP[platform]:
  480. values = list(defn.find_all(group + suffix))
  481. if values:
  482. for value in values:
  483. r.append(closure(value))
  484. break
  485. else:
  486. for value in defn.find_all(nonetag):
  487. r.append(closure(value))
  488. return ''.join(r)
  489. #
  490. # Handle values from sum of all groups for a platform, for example:
  491. #
  492. # module = {
  493. # common = kern/misc.c;
  494. # emu = kern/emu/misc.c;
  495. # ...
  496. # }
  497. #
  498. def foreach_platform_value(defn, platform, suffix, closure):
  499. r = []
  500. for group in RMAP[platform]:
  501. for value in defn.find_all(group + suffix):
  502. r.append(closure(value))
  503. return ''.join(r)
  504. def platform_conditional(platform, closure):
  505. output("\nif COND_" + platform + "\n")
  506. closure(platform)
  507. output("endif\n")
  508. #
  509. # Handle guarding with platform-specific "enable" keys, for example:
  510. #
  511. # module = {
  512. # name = pci;
  513. # noemu = bus/pci.c;
  514. # emu = bus/emu/pci.c;
  515. # emu = commands/lspci.c;
  516. #
  517. # enable = emu;
  518. # enable = i386_pc;
  519. # enable = x86_efi;
  520. # enable = i386_ieee1275;
  521. # enable = i386_coreboot;
  522. # };
  523. #
  524. def foreach_enabled_platform(defn, closure):
  525. if 'enable' in defn:
  526. for platform in GRUB_PLATFORMS:
  527. if platform_tagged(defn, platform, "enable"):
  528. platform_conditional(platform, closure)
  529. else:
  530. for platform in GRUB_PLATFORMS:
  531. platform_conditional(platform, closure)
  532. #
  533. # Handle guarding with platform-specific automake conditionals, for example:
  534. #
  535. # module = {
  536. # name = usb;
  537. # common = bus/usb/usb.c;
  538. # noemu = bus/usb/usbtrans.c;
  539. # noemu = bus/usb/usbhub.c;
  540. # enable = emu;
  541. # enable = i386;
  542. # enable = mips_loongson;
  543. # emu_condition = COND_GRUB_EMU_SDL;
  544. # };
  545. #
  546. def under_platform_specific_conditionals(defn, platform, closure):
  547. output(foreach_platform_specific_value(defn, platform, "_condition", "condition", lambda cond: "if " + cond + "\n"))
  548. closure(defn, platform)
  549. output(foreach_platform_specific_value(defn, platform, "_condition", "condition", lambda cond: "endif " + cond + "\n"))
  550. def platform_specific_values(defn, platform, suffix, nonetag):
  551. return foreach_platform_specific_value(defn, platform, suffix, nonetag,
  552. lambda value: value + " ")
  553. def platform_values(defn, platform, suffix):
  554. return foreach_platform_value(defn, platform, suffix, lambda value: value + " ")
  555. def extra_dist(defn):
  556. return foreach_value(defn, "extra_dist", lambda value: value + " ")
  557. def platform_sources(defn, p): return platform_values(defn, p, "")
  558. def platform_nodist_sources(defn, p): return platform_values(defn, p, "_nodist")
  559. def platform_startup(defn, p): return platform_specific_values(defn, p, "_startup", "startup")
  560. def platform_ldadd(defn, p): return platform_specific_values(defn, p, "_ldadd", "ldadd")
  561. def platform_dependencies(defn, p): return platform_specific_values(defn, p, "_dependencies", "dependencies")
  562. def platform_cflags(defn, p): return platform_specific_values(defn, p, "_cflags", "cflags")
  563. def platform_ldflags(defn, p): return platform_specific_values(defn, p, "_ldflags", "ldflags")
  564. def platform_cppflags(defn, p): return platform_specific_values(defn, p, "_cppflags", "cppflags")
  565. def platform_ccasflags(defn, p): return platform_specific_values(defn, p, "_ccasflags", "ccasflags")
  566. def platform_stripflags(defn, p): return platform_specific_values(defn, p, "_stripflags", "stripflags")
  567. def platform_objcopyflags(defn, p): return platform_specific_values(defn, p, "_objcopyflags", "objcopyflags")
  568. #
  569. # Emit snippet only the first time through for the current name.
  570. #
  571. seen_target = set()
  572. def first_time(defn, snippet):
  573. if defn['name'] not in seen_target:
  574. return snippet
  575. return ''
  576. def is_platform_independent(defn):
  577. if 'enable' in defn:
  578. return False
  579. for suffix in [ "", "_nodist" ]:
  580. template = platform_values(defn, GRUB_PLATFORMS[0], suffix)
  581. for platform in GRUB_PLATFORMS[1:]:
  582. if template != platform_values(defn, platform, suffix):
  583. return False
  584. for suffix in [ "startup", "ldadd", "dependencies", "cflags", "ldflags", "cppflags", "ccasflags", "stripflags", "objcopyflags", "condition" ]:
  585. template = platform_specific_values(defn, GRUB_PLATFORMS[0], "_" + suffix, suffix)
  586. for platform in GRUB_PLATFORMS[1:]:
  587. if template != platform_specific_values(defn, platform, "_" + suffix, suffix):
  588. return False
  589. for tag in [ "nostrip" ]:
  590. template = platform_tagged(defn, GRUB_PLATFORMS[0], tag)
  591. for platform in GRUB_PLATFORMS[1:]:
  592. if template != platform_tagged(defn, platform, tag):
  593. return False
  594. return True
  595. def module(defn, platform):
  596. name = defn['name']
  597. set_canonical_name_suffix(".module")
  598. gvar_add("platform_PROGRAMS", name + ".module")
  599. gvar_add("MODULE_FILES", name + ".module$(EXEEXT)")
  600. var_set(cname(defn) + "_SOURCES", platform_sources(defn, platform) + " ## platform sources")
  601. var_set("nodist_" + cname(defn) + "_SOURCES", platform_nodist_sources(defn, platform) + " ## platform nodist sources")
  602. var_set(cname(defn) + "_LDADD", platform_ldadd(defn, platform))
  603. var_set(cname(defn) + "_CFLAGS", "$(AM_CFLAGS) $(CFLAGS_MODULE) " + platform_cflags(defn, platform))
  604. var_set(cname(defn) + "_LDFLAGS", "$(AM_LDFLAGS) $(LDFLAGS_MODULE) " + platform_ldflags(defn, platform))
  605. var_set(cname(defn) + "_CPPFLAGS", "$(AM_CPPFLAGS) $(CPPFLAGS_MODULE) " + platform_cppflags(defn, platform))
  606. var_set(cname(defn) + "_CCASFLAGS", "$(AM_CCASFLAGS) $(CCASFLAGS_MODULE) " + platform_ccasflags(defn, platform))
  607. var_set(cname(defn) + "_DEPENDENCIES", "$(TARGET_OBJ2ELF) " + platform_dependencies(defn, platform))
  608. gvar_add("dist_noinst_DATA", extra_dist(defn))
  609. gvar_add("BUILT_SOURCES", "$(nodist_" + cname(defn) + "_SOURCES)")
  610. gvar_add("CLEANFILES", "$(nodist_" + cname(defn) + "_SOURCES)")
  611. gvar_add("MOD_FILES", name + ".mod")
  612. gvar_add("MARKER_FILES", name + ".marker")
  613. gvar_add("CLEANFILES", name + ".marker")
  614. output("""
  615. """ + name + """.marker: $(""" + cname(defn) + """_SOURCES) $(nodist_""" + cname(defn) + """_SOURCES)
  616. $(TARGET_CPP) -DGRUB_LST_GENERATOR $(CPPFLAGS_MARKER) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(""" + cname(defn) + """_CPPFLAGS) $(CPPFLAGS) $^ > $@.new || (rm -f $@; exit 1)
  617. grep 'MARKER' $@.new > $@; rm -f $@.new
  618. """)
  619. def kernel(defn, platform):
  620. name = defn['name']
  621. set_canonical_name_suffix(".exec")
  622. gvar_add("platform_PROGRAMS", name + ".exec")
  623. var_set(cname(defn) + "_SOURCES", platform_startup(defn, platform))
  624. var_add(cname(defn) + "_SOURCES", platform_sources(defn, platform))
  625. var_set("nodist_" + cname(defn) + "_SOURCES", platform_nodist_sources(defn, platform) + " ## platform nodist sources")
  626. var_set(cname(defn) + "_LDADD", platform_ldadd(defn, platform))
  627. var_set(cname(defn) + "_CFLAGS", "$(AM_CFLAGS) $(CFLAGS_KERNEL) " + platform_cflags(defn, platform))
  628. var_set(cname(defn) + "_LDFLAGS", "$(AM_LDFLAGS) $(LDFLAGS_KERNEL) " + platform_ldflags(defn, platform))
  629. var_set(cname(defn) + "_CPPFLAGS", "$(AM_CPPFLAGS) $(CPPFLAGS_KERNEL) " + platform_cppflags(defn, platform))
  630. var_set(cname(defn) + "_CCASFLAGS", "$(AM_CCASFLAGS) $(CCASFLAGS_KERNEL) " + platform_ccasflags(defn, platform))
  631. var_set(cname(defn) + "_STRIPFLAGS", "$(AM_STRIPFLAGS) $(STRIPFLAGS_KERNEL) " + platform_stripflags(defn, platform))
  632. var_set(cname(defn) + "_DEPENDENCIES", "$(TARGET_OBJ2ELF)")
  633. gvar_add("dist_noinst_DATA", extra_dist(defn))
  634. gvar_add("BUILT_SOURCES", "$(nodist_" + cname(defn) + "_SOURCES)")
  635. gvar_add("CLEANFILES", "$(nodist_" + cname(defn) + "_SOURCES)")
  636. gvar_add("platform_DATA", name + ".img")
  637. gvar_add("CLEANFILES", name + ".img")
  638. rule(name + ".img", name + ".exec$(EXEEXT)",
  639. if_platform_tagged(defn, platform, "nostrip",
  640. """if test x$(TARGET_APPLE_LINKER) = x1; then \
  641. $(TARGET_OBJCONV) -f$(TARGET_MODULE_FORMAT) -nr:_grub_mod_init:grub_mod_init -nr:_grub_mod_fini:grub_mod_fini -ed2022 -wd1106 -nu -nd $< $@; \
  642. elif test ! -z '$(TARGET_OBJ2ELF)'; then \
  643. $(TARGET_OBJ2ELF) $< $@ || (rm -f $@; exit 1); \
  644. else cp $< $@; fi""",
  645. """if test x$(TARGET_APPLE_LINKER) = x1; then \
  646. $(TARGET_STRIP) -S -x $(""" + cname(defn) + """) -o $@.bin $<; \
  647. $(TARGET_OBJCONV) -f$(TARGET_MODULE_FORMAT) -nr:_grub_mod_init:grub_mod_init -nr:_grub_mod_fini:grub_mod_fini -ed2022 -ed2016 -wd1106 -nu -nd $@.bin $@; \
  648. rm -f $@.bin; \
  649. elif test ! -z '$(TARGET_OBJ2ELF)'; then \
  650. """ + "$(TARGET_STRIP) $(" + cname(defn) + "_STRIPFLAGS) -o $@.bin $< && \
  651. $(TARGET_OBJ2ELF) $@.bin $@ || (rm -f $@; rm -f $@.bin; exit 1); \
  652. rm -f $@.bin; \
  653. else """ + "$(TARGET_STRIP) $(" + cname(defn) + "_STRIPFLAGS) -o $@ $<; \
  654. fi"""))
  655. def image(defn, platform):
  656. name = defn['name']
  657. set_canonical_name_suffix(".image")
  658. gvar_add("platform_PROGRAMS", name + ".image")
  659. var_set(cname(defn) + "_SOURCES", platform_sources(defn, platform))
  660. var_set("nodist_" + cname(defn) + "_SOURCES", platform_nodist_sources(defn, platform) + "## platform nodist sources")
  661. var_set(cname(defn) + "_LDADD", platform_ldadd(defn, platform))
  662. var_set(cname(defn) + "_CFLAGS", "$(AM_CFLAGS) $(CFLAGS_IMAGE) " + platform_cflags(defn, platform))
  663. var_set(cname(defn) + "_LDFLAGS", "$(AM_LDFLAGS) $(LDFLAGS_IMAGE) " + platform_ldflags(defn, platform))
  664. var_set(cname(defn) + "_CPPFLAGS", "$(AM_CPPFLAGS) $(CPPFLAGS_IMAGE) " + platform_cppflags(defn, platform))
  665. var_set(cname(defn) + "_CCASFLAGS", "$(AM_CCASFLAGS) $(CCASFLAGS_IMAGE) " + platform_ccasflags(defn, platform))
  666. var_set(cname(defn) + "_OBJCOPYFLAGS", "$(OBJCOPYFLAGS_IMAGE) " + platform_objcopyflags(defn, platform))
  667. # var_set(cname(defn) + "_DEPENDENCIES", platform_dependencies(defn, platform) + " " + platform_ldadd(defn, platform))
  668. gvar_add("dist_noinst_DATA", extra_dist(defn))
  669. gvar_add("BUILT_SOURCES", "$(nodist_" + cname(defn) + "_SOURCES)")
  670. gvar_add("CLEANFILES", "$(nodist_" + cname(defn) + "_SOURCES)")
  671. gvar_add("platform_DATA", name + ".img")
  672. gvar_add("CLEANFILES", name + ".img")
  673. rule(name + ".img", name + ".image$(EXEEXT)", """
  674. if test x$(TARGET_APPLE_LINKER) = x1; then \
  675. $(MACHO2IMG) $< $@; \
  676. else \
  677. $(TARGET_OBJCOPY) $(""" + cname(defn) + """_OBJCOPYFLAGS) --strip-unneeded -R .note -R .comment -R .note.gnu.build-id -R .MIPS.abiflags -R .reginfo -R .rel.dyn -R .note.gnu.gold-version -R .ARM.exidx $< $@; \
  678. fi
  679. """)
  680. def library(defn, platform):
  681. name = defn['name']
  682. set_canonical_name_suffix("")
  683. vars_init(defn,
  684. cname(defn) + "_SOURCES",
  685. "nodist_" + cname(defn) + "_SOURCES",
  686. cname(defn) + "_CFLAGS",
  687. cname(defn) + "_CPPFLAGS",
  688. cname(defn) + "_CCASFLAGS")
  689. # cname(defn) + "_DEPENDENCIES")
  690. if name not in seen_target:
  691. gvar_add("noinst_LIBRARIES", name)
  692. var_add(cname(defn) + "_SOURCES", platform_sources(defn, platform))
  693. var_add("nodist_" + cname(defn) + "_SOURCES", platform_nodist_sources(defn, platform))
  694. var_add(cname(defn) + "_CFLAGS", first_time(defn, "$(AM_CFLAGS) $(CFLAGS_LIBRARY) ") + platform_cflags(defn, platform))
  695. var_add(cname(defn) + "_CPPFLAGS", first_time(defn, "$(AM_CPPFLAGS) $(CPPFLAGS_LIBRARY) ") + platform_cppflags(defn, platform))
  696. var_add(cname(defn) + "_CCASFLAGS", first_time(defn, "$(AM_CCASFLAGS) $(CCASFLAGS_LIBRARY) ") + platform_ccasflags(defn, platform))
  697. # var_add(cname(defn) + "_DEPENDENCIES", platform_dependencies(defn, platform) + " " + platform_ldadd(defn, platform))
  698. gvar_add("dist_noinst_DATA", extra_dist(defn))
  699. if name not in seen_target:
  700. gvar_add("BUILT_SOURCES", "$(nodist_" + cname(defn) + "_SOURCES)")
  701. gvar_add("CLEANFILES", "$(nodist_" + cname(defn) + "_SOURCES)")
  702. def installdir(defn, default="bin"):
  703. return defn.get('installdir', default)
  704. def manpage(defn, adddeps):
  705. name = defn['name']
  706. mansection = defn['mansection']
  707. output("if COND_MAN_PAGES\n")
  708. gvar_add("man_MANS", name + "." + mansection)
  709. rule(name + "." + mansection, name + " " + adddeps, """
  710. chmod a+x """ + name + """
  711. PATH=$(builddir):$$PATH pkgdatadir=$(builddir) $(HELP2MAN) --section=""" + mansection + """ -i $(top_srcdir)/docs/man/""" + name + """.h2m -o $@ """ + name + """
  712. """)
  713. gvar_add("CLEANFILES", name + "." + mansection)
  714. output("endif\n")
  715. def program(defn, platform, test=False):
  716. name = defn['name']
  717. set_canonical_name_suffix("")
  718. if 'testcase' in defn:
  719. gvar_add("check_PROGRAMS", name)
  720. gvar_add("TESTS", name)
  721. else:
  722. var_add(installdir(defn) + "_PROGRAMS", name)
  723. if 'mansection' in defn:
  724. manpage(defn, "")
  725. var_set(cname(defn) + "_SOURCES", platform_sources(defn, platform))
  726. var_set("nodist_" + cname(defn) + "_SOURCES", platform_nodist_sources(defn, platform))
  727. var_set(cname(defn) + "_LDADD", platform_ldadd(defn, platform))
  728. var_set(cname(defn) + "_CFLAGS", "$(AM_CFLAGS) $(CFLAGS_PROGRAM) " + platform_cflags(defn, platform))
  729. var_set(cname(defn) + "_LDFLAGS", "$(AM_LDFLAGS) $(LDFLAGS_PROGRAM) " + platform_ldflags(defn, platform))
  730. var_set(cname(defn) + "_CPPFLAGS", "$(AM_CPPFLAGS) $(CPPFLAGS_PROGRAM) " + platform_cppflags(defn, platform))
  731. var_set(cname(defn) + "_CCASFLAGS", "$(AM_CCASFLAGS) $(CCASFLAGS_PROGRAM) " + platform_ccasflags(defn, platform))
  732. # var_set(cname(defn) + "_DEPENDENCIES", platform_dependencies(defn, platform) + " " + platform_ldadd(defn, platform))
  733. gvar_add("dist_noinst_DATA", extra_dist(defn))
  734. gvar_add("BUILT_SOURCES", "$(nodist_" + cname(defn) + "_SOURCES)")
  735. gvar_add("CLEANFILES", "$(nodist_" + cname(defn) + "_SOURCES)")
  736. def data(defn, platform):
  737. var_add("dist_" + installdir(defn) + "_DATA", platform_sources(defn, platform))
  738. gvar_add("dist_noinst_DATA", extra_dist(defn))
  739. def transform_data(defn, platform):
  740. name = defn['name']
  741. var_add(installdir(defn) + "_DATA", name)
  742. rule(name, "$(top_builddir)/config.status " + platform_sources(defn, platform) + platform_dependencies(defn, platform), """
  743. (for x in """ + platform_sources(defn, platform) + """; do cat $(srcdir)/"$$x"; done) | $(top_builddir)/config.status --file=$@:-
  744. chmod a+x """ + name + """
  745. """)
  746. gvar_add("CLEANFILES", name)
  747. gvar_add("EXTRA_DIST", extra_dist(defn))
  748. gvar_add("dist_noinst_DATA", platform_sources(defn, platform))
  749. def script(defn, platform):
  750. name = defn['name']
  751. if 'testcase' in defn:
  752. gvar_add("check_SCRIPTS", name)
  753. gvar_add ("TESTS", name)
  754. else:
  755. var_add(installdir(defn) + "_SCRIPTS", name)
  756. if 'mansection' in defn:
  757. manpage(defn, "grub-mkconfig_lib")
  758. rule(name, "$(top_builddir)/config.status " + platform_sources(defn, platform) + platform_dependencies(defn, platform), """
  759. (for x in """ + platform_sources(defn, platform) + """; do cat $(srcdir)/"$$x"; done) | $(top_builddir)/config.status --file=$@:-
  760. chmod a+x """ + name + """
  761. """)
  762. gvar_add("CLEANFILES", name)
  763. gvar_add("EXTRA_DIST", extra_dist(defn))
  764. gvar_add("dist_noinst_DATA", platform_sources(defn, platform))
  765. def rules(target, closure):
  766. seen_target.clear()
  767. seen_vars.clear()
  768. for defn in defparser.definitions.find_all(target):
  769. if is_platform_independent(defn):
  770. under_platform_specific_conditionals(defn, GRUB_PLATFORMS[0], closure)
  771. else:
  772. foreach_enabled_platform(
  773. defn,
  774. lambda p: under_platform_specific_conditionals(defn, p, closure))
  775. # Remember that we've seen this target.
  776. seen_target.add(defn['name'])
  777. parser = OptionParser(usage="%prog DEFINITION-FILES")
  778. _, args = parser.parse_args()
  779. for arg in args:
  780. defparser.read_definitions(arg)
  781. rules("module", module)
  782. rules("kernel", kernel)
  783. rules("image", image)
  784. rules("library", library)
  785. rules("program", program)
  786. rules("script", script)
  787. rules("data", data)
  788. rules("transform_data", transform_data)
  789. write_output(section='decl')
  790. write_output()