gentpl.py 34 KB

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