gentpl.py 34 KB

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