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