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