13 global_options_by_order = []
14 global_option_values = {}
15 global_uses_options = {}
19 alloptions = 0 # override uses at top level
21 local_path = re.compile(r'^\.')
22 include_pattern = re.compile(r'%%([^%]+)%%')
24 # the cpu type for this mainboard
27 # -----------------------------------------------------------------------------
29 # -----------------------------------------------------------------------------
32 """Used to keep track of the current part or dir"""
34 def __init__ (self, stack):
43 if (self.index < self.len):
44 s = self.stack[self.index]
45 self.index = self.index + 1
53 return len(self.stack)
55 def __getitem__ (self, i):
62 return self.__stack_iter(self.stack)
65 self.stack.append(part)
69 return self.stack.pop()
80 return (len(self.stack) == 0)
93 def __init__(self, *level):
96 def setdebug(self, *level):
99 def level(self, level):
100 return level in self.__level
102 def info(self, level, str):
103 if level in self.__level:
107 debug = debug_info(debug_info.none)
109 # -----------------------------------------------------------------------------
111 # -----------------------------------------------------------------------------
114 """Used to keep track of our current location while parsing
115 configuration files"""
117 def __init__(self, file, line, command):
120 self.command = command
121 def next_line(self, command):
122 self.line = self.line + 1
123 self.command = command
125 return "%s:%d" % (self.file, self.line)
136 s = s + '\n' + p.at()
140 return self.stack.tos().file
143 return self.stack.tos().line
146 return self.stack.tos().command
148 def push(self, file):
149 self.stack.push(self.__place(os.path.normpath(file), 0, ""))
154 def next_line(self, command):
155 self.stack.tos().next_line(command)
158 return self.stack.tos().at()
162 """Print error message"""
165 print "===> ERROR: %s" % string
169 """Print error message and exit"""
174 """Print warning message"""
176 warnings = warnings + 1
177 print "===> Warning: %s" % string
181 """Exit parser if an error has been encountered"""
185 def safe_open(file, mode):
187 return open(file, mode)
189 fatal("Could not open file \"%s\"" % file)
191 # -----------------------------------------------------------------------------
193 # -----------------------------------------------------------------------------
196 """A rom image is the ultimate goal of linuxbios"""
197 def __init__ (self, name):
198 # name of this rom image
201 # set by 'arch' directive
204 # set by 'payload' directive
207 # set by 'init' directive
210 # make rules added by 'makerule' directive
211 self.makebaserules = {}
213 # object files added by 'object' directive
214 self.objectrules = {}
216 # init object files added by 'initobject' directive
217 self.initobjectrules = {}
219 # driver files added by 'drive' directive
220 self.driverrules = {}
222 # loader scripts added by 'ldscript' directive
225 # user defines added by 'makedefine' directive
226 self.userdefines = []
228 # files to be included in crt0.S
229 self.initincludes = {}
231 # as above, but order is preserved
232 self.initincludesorder = []
234 # transitional flag to support old crtinclude format
235 self.useinitincludes = 0
237 # instance counter for parts
238 self.partinstance = 0
240 # chip config files included by the 'config' directive
241 self.configincludes = {}
246 # name of target directory specified by 'target' directive
249 # option values set in rom image
258 def setarch(self, arch):
261 def setpayload(self, payload):
262 self.payload = payload
264 def setinitfile(self, initfile):
265 self.initfile = initfile
267 def getinitfile(self):
270 def addmakerule(self, id):
271 o = getdict(self.makebaserules, id)
273 print "Warning, rule %s previously defined" % id
275 setdict(self.makebaserules, id, o)
277 def getmakerules(self):
278 return self.makebaserules
280 def getmakerule(self, id):
281 o = getdict(self.makebaserules, id)
284 fatal("No such make rule \"%s\"" % id);
286 def addmakeaction(self, id, str):
287 o = getdict(self.makebaserules, id)
292 fatal("No such rule \"%s\" for addmakeaction" % id);
294 def addmakedepend(self, id, str):
295 o = getdict(self.makebaserules, id)
300 fatal("No such rule \"%s\" for addmakedepend" % id);
302 # this is called with an an object name.
303 # the easiest thing to do is add this object to the current
305 # such kludgery. If the name starts with '.' then make the
306 # dependency be on ./thing.x gag me.
307 def addobjectdriver(self, dict, object_name):
309 suffix = object_name[-2:]
312 base = object_name[:-2]
313 type = object_name[-1:]
314 if (object_name[0] == '.'):
315 source = base + suffix
317 source = os.path.join(dirstack.tos(), base + suffix)
319 debug.info(debug.object, "add object %s source %s" % (object_name, source))
320 l = getdict(dict, base)
322 print "Warning, object/driver %s previously defined" % base
323 setdict(dict, base, [object, source, type, base])
325 def addinitobjectrule(self, name):
326 self.addobjectdriver(self.initobjectrules, name)
328 def addobjectrule(self, name):
329 self.addobjectdriver(self.objectrules, name)
331 def adddriverrule(self, name):
332 self.addobjectdriver(self.driverrules, name)
334 def getinitobjectrules(self):
335 return self.initobjectrules
337 def getinitobjectrule(self, name):
338 o = getdict(self.initobjectrules, name)
341 fatal("No such init object rule \"%s\"" % name);
343 def getobjectrules(self):
344 return self.objectrules
346 def getobjectrule(self, name):
347 o = getdict(self.objectrules, name)
350 fatal("No such object rule \"%s\"" % name);
352 def getdriverrules(self):
353 return self.driverrules
355 def getdriverrule(self, name):
356 o = getdict(self.driverrules, name)
359 fatal("No such driver rule \"%s\"" % name);
361 def addldscript(self, path):
362 self.ldscripts.append(path)
364 def getldscripts(self):
365 return self.ldscripts
367 def adduserdefine(self, str):
368 self.userdefines.append(str)
370 def getuserdefines(self):
371 return self.userdefines
373 def addinitinclude(self, str, path):
375 self.useinitincludes = 1
377 debug.info(debug.object, "ADDCRT0: %s -> %s" % (str, path))
378 o = getdict(self.initincludes, path)
380 print "Warning, init include for %s previously defined" % path
381 o = initinclude(str, path)
382 setdict(self.initincludes, path, o)
383 self.initincludesorder.append(path)
385 def getinitincludes(self):
386 return self.initincludesorder
388 def getinitinclude(self, path):
389 o = getdict(self.initincludes, path)
392 fatal("No such init include \"%s\"" % path);
394 def addconfiginclude(self, part, path):
395 setdict(self.configincludes, part, path)
397 def getconfigincludes(self):
398 return self.configincludes
400 def getincludefilename(self):
401 if (self.useinitincludes):
404 return "crt0_includes.h"
407 return self.useinitincludes
410 return self.partinstance
412 def newpartinstance(self):
413 i = self.partinstance
414 self.partinstance = self.partinstance + 1
417 def setroot(self, part):
423 def settargetdir(self, path):
424 self.targetdir = path
426 def gettargetdir(self):
427 return self.targetdir
430 """A buildrom statement"""
431 def __init__ (self, size, roms):
436 """include file for initialization code"""
437 def __init__ (self, str, path):
448 """Rule to be included in Makefile"""
449 def __init__ (self, target):
454 def addaction(self, action):
455 self.actions.append(action)
457 def adddependency(self, dependency):
458 self.dependency.append(dependency)
463 def gdependency(self):
464 return self.dependency
470 """Configuration option"""
471 def __init__ (self, name):
472 self.name = name # name of option
473 self.loc = 0 # current location
474 self.set = 0 # option has been set
475 self.used = 0 # option has been set
476 self.default = 0 # option has default value (otherwise
478 self.comment = '' # description of option
479 self.exportable = 0 # option is able to be exported
480 self.exported = 0 # option is exported
481 self.defined = 0 # option has a value
482 self.format = '%s' # option print format
484 def setvalue(self, value, values, loc):
489 setdict(values, self.name, value)
491 def getvalue(self, image, values):
493 v = getdict(values, self.name)
497 if (not (type(val) is str)):
499 if (val == '' or val[0] != '{'):
503 val = parse('delexpr', val)
505 # TODO: need to check for parse errors!
506 return option_value(val)
508 def setdefault(self, value, loc):
509 global global_option_values
511 fatal("Error: default value for %s already set" % self.name)
512 setdict(global_option_values, self.name, value)
517 def setnodefault(self, loc):
525 def setcomment(self, comment, loc):
526 if (self.comment != ''):
527 print "%s: " % self.name
528 print "Attempt to modify comment at %s" % loc
530 self.comment = comment
532 def setexportable(self):
535 def setexported(self):
539 def setnoexport(self):
543 def setformat(self, fmt):
550 if (self.exportable):
554 def isexported(self):
555 return (self.exported and self.defined)
557 # def isdefined(self):
558 # return (self.defined)
567 """Value of a configuration option"""
568 def __init__(self, value):
575 """A configuration part"""
576 def __init__ (self, image, dir, parent, part, type_name, instance_name):
577 debug.info(debug.object, "partobj dir %s parent %s part %s" \
578 % (dir, parent, part))
580 # romimage that is configuring this part
583 # links for static device tree
587 # list of init code files
590 # initializers for static device tree
591 self.registercode = {}
596 # type name of this part
597 self.type_name = type_name
599 # object files needed to build this part
602 # directory containg part files
605 # instance number, used to distinguish anonymous
606 # instances of this part
607 self.instance = image.newpartinstance()
608 debug.info(debug.object, "INSTANCE %d" % self.instance)
610 # Options used by this part
611 self.uses_options = {}
613 # Name of chip config file (0 if not needed)
616 # Flag to indicate that we have generated type
617 # definitions for this part (only want to do it once)
620 # If no instance name is supplied then generate
622 if (instance_name == 0):
623 self.instance_name = self.type_name + \
624 "_dev%d" % self.instance
625 self.config_name = "%s_config_%d" \
626 % (self.type_name, self.instance)
628 self.instance_name = instance_name
629 self.config_name = "%s_config" % self.instance_name
631 # Link this part into the tree
633 debug.info(debug.gencode, "add to parent")
635 # add current child as my sibling,
637 if (parent.children):
638 debug.info(debug.gencode, "add %s (%d) as sibling" % (parent.children.dir, parent.children.instance))
639 self.siblings = parent.children
640 parent.children = self
644 def dumpme(self, lvl):
645 """Dump information about this part for debugging"""
646 print "%d: part %s" % (lvl, self.part)
647 print "%d: instance %d" % (lvl, self.instance)
648 print "%d: dir %s" % (lvl,self.dir)
649 print "%d: name %s" % (lvl,self.name)
650 print "%d: parent %s" % (lvl,self.parent.part)
651 print "%d: parent dir %s" % (lvl,self.parent.dir)
653 print "%d: child %s" % (lvl, self.children.dir)
655 print "%d: siblings %s" % (lvl, self.siblings.dir)
656 print "%d: initcode " % lvl
657 for i in self.initcode:
659 print "%d: registercode " % lvl
660 for f, v in self.registercode.items():
661 print " %s = %s" % (f, v)
664 def gencode(self, file, pass_num):
665 """Generate static initalizer code for this part. Two passes
666 are used - the first generates type information, and the second
667 generates instance information"""
670 file.write("struct chip %s;\n" \
671 % self.instance_name)
673 file.write("struct chip static_root;\n")
675 if (self.chipconfig):
676 debug.info(debug.gencode, "gencode: chipconfig(%d)" % \
678 file.write("struct %s_config %s" % (self.type_name ,\
680 if (self.registercode):
681 file.write("\t= {\n")
682 for f, v in self.registercode.items():
683 file.write( " .%s = %s,\n" % (f, v))
689 file.write("struct chip %s = {\n" % self.instance_name)
691 file.write("struct chip static_root = {\n")
692 file.write("/* %s %s */\n" % (self.part, self.dir))
694 debug.info(debug.gencode, "gencode: siblings(%d)" \
695 % self.siblings.instance)
696 file.write(" .next = &%s,\n" \
697 % self.siblings.instance_name)
699 file.write(" .next = 0,\n")
701 debug.info(debug.gencode, "gencode: children(%d)" \
702 % self.children.instance)
703 file.write(" .children = &%s,\n" \
704 % self.children.instance_name)
706 file.write(" .children = 0,\n")
707 if (self.chipconfig):
708 # set the pointer to the structure for all this
710 file.write(" .control= &%s_control,\n" % \
712 # generate the pointer to the isntance
714 file.write(" .chip_info = (void *) &%s,\n" \
717 file.write(" .control= 0,\n")
718 file.write(" .chip_info= 0,\n")
721 def addinit(self, code):
722 """Add init file to this part"""
723 self.initcode.append(code)
725 def addconfig(self, path):
726 """Add chip config file to this part"""
727 self.chipconfig = os.path.join(self.dir, path)
728 self.image.addconfiginclude(self.type_name, self.chipconfig)
730 def addregister(self, field, value):
731 """Register static initialization information"""
732 field = dequote(field)
733 value = dequote(value)
734 setdict(self.registercode, field, value)
736 def usesoption(self, name):
737 """Declare option that can be used by this part"""
738 global global_options
739 o = getdict(global_options, name)
741 fatal("Error: can't use undefined option %s" % name)
743 o1 = getdict(self.uses_options, name)
746 setdict(self.uses_options, name, o)
748 # -----------------------------------------------------------------------------
750 # -----------------------------------------------------------------------------
752 def getdict(dict, name):
753 if name not in dict.keys():
754 debug.info(debug.dict, "Undefined: %s" % name)
756 v = dict.get(name, 0)
757 debug.info(debug.dict, "getdict %s returning %s" % (name, v))
760 def setdict(dict, name, value):
761 debug.info(debug.dict, "setdict sets %s to %s" % (name, value))
765 # to create an option, it has to not exist.
766 # When an option value is fetched, the fact that it was used is
768 # Legal things to do:
769 # set a default value, then set a real value before the option is used.
770 # set a value, try to set a default, default silently fails.
772 # use the value, then try to set the value
775 global global_options, global_options_by_order
776 o = getdict(global_options, name)
778 print "option %s already defined" % name
781 setdict(global_options, name, o)
782 global_options_by_order.append(name)
784 def getoption(name, image):
785 """option must be declared before being used in a part
786 if we're not processing a part, then we must
787 be at the top level where all options are available
788 global global_uses_options, global_option_values"""
789 curpart = partstack.tos()
791 o = getdict(curpart.uses_options, name)
793 o = getdict(global_options, name)
795 o = getdict(global_uses_options, name)
796 if (o == 0 or not o.defined):
797 error("Option %s undefined (missing use command?)" % name)
801 v = o.getvalue(image, image.getvalues())
803 v = o.getvalue(image, global_option_values)
806 def setoption(name, value):
807 global loc, global_options, global_option_values, curimage
808 curpart = partstack.tos()
809 if (curpart and curpart.part != 'mainboard'):
810 fatal("Options may only be set in top-level and mainboard configuration files")
811 o = getdict(global_uses_options, name)
813 fatal("Attempt to set nonexistent option %s" % name)
814 v = option_value(value)
816 o.setvalue(v, curimage.getvalues(), loc)
818 o.setvalue(v, global_option_values, loc)
820 def setdefault(name, value):
821 global loc, global_options
822 o = getdict(global_options, name)
826 print "setdefault: attempt to duplicate default for %s" % name
828 v = option_value(value)
831 def setnodefault(name):
832 global loc, global_options
833 o = getdict(global_options, name)
837 print "setdefault: attempt to duplicate default for %s" % name
841 def setcomment(name, value):
842 global loc, global_options
843 o = getdict(global_options, name)
845 fatal("setcomment: %s not here" % name)
846 o.setcomment(value, loc)
848 def setexported(name):
849 global global_options
850 o = getdict(global_options, name)
852 fatal("setexported: %s not here" % name)
855 def setnoexport(name):
856 global global_options
857 o = getdict(global_options, name)
859 fatal("setnoexport: %s not here" % name)
862 def setexportable(name):
863 global global_options
864 o = getdict(global_options, name)
866 fatal("setexportable: %s not here" % name)
869 def setformat(name, fmt):
870 global global_options
871 o = getdict(global_options, name)
873 fatal("setformat: %s not here" % name)
876 def getformated(name, image):
877 global global_options, global_option_values
878 o = getdict(global_options, name)
879 if (o == 0 or not o.defined):
880 fatal( "Option %s undefined." % name)
883 v = o.getvalue(image, image.getvalues())
885 v = o.getvalue(image, global_option_values)
887 return (f % v.contents())
889 def isexported(name):
890 global global_options
891 o = getdict(global_options, name)
893 return o.isexported()
896 #def isdefined(name, part):
897 # global global_options
899 # o = getdict(part.uses_options, name)
901 # o = getdict(global_options, name)
903 # return o.isdefined()
906 def isset(name, part):
907 global global_uses_options
909 o = getdict(part.uses_options, name)
911 o = getdict(global_uses_options, name)
916 #def isused(name, part):
917 # global global_options
919 # o = getdict(part.uses_options, name)
921 # o = getdict(global_options, name)
926 def usesoption(name):
927 global global_options, global_uses_options
928 curpart = partstack.tos()
930 curpart.usesoption(name)
932 o = getdict(global_options, name)
934 fatal("Can't use undefined option %s" % name)
936 o1 = getdict(global_uses_options, name)
939 setdict(global_uses_options, name, o)
941 def validdef(name, defval):
942 global global_options
943 o = getdict(global_options, name)
945 fatal("validdef: %s not here" % name)
946 if ((defval & 1) != 1):
947 fatal("Must specify default value for option %s" % name)
948 if ((defval & 2) != 2):
949 fatal("Must specify export for option %s" % name)
950 if ((defval & 4) != 4):
951 fatal("Must specify comment for option %s" % name)
954 file = os.path.join('src', 'config', 'Options.lb')
955 optionsfile = os.path.join(treetop, file)
956 fp = safe_open(optionsfile, 'r')
958 if (not parse('options', fp.read())):
959 fatal("Could not parse file")
963 global curimage, dirstack
965 curimage.setinitfile(treetop + '/src/' + path)
967 curimage.setinitfile(dirstack.tos() + '/' + path)
968 print "Adding init file: %s" % path
972 curpart = partstack.tos()
973 curpart.addconfig(path)
975 def addregister(field, value):
977 curpart = partstack.tos()
978 curpart.addregister(field, value)
980 def addcrt0include(path):
981 """we do the crt0include as a dictionary, so that if needed we
982 can trace who added what when. Also it makes the keys
985 curimage.addinitinclude(0, path)
987 def addinitinclude(str, path):
989 curimage.addinitinclude(dequote(str), path)
991 def addldscript(path):
992 global curimage, dirstack
993 curdir = dirstack.tos()
995 fullpath = treetop + '/src/' + path
997 fullpath = curdir + '/' + path
998 debug.info(debug.statement, "fullpath :%s: curdir :%s: path :%s:" % (fullpath, curdir, path))
999 curimage.addldscript(fullpath)
1003 curimage.setpayload(path)
1004 adduserdefine("PAYLOAD:=%s"%path)
1005 # addrule('payload')
1006 # adddep('payload', path)
1007 # addaction('payload', 'cp $< $@')
1009 def startromimage(name):
1010 global romimages, curimage, target_dir, target_name
1011 print "Configuring ROMIMAGE %s" % name
1012 o = getdict(romimages, name)
1014 fatal("romimage %s previously defined" % name)
1015 curimage = romimage(name)
1016 curimage.settargetdir(os.path.join(target_dir, name))
1017 #o = partobj(curimage, target_dir, 0, 'board', target_name)
1018 #curimage.setroot(o)
1019 setdict(romimages, name, curimage)
1023 print "End ROMIMAGE"
1027 def mainboard(path):
1028 full_path = os.path.join(treetop, 'src', 'mainboard', path)
1029 setoption('MAINBOARD', full_path)
1030 vendor = re.sub("/.*", "", path)
1031 part_number = re.sub("[^/]*/", "", path)
1032 setoption('MAINBOARD_VENDOR', vendor)
1033 setoption('MAINBOARD_PART_NUMBER', part_number)
1034 dodir('/config', 'Config.lb')
1035 part('mainboard', path, 'Config.lb', 0)
1036 curimage.setroot(partstack.tos())
1039 def addbuildrom(size, roms):
1041 print "Build ROM size %d" % size
1042 b = buildrom(size, roms)
1045 def addinitobject(object_name):
1047 curimage.addinitobjectrule(object_name)
1049 def addobject(object_name):
1051 curimage.addobjectrule(object_name)
1053 def adddriver(driver_name):
1055 curimage.adddriverrule(driver_name)
1058 global target_dir, target_name
1059 print "Configuring TARGET %s" % name
1061 target_dir = os.path.join(os.path.dirname(loc.file()), name)
1062 if not os.path.isdir(target_dir):
1063 print "Creating directory %s" % target_dir
1064 os.makedirs(target_dir)
1065 print "Will place Makefile, crt0.S, etc. in %s" % target_dir
1070 if (cpu_type and (cpu_type != path)):
1071 fatal("Two different CPU types: %s and %s" % (cpu_type, path))
1072 srcdir = "/cpu/%s" % path
1073 dodir(srcdir, "Config.lb")
1076 def part(type, path, file, name):
1077 global curimage, dirstack, partstack
1078 # special case for 'cpu' parts.
1079 # we could add a new function too, but this is rather trivial.
1080 # if the part is a cpu, and we haven't seen it before,
1081 # arrange to source the directory /cpu/'type'
1084 partdir = os.path.join(type, path)
1085 srcdir = os.path.join(treetop, 'src')
1086 fulldir = os.path.join(srcdir, partdir)
1087 type_name = flatten_name(os.path.join(type, path))
1088 newpart = partobj(curimage, fulldir, partstack.tos(), type, \
1090 print "Configuring PART %s, path %s" % (type, path)
1091 partstack.push(newpart)
1092 dirstack.push(fulldir)
1093 doconfigfile(srcdir, partdir, file)
1096 global dirstack, partstack
1097 curpart = partstack.pop()
1099 fatal("Trying to pop non-existent part")
1100 print "End PART %s" % curpart.part
1101 # Warn if options are used without being set in this part
1102 for i in curpart.uses_options.keys():
1103 if (not isset(i, curpart)):
1104 print "WARNING: Option %s using default value %s" % (i, getformated(i, curpart.image))
1107 def dodir(path, file):
1108 """dodir is like part but there is no new part"""
1110 # if the first char is '/', it is relative to treetop,
1111 # else relative to curdir
1112 # os.path.join screws up if the name starts with '/', sigh.
1113 print "Configuring DIR %s" % os.path.join(path, file)
1114 if (path[0] == '/'):
1115 fullpath = os.path.join(treetop, 'src')
1116 path = re.sub('^/*', '', path)
1118 fullpath = dirstack.tos()
1119 debug.info(debug.statement, "DODIR: path %s, fullpath %s" % (path, fullpath))
1120 dirstack.push(os.path.join(fullpath, path))
1121 doconfigfile(fullpath, path, file)
1126 v = getoption(name, curimage)
1132 curimage.addmakerule(id)
1134 def adduserdefine(str):
1136 curimage.adduserdefine(str)
1138 def addaction(id, str):
1140 curimage.addmakeaction(id, str)
1142 def adddep(id, str):
1144 curimage.addmakedepend(id, str)
1146 def setarch(my_arch):
1147 """arch is 'different' ... darn it."""
1149 curimage.setarch(my_arch)
1150 setoption('ARCH', my_arch)
1151 part('arch', my_arch, 'Config.lb', 0)
1153 def doconfigfile(path, confdir, file):
1154 rname = os.path.join(confdir, file)
1156 fullpath = os.path.join(path, rname)
1157 fp = safe_open(fullpath, 'r')
1158 if (not parse('cfgfile', fp.read())):
1159 fatal("Could not parse file")
1163 #=============================================================================
1165 #=============================================================================
1166 def ternary(val, yes, no):
1167 debug.info(debug.statement, "ternary %s" % expr)
1168 debug.info(debug.statement, "expr %s a %d yes %d no %d"% (expr, a, yes, no))
1170 debug.info(debug.statement, "Ternary returns %d" % yes)
1173 debug.info(debug.statement, "Ternary returns %d" % no)
1177 """atoi is in the python library, but not strtol? Weird!"""
1178 return eval('int(%s)' % name)
1181 """ Is the given string an integer?"""
1189 a = re.sub("^\"", "", str)
1190 a = re.sub("\"$", "", a)
1191 # highly un-intuitive, need four \!
1192 a = re.sub("\\\\\"", "\"", a)
1195 def flatten_name(str):
1196 a = re.sub("/", "_", str)
1200 """If the first part of <path> matches treetop, replace
1201 that part with $(TOP)"""
1202 if path[0:len(treetop)] == treetop:
1203 path = path[len(treetop):len(path)]
1204 if (path[0:1] == "/"):
1205 path = path[1:len(path)]
1206 path = "$(TOP)/" + path
1210 # to make if work without 2 passses, we use an old hack from SIMD, the
1211 # context bit. If the bit is 1, then ops get done, otherwise
1212 # ops don't get done. From the top level, context is always
1213 # 1. In an if, context depends on eval of the if condition
1219 # less general tokens should come first, otherwise they get matched
1221 token ACTION: 'action'
1222 token ADDACTION: 'addaction'
1223 token ALWAYS: 'always'
1225 token BUILDROM: 'buildrom'
1226 token COMMENT: 'comment'
1227 token CONFIG: 'config'
1229 token DEFAULT: 'default'
1230 token DEFINE: 'define'
1231 token DEPENDS: 'depends'
1233 token DRIVER: 'driver'
1238 token EXPORT: 'export'
1239 token FORMAT: 'format'
1242 token INITOBJECT: 'initobject'
1243 token INITINCLUDE: 'initinclude'
1244 token LDSCRIPT: 'ldscript'
1245 token LOADOPTIONS: 'loadoptions'
1246 token MAINBOARD: 'mainboard'
1247 token MAINBOARDINIT: 'mainboardinit'
1248 token MAKEDEFINE: 'makedefine'
1249 token MAKERULE: 'makerule'
1250 token NEVER: 'never'
1252 token NORTHBRIDGE: 'northbridge'
1253 token OBJECT: 'object'
1254 token OPTION: 'option'
1255 token PAYLOAD: 'payload'
1257 token PRINT: 'print'
1258 token REGISTER: 'register'
1259 token ROMIMAGE: 'romimage'
1260 token SOUTHBRIDGE: 'southbridge'
1261 token SUPERIO: 'superio'
1262 token TARGET: 'target'
1265 token NUM: r'[0-9]+'
1266 token XNUM: r'0x[0-9a-fA-F]+'
1267 # Why is path separate? Because paths to resources have to at least
1268 # have a slash, we thinks
1269 token PATH: r'[a-zA-Z0-9_.][a-zA-Z0-9/_.]+[a-zA-Z0-9_.]+'
1270 # Dir's on the other hand are abitrary
1271 # this may all be stupid.
1272 token DIRPATH: r'[-a-zA-Z0-9_$()./]+'
1273 token ID: r'[a-zA-Z_.]+[a-zA-Z0-9_.]*'
1274 token DELEXPR: r'{([^}]+|\\.)*}'
1275 token STR: r'"([^\\"]+|\\.)*"'
1276 token RAWTEXT: r'.*'
1278 rule expr: logical {{ l = logical }}
1279 ( "&&" logical {{ l = l and logical }}
1280 | "||" logical {{ l = l or logical }}
1283 rule logical: factor {{ n = factor }}
1284 ( "[+]" factor {{ n = n+factor }}
1285 | "-" factor {{ n = n-factor }}
1288 rule factor: term {{ v = term }}
1289 ( "[*]" term {{ v = v*term }}
1290 | "/" term {{ v = v/term }}
1291 | "<<" term {{ v = v << term }}
1292 | ">=" term {{ v = (v < term)}}
1295 # A term is a number, variable, or an expression surrounded by parentheses
1296 rule term: NUM {{ return atoi(NUM) }}
1297 | XNUM {{ return tohex(XNUM) }}
1298 | ID {{ return lookup(ID) }}
1299 | unop {{ return unop }}
1300 | "\\(" expr "\\)" {{ return expr }}
1302 rule unop: "!" expr {{ return not(expr) }}
1304 rule partend<<C>>: (stmt<<C>>)* END {{ if (C): partpop()}}
1306 # This is needed because the legacy cpu command could not distinguish
1307 # between cpu vendors. It should just be PATH, but getting this change
1308 # into the source tree will be tricky...
1309 # DO NOT USE ID AS IT MAY GO AWAY IN THE FUTURE
1310 rule partid: ID {{ return ID }}
1311 | PATH {{ return PATH }}
1313 rule parttype: NORTHBRIDGE {{ return 'northbridge' }}
1314 | SUPERIO {{ return 'superio' }}
1315 | PMC {{ return 'pmc' }}
1316 | SOUTHBRIDGE {{ return 'southbridge' }}
1317 | CPU {{ return 'cpu' }}
1319 rule partdef<<C>>: {{ name = 0 }}
1321 [ STR {{ name = dequote(STR) }}
1322 ] {{ if (C): part(parttype, partid, 'Config.lb', name) }}
1325 rule arch<<C>>: ARCH ID {{ if (C): setarch(ID) }}
1328 rule mainboardinit<<C>>:
1329 MAINBOARDINIT DIRPATH {{ if (C): addcrt0include(DIRPATH)}}
1331 rule initinclude<<C>>:
1334 DIRPATH {{ if (C): addinitinclude(STR, DIRPATH)}}
1336 rule initobject<<C>>:
1337 INITOBJECT DIRPATH {{ if (C): addinitobject(DIRPATH)}}
1339 rule object<<C>>: OBJECT DIRPATH {{ if (C): addobject(DIRPATH)}}
1341 rule driver<<C>>: DRIVER DIRPATH {{ if (C): adddriver(DIRPATH)}}
1343 rule dir<<C>>: DIR DIRPATH {{ if (C): dodir(DIRPATH, 'Config.lb') }}
1345 rule ldscript<<C>>: LDSCRIPT DIRPATH {{ if (C): addldscript(DIRPATH) }}
1347 rule iif<<C>>: IF ID {{ c = lookup(ID) }}
1349 [ ELSE (stmt<<C and not c>>)* ]
1352 rule depsacts<<ID, C>>:
1353 ( DEPENDS STR {{ if (C): adddep(ID, STR) }}
1354 | ACTION STR {{ if (C): addaction(ID, STR) }}
1357 rule makerule<<C>>: MAKERULE DIRPATH {{ if (C): addrule(DIRPATH) }}
1358 depsacts<<DIRPATH, C>>
1361 rule makedefine<<C>>:
1362 MAKEDEFINE RAWTEXT {{ if (C): adduserdefine(RAWTEXT) }}
1364 rule addaction<<C>>:
1365 ADDACTION ID STR {{ if (C): addaction(ID, STR) }}
1367 rule init<<C>>: INIT DIRPATH {{ if (C): addinit(DIRPATH) }}
1369 rule field: STR {{ return STR }}
1371 rule register<<C>>: REGISTER field '=' STR {{ if (C): addregister(field, STR) }}
1373 rule prtval: expr {{ return str(expr) }}
1374 | STR {{ return STR }}
1376 rule prtlist: prtval {{ el = "%(" + prtval }}
1377 ( "," prtval {{ el = el + "," + prtval }}
1378 )* {{ return el + ")" }}
1380 rule prtstmt<<C>>: PRINT STR {{ val = STR }}
1381 [ "," prtlist {{ val = val + prtlist }}
1382 ] {{ if (C): print eval(val) }}
1384 rule config<<C>>: CONFIG PATH {{ if (C): addconfig(PATH) }}
1386 rule stmt<<C>>: arch<<C>> {{ return arch}}
1387 | addaction<<C>> {{ return addaction }}
1388 | config<<C>> {{ return config}}
1389 | dir<<C>> {{ return dir}}
1390 | driver<<C>> {{ return driver }}
1391 | iif<<C>> {{ return iif }}
1392 | init<<C>> {{ return init }}
1393 | initinclude<<C>> {{ return initinclude }}
1394 | initobject<<C>> {{ return initobject }}
1395 | ldscript<<C>> {{ return ldscript}}
1396 | mainboardinit<<C>> {{ return mainboardinit }}
1397 | makedefine<<C>> {{ return makedefine }}
1398 | makerule<<C>> {{ return makerule }}
1399 | object<<C>> {{ return object }}
1400 | option<<C>> {{ return option }}
1401 | partdef<<C>> {{ return partdef }}
1402 | prtstmt<<C>> {{ return prtstmt}}
1403 | register<<C>> {{ return register}}
1405 # ENTRY for parsing Config.lb file
1406 rule cfgfile: (uses<<1>>)*
1410 rule usesid<<C>>: ID {{ if (C): usesoption(ID) }}
1412 rule uses<<C>>: USES (usesid<<C>>)+
1414 rule value: STR {{ return dequote(STR) }}
1415 | expr {{ return expr }}
1416 | DELEXPR {{ return DELEXPR }}
1418 rule option<<C>>: OPTION ID EQ value {{ if (C): setoption(ID, value) }}
1420 rule opif<<C>>: IF ID {{ c = lookup(ID) }}
1421 (opstmt<<C and c>>)*
1422 [ ELSE (opstmt<<C and not c>>)* ]
1425 rule opstmt<<C>>: option<<C>>
1429 rule payload<<C>>: PAYLOAD DIRPATH {{ if (C): payload(DIRPATH) }}
1431 rule mainboard<<C>>:
1432 MAINBOARD PATH {{ if (C): mainboard(PATH) }}
1434 rule romif<<C>>: IF ID {{ c = lookup(ID) }}
1435 (romstmt<<C and c>>)*
1436 [ ELSE (romstmt<<C and not c>>)* ]
1439 rule romstmt<<C>>: romif<<C>>
1444 rule romimage: ROMIMAGE STR {{ startromimage(dequote(STR)) }}
1446 END {{ endromimage() }}
1448 rule roms: STR {{ s = '(' + STR }}
1449 ( STR {{ s = s + "," + STR }}
1450 )* {{ return eval(s + ')') }}
1452 rule buildrom: BUILDROM expr roms {{ addbuildrom(expr, roms) }}
1454 rule romstmts: romimage
1458 # ENTRY for parsing root part
1459 rule board: LOADOPTIONS {{ loadoptions() }}
1460 TARGET DIRPATH {{ target(DIRPATH) }}
1465 # ENTRY for parsing a delayed value
1466 rule delexpr: "{" expr "}" EOF {{ return expr }}
1468 rule defstmts<<ID>>: {{ d = 0 }}
1470 ( value {{ setdefault(ID, value) }}
1471 | NONE {{ setnodefault(ID) }}
1473 | FORMAT STR {{ setformat(ID, dequote(STR)) }}
1475 ( ALWAYS {{ setexported(ID) }}
1476 | USED {{ setexportable(ID) }}
1477 | NEVER {{ setnoexport(ID) }}
1479 | COMMENT STR {{ setcomment(ID, dequote(STR)); d = d | 4 }}
1482 rule define: DEFINE ID {{ newoption(ID) }}
1483 defstmts<<ID>> END {{ validdef(ID, defstmts) }}
1485 # ENTRY for parsing Options.lb file
1486 rule options: (define)* EOF {{ return 1 }}
1489 #=============================================================================
1491 #=============================================================================
1492 def writemakefileheader(file, fname):
1493 file.write("# File: %s\n" % fname)
1494 file.write("# This file was generated by '%s %s %s'\n\n"
1495 % (sys.argv[0], sys.argv[1], sys.argv[2]))
1497 def writemakefilesettings(path):
1498 global treetop, target_dir
1499 # Write Makefile.settings to seperate the settings
1500 # from the actual makefile creation
1501 # In practice you need to rerun NLBConfig.py to change
1502 # these but in theory you shouldn't need to.
1504 filename = os.path.join(path, "Makefile.settings")
1505 print "Creating", filename
1506 file = safe_open(filename, 'w+')
1507 writemakefileheader(file, filename)
1508 file.write("TOP:=%s\n" % (treetop))
1509 file.write("TARGET_DIR:=%s\n" % target_dir)
1510 # for i in global_options_by_order:
1511 # if (isexported(i, 0)):
1512 # file.write("export %s:=%s\n" % (i, getformated(i, 0)))
1513 # file.write("export VARIABLES := ")
1514 # for i in global_options.keys():
1515 # if (isexported(i, 0)):
1516 # file.write("%s " % i)
1520 def writeimagesettings(image):
1522 global global_options_by_order
1523 # Write Makefile.settings to seperate the settings
1524 # from the actual makefile creation
1525 # In practice you need to rerun NLBConfig.py to change
1526 # these but in theory you shouldn't need to.
1528 filename = os.path.join(image.gettargetdir(), "Makefile.settings")
1529 print "Creating", filename
1530 file = safe_open(filename, 'w+')
1531 writemakefileheader(file, filename)
1532 file.write("TOP:=%s\n" % (treetop))
1533 file.write("TARGET_DIR:=%s\n" % (image.gettargetdir()))
1534 for i in global_options_by_order:
1536 file.write("export %s:=%s\n" % (i, getformated(i, image)))
1537 file.write("export VARIABLES := ")
1538 for i in global_options_by_order:
1540 file.write("%s " % i)
1544 # write the romimage makefile
1545 # let's try the Makefile
1546 # first, dump all the -D stuff
1548 def writeimagemakefile(image):
1549 makefilepath = os.path.join(image.gettargetdir(), "Makefile")
1550 print "Creating", makefilepath
1551 file = safe_open(makefilepath, 'w+')
1552 writemakefileheader(file, makefilepath)
1554 #file.write("include cpuflags\n")
1555 # Putting "include cpuflags" in the Makefile has the problem that the
1556 # cpuflags file would be generated _after_ we want to include it.
1557 # Instead, let make do the work of computing CPUFLAGS:
1558 file.write("# Get the value of TOP, VARIABLES, and several other variables.\n")
1559 file.write("include Makefile.settings\n\n")
1560 file.write("# Function to create an item like -Di586 or -DMAX_CPUS='1' or -Ui686\n")
1561 file.write("D_item = $(if $(subst undefined,,$(origin $1)),-D$1$(if $($1),='$($1)',),-U$1)\n\n")
1562 file.write("# Compute the value of CPUFLAGS here during make's first pass.\n")
1563 file.write("CPUFLAGS := $(foreach _var_,$(VARIABLES),$(call D_item,$(_var_)))\n\n")
1565 for i in image.getuserdefines():
1566 file.write("%s\n" %i)
1570 file.write("all: linuxbios.rom")
1571 # print out all the object dependencies
1572 file.write("\n# object dependencies (objectrules:)\n")
1573 file.write("INIT-OBJECTS :=\n")
1574 file.write("OBJECTS :=\n")
1575 file.write("DRIVER :=\n")
1576 file.write("\nSOURCES :=\n")
1577 for irule, init in image.getinitobjectrules().items():
1580 file.write("INIT-OBJECTS += %s\n" % (i_name))
1581 file.write("SOURCES += %s\n" % (i_source))
1583 for objrule, obj in image.getobjectrules().items():
1586 file.write("OBJECTS += %s\n" % (obj_name))
1587 file.write("SOURCES += %s\n" % (obj_source))
1590 file.write("OBJECTS += static.o\n")
1591 file.write("SOURCES += static.c\n")
1593 for driverrule, driver in image.getdriverrules().items():
1594 obj_name = driver[0]
1595 obj_source = driver[1]
1596 file.write("DRIVER += %s\n" % (obj_name))
1597 file.write("SOURCES += %s\n" % (obj_source))
1599 # Print out all ldscript.ld dependencies.
1600 file.write("\n# ldscript.ld dependencies:\n")
1601 file.write("LDSUBSCRIPTS-1 := \n" )
1602 for script in image.getldscripts():
1603 file.write("LDSUBSCRIPTS-1 += %s\n" % topify(script))
1605 # Print out the dependencies for crt0_includes.h
1606 file.write("\n# Dependencies for crt0_includes.h\n")
1607 file.write("CRT0_INCLUDES:=\n")
1608 for inc in image.getinitincludes():
1609 if (local_path.match(inc)):
1610 file.write("CRT0_INCLUDES += %s\n" % inc)
1612 file.write("CRT0_INCLUDES += $(TOP)/src/%s\n" % inc)
1614 # Print out the user defines.
1615 file.write("\n# userdefines:\n")
1616 #for udef in image.userdefines:
1617 #file.write("%s\n" % udef)
1619 # Print out the base rules.
1620 # Need to have a rule that counts on 'all'.
1621 file.write("\n# mainrulelist:")
1622 #file.write("\nmainrule: %s\n" % image.mainrulelist)
1624 # Print out any user rules.
1625 file.write("\n# From makerule or docipl commands:\n")
1626 # Old way (hash order): for target in makebaserules.keys():
1627 # New way (config file order):
1628 #for target in image.makerule_targets:
1629 #image.makebaserules[target].write(file)
1631 file.write("\n# objectrules:\n")
1632 for objrule, obj in image.getobjectrules().items():
1633 source = topify(obj[1])
1636 # for .S, .o depends on .s
1637 file.write("%s: %s.s\n" % (obj[0], obj[3]))
1638 file.write("\t@echo $(CC) ... -o $@ $<\n")
1639 file.write("\t$(CC) -c $(CPU_OPT) -o $@ $<\n")
1640 # and .s depends on .S
1641 file.write("%s.s: %s\n" % (obj[3], source))
1642 file.write("\t@echo $(CPP) ... $< > $@\n")
1643 # Note: next 2 lines are ONE output line!
1644 file.write("\t$(CPP) $(CPPFLAGS) $< ")
1645 file.write(">$@.new && mv $@.new $@\n")
1647 file.write("%s: %s\n" % (obj[0], source))
1648 file.write("\t$(CC) -c $(CFLAGS) -o $@ $<\n")
1649 #file.write("%s\n" % objrule[2])
1651 for driverrule, driver in image.getdriverrules().items():
1652 source = topify(driver[1])
1653 file.write("%s: %s\n" % (driver[0], source))
1654 file.write("\t$(CC) -c $(CFLAGS) -o $@ $<\n")
1655 #file.write("%s\n" % objrule[2])
1657 # special rule for chip_target.c
1658 file.write("static.o: static.c\n")
1659 file.write("\t$(CC) -c $(CFLAGS) -o $@ $<\n")
1661 # Print out the rules that will make cause the files
1662 # generated by NLBConfig.py to be remade if any dependencies change.
1664 file.write("\n# Remember the automatically generated files\n")
1665 file.write("GENERATED:=\n")
1666 for genfile in ['Makefile',
1669 'LinuxBIOSDoc.config' ]:
1670 file.write("GENERATED += %s\n" % genfile)
1671 file.write("GENERATED += %s\n" % image.getincludefilename())
1673 #file.write("\n# Remake Makefile (and the other files generated by\n")
1674 #file.write("# NLBConfig.py) if any config dependencies change.\n")
1676 #for cfile in image.config_file_list:
1677 # file.write("$(GENERATED): %s\n" % topify(cfile))
1679 #for depfile in [ '%s' % top_config_file, # This a duplicate, remove?
1680 # '$(TOP)/util/config/NLBConfig.py',
1681 # '$(TOP)/src/arch/$(ARCH)/config/make.base' ]:
1682 # file.write("$(GENERATED): %s\n" % depfile)
1684 #file.write("$(GENERATED):\n")
1685 #file.write("\tpython $(TOP)/util/config/NLBConfig.py %s $(TOP)\n"
1686 # % top_config_file)
1688 keys = image.getroot().uses_options.keys()
1690 file.write("\necho:\n")
1692 file.write("\t@echo %s='$(%s)'\n"% (key,key))
1694 for i, m in image.getmakerules().items():
1695 file.write("%s: " %i)
1696 for i in m.dependency:
1697 file.write("%s " % i)
1700 file.write("\t%s\n" % i)
1704 def writemakefile(path):
1705 makefilepath = os.path.join(path, "Makefile")
1706 print "Creating", makefilepath
1707 file = safe_open(makefilepath, 'w+')
1708 writemakefileheader(file, makefilepath)
1712 for i in romimages.keys():
1713 file.write("%s-rom " % i)
1715 for i, o in romimages.items():
1716 file.write("%s-rom:\n" % o.getname())
1717 file.write("\tif (cd %s; \\\n" % o.getname())
1718 file.write("\t\tmake linuxbios.rom)\\\n");
1719 file.write("\tthen true; else exit 1; fi;\n\n")
1720 file.write("clean: ")
1721 for i in romimages.keys():
1722 file.write("%s-clean " % i)
1724 for i, o in romimages.items():
1725 file.write("%s-clean:\n" % o.getname())
1726 file.write("\t(cd %s; make clean)\n" % o.getname())
1729 def writeinitincludes(image):
1730 global include_pattern
1731 filepath = os.path.join(image.gettargetdir(), image.getincludefilename())
1732 print "Creating", filepath
1733 outfile = safe_open(filepath, 'w+')
1734 if (image.newformat()):
1735 infile = safe_open(image.getinitfile(), 'r')
1737 line = infile.readline()
1739 p = include_pattern.match(line)
1741 for i in image.getinitincludes():
1742 inc = image.getinitinclude(i)
1743 if (inc.getstring() == p.group(1)):
1744 outfile.write("#include \"%s\"\n" % inc.getpath())
1746 outfile.write(line);
1747 line = infile.readline()
1751 for i in image.getinitincludes():
1752 outfile.write("#include <%s>\n" % i)
1755 def writeldoptions(image):
1756 # Write Makefile.settings to seperate the settings
1757 # from the actual makefile creation
1758 # In practice you need to rerun NLBConfig.py to change
1759 # these but in theory you shouldn't need to.
1761 filename = os.path.join(image.gettargetdir(), "ldoptions")
1762 print "Creating", filename
1763 file = safe_open(filename, 'w+')
1764 for i in global_options.keys():
1765 if (isexported(i) and IsInt(getoption(i, image))):
1766 file.write("%s = %s;\n" % (i, getformated(i, image)))
1769 def dumptree(part, lvl):
1770 debug.info(debug.dumptree, "DUMPTREE ME is")
1772 # dump the siblings -- actually are there any? not sure
1774 debug.info(debug.dumptree, "DUMPTREE SIBLINGS are")
1780 debug.info(debug.dumptree, "DUMPTREE KIDS are")
1781 #for kid in part.children:
1783 dumptree(part.children, lvl+1)
1784 debug.info(debug.dumptree, "DONE DUMPTREE")
1786 def writecode(image):
1787 filename = os.path.join(img_dir, "static.c")
1788 print "Creating", filename
1789 file = safe_open(filename, 'w+')
1790 file.write("#include <device/chip.h>\n")
1791 for path in image.getconfigincludes().values():
1792 file.write("#include \"%s\"\n" % path)
1793 gencode(image.getroot(), file, 0)
1794 gencode(image.getroot(), file, 1)
1797 def gencode(part, file, pass_num):
1798 debug.info(debug.gencode, "GENCODE ME is")
1799 part.gencode(file, pass_num)
1800 # dump the siblings -- actually are there any? not sure
1801 debug.info(debug.gencode, "GENCODE SIBLINGS are")
1804 kid.gencode(file, pass_num)
1806 # now dump the children
1807 debug.info(debug.gencode, "GENCODE KIDS are")
1809 gencode(part.children, file, pass_num)
1813 gencode(kid.children, file, pass_num)
1815 debug.info(debug.gencode, "DONE GENCODE")
1817 def verifyparse(image):
1818 """Add any run-time checks to verify that parsing the configuration
1820 if (image.newformat() and image.getinitfile() == ''):
1821 fatal("An init file must be specified")
1823 #=============================================================================
1825 #=============================================================================
1826 if __name__=='__main__':
1827 from sys import argv
1829 print 'Args: <file> <path to linuxbios>'
1832 top_config_file = os.path.abspath(sys.argv[1])
1834 treetop = os.path.abspath(sys.argv[2])
1836 # Now read in the customizing script...
1838 fp = safe_open(argv[1], 'r')
1839 if (not parse('board', fp.read())):
1840 fatal("Could not parse file")
1843 for image_name, image in romimages.items():
1846 # no longer need to check if an options has been used
1849 for image_name, image in romimages.items():
1850 if (debug.level(debug.dumptree)):
1851 debug.info(debug.dumptree, "DEVICE TREE:")
1852 dumptree(image.getroot(), 0)
1854 img_dir = image.gettargetdir()
1855 if not os.path.isdir(img_dir):
1856 print "Creating directory %s" % img_dir
1857 os.makedirs(img_dir)
1859 if (debug.level(debug.dump)):
1860 for i in image.getinitincludes():
1861 debug.info(debug.dump, "crt0include file %s" % i)
1862 for i in image.getdriverrules().keys():
1863 debug.info(debug.dump, "driver file %s" % i)
1864 for i in image.getldscripts():
1865 debug.info(debug.dump, "ldscript file %s" % i)
1866 for i, m in image.getmakerules().items():
1867 debug.info(debug.dump, " makerule %s dep %s act %s" % (i, m.dependency, m.actions))
1870 writeimagesettings(image)
1871 writeinitincludes(image)
1872 writeimagemakefile(image)
1873 writeldoptions(image)
1875 writemakefilesettings(target_dir)
1876 writemakefile(target_dir)