4 # This file is part of BeRTOS.
6 # Bertos is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 # As a special exception, you may use this file as part of a free software
21 # library without restriction. Specifically, if other files instantiate
22 # templates or use macros or inline functions from this file, or you compile
23 # this file and link it with other files to produce an executable, this
24 # file does not by itself cause the resulting executable to be covered by
25 # the GNU General Public License. This exception does not however
26 # invalidate any other reasons why the executable file might be covered by
27 # the GNU General Public License.
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
33 # Author: Lorenzo Berni <duplo@develer.com>
41 # Use custom copytree function
47 import DefineException
49 def isBertosDir(directory):
50 return os.path.exists(directory + "/VERSION")
52 def bertosVersion(directory):
53 return open(directory + "/VERSION").readline().strip()
55 def createBertosProject(project_info):
56 directory = project_info.info("PROJECT_PATH")
57 sources_dir = project_info.info("SOURCES_PATH")
58 if not os.path.isdir(directory):
60 f = open(directory + "/project.bertos", "w")
61 f.write(pickle.dumps(project_info))
63 # Destination source dir
64 srcdir = directory + "/bertos"
65 shutil.rmtree(srcdir, True)
66 copytree.copytree(sources_dir + "/bertos", srcdir, ignore_list=const.IGNORE_LIST)
67 # Destination makefile
68 makefile = directory + "/Makefile"
69 if os.path.exists(makefile):
71 makefile = open("mktemplates/Makefile").read()
72 makefile = makefileGenerator(project_info, makefile)
73 open(directory + "/Makefile", "w").write(makefile)
74 # Destination project dir
75 prjdir = directory + "/" + os.path.basename(directory)
76 shutil.rmtree(prjdir, True)
78 # Destination hw files
79 hwdir = prjdir + "/hw"
80 shutil.rmtree(hwdir, True)
82 # Copy all the hw files
83 for module, information in project_info.info("MODULES").items():
84 for hwfile in information["hw"]:
85 string = open(sources_dir + "/" + hwfile, "r").read()
86 open(hwdir + "/" + os.path.basename(hwfile), "w").write(string)
87 # Destination configurations files
88 cfgdir = prjdir + "/cfg"
89 shutil.rmtree(cfgdir, True)
91 # Set to 1 the autoenabled for enabled modules
92 for module, information in project_info.info("MODULES").items():
93 if information["enabled"] and "configuration" in information and information["configuration"] != "":
94 configurations = project_info.info("CONFIGURATIONS")
95 configuration = configurations[information["configuration"]]
96 for start, parameter in configuration["paramlist"]:
97 if "type" in configuration[parameter]["informations"] and configuration[parameter]["informations"]["type"] == "autoenabled":
98 configuration[parameter]["value"] = "1"
99 project_info.setInfo("CONFIGURATIONS", configurations)
100 # Copy all the configuration files
101 for configuration, information in project_info.info("CONFIGURATIONS").items():
102 string = open(sources_dir + "/" + configuration, "r").read()
103 for start, parameter in information["paramlist"]:
104 infos = information[parameter]
105 value = infos["value"]
106 if "unsigned" in infos["informations"] and infos["informations"]["unsigned"]:
108 if "long" in infos["informations"] and infos["informations"]["long"]:
110 string = sub(string, parameter, value)
111 f = open(cfgdir + "/" + os.path.basename(configuration), "w")
115 makefile = open("mktemplates/template.mk", "r").read()
116 makefile = mkGenerator(project_info, makefile)
117 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
118 # Destination main.c file
119 main = open("srctemplates/main.c", "r").read()
120 open(prjdir + "/main.c", "w").write(main)
121 # Files for selected plugins
123 for plugin in project_info.info("OUTPUT"):
124 module = loadPlugin(plugin)
125 relevants_files[plugin] = module.createProject(project_info)
126 project_info.setInfo("RELEVANT_FILES", relevants_files)
128 def loadPlugin(plugin):
130 Returns the given plugin module.
132 return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
134 def mkGenerator(project_info, makefile):
136 Generates the mk file for the current project.
139 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
140 mk_data["$cpuflag"] = project_info.info("CPU_INFOS")["CPU_FLAG_NAME"]
141 mk_data["$cpuname"] = project_info.info("CPU_INFOS")["CORE_CPU"]
142 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
143 mk_data["$cflags"] = " ".join(project_info.info("CPU_INFOS")["C_FLAGS"])
144 mk_data["$ldflags"] = " ".join(project_info.info("CPU_INFOS")["LD_FLAGS"])
145 mk_data["$cppflags"] = " ".join(project_info.info("CPU_INFOS")["CPP_FLAGS"])
146 mk_data["$cppaflags"] = " ".join(project_info.info("CPU_INFOS")["CPPA_FLAGS"])
147 mk_data["$cxxflags"] = " ".join(project_info.info("CPU_INFOS")["CXX_FLAGS"])
148 mk_data["$asflags"] = " ".join(project_info.info("CPU_INFOS")["AS_FLAGS"])
149 mk_data["$arflags"] = " ".join(project_info.info("CPU_INFOS")["AR_FLAGS"])
150 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
151 mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
152 mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
153 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
155 while makefile.find(key) != -1:
156 makefile = makefile.replace(key, mk_data[key])
159 def makefileGenerator(project_info, makefile):
161 Generate the Makefile for the current project.
163 # TODO write a general function that works for both the mk file and the Makefile
164 while makefile.find("project_name") != -1:
165 makefile = makefile.replace("project_name", os.path.basename(project_info.info("PROJECT_PATH")))
168 def csrcGenerator(project_info):
169 modules = project_info.info("MODULES")
170 files = project_info.info("FILES")
171 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
175 # file to be included in CSRC variable
177 # file to be included in PCSRC variable
179 # files to be included in CPPASRC variable
181 # files to be included in CXXSRC variable
183 # files to be included in ASRC variable
185 # constants to be included at the beginning of the makefile
187 for module, information in modules.items():
188 module_files = set([])
189 dependency_files = set([])
192 hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
193 if information["enabled"]:
194 if "constants" in information:
195 constants.update(information["constants"])
196 cfiles, sfiles = findModuleFiles(module, project_info)
197 module_files |= set(cfiles)
198 asm_files |= set(sfiles)
199 for file in information["hw"]:
200 if file.endswith(".c"):
201 module_files |= set([hwdir + "/" + os.path.basename(file)])
202 for file_dependency in information["depends"]:
203 if file_dependency in files:
204 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
205 dependency_files |= set(dependencyCFiles)
206 asm_files |= set(dependencySFiles)
207 for file in module_files:
208 if not harvard or information.get("harvard", "both") == "both":
210 if harvard and "harvard" in information:
212 for file in dependency_files:
214 for file in project_info.info("CPU_INFOS")["C_SRC"]:
216 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
218 for file in asm_files:
220 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
222 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
224 for file in project_info.info("CPU_INFOS")["ASRC"]:
226 csrc = " \\\n\t".join(csrc) + " \\"
227 pcsrc = " \\\n\t".join(pcsrc) + " \\"
228 cppasrc = " \\\n\t".join(cppasrc) + " \\"
229 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
230 asrc = " \\\n\t".join(asrc) + " \\"
231 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
232 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
234 def findModuleFiles(module, project_info):
235 # Find the files related to the selected module
238 # .c files related to the module and the cpu architecture
239 for filename, path in findDefinitions(module + ".c", project_info) + \
240 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
241 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
242 path = replaceSeparators(path)
243 cfiles.append(path + "/" + filename)
244 # .s files related to the module and the cpu architecture
245 for filename, path in findDefinitions(module + ".s", project_info) + \
246 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
247 findDefinitions(module + ".S", project_info) + \
248 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
249 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
250 path = replaceSeparators(path)
251 sfiles.append(path + "/" + filename)
252 # .c and .s files related to the module and the cpu tags
253 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
254 for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
255 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
257 path = replaceSeparators(path)
258 cfiles.append(path + "/" + filename)
259 for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
260 findDefinitions(module + "_" + tag + ".S", project_info):
261 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
262 path = replaceSeparators(path)
263 sfiles.append(path + "/" + filename)
264 return cfiles, sfiles
266 def replaceSeparators(path):
268 Replace the separators in the given path with unix standard separator.
271 while path.find(os.sep) != -1:
272 path = path.replace(os.sep, "/")
276 path = os.environ["PATH"]
278 path = path.split(";")
280 path = path.split(":")
283 def findToolchains(path_list):
285 for element in path_list:
286 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
287 toolchains.append(toolchain)
288 return list(set(toolchains))
290 def getToolchainInfo(output):
292 expr = re.compile("Target: .*")
293 target = expr.findall(output)
295 info["target"] = target[0].split("Target: ")[1]
296 expr = re.compile("gcc version [0-9,.]*")
297 version = expr.findall(output)
298 if len(version) == 1:
299 info["version"] = version[0].split("gcc version ")[1]
300 expr = re.compile("gcc version [0-9,.]* \(.*\)")
301 build = expr.findall(output)
303 build = build[0].split("gcc version ")[1]
304 build = build[build.find("(") + 1 : build.find(")")]
305 info["build"] = build
306 expr = re.compile("Configured with: .*")
307 configured = expr.findall(output)
308 if len(configured) == 1:
309 info["configured"] = configured[0].split("Configured with: ")[1]
310 expr = re.compile("Thread model: .*")
311 thread = expr.findall(output)
313 info["thread"] = thread[0].split("Thread model: ")[1]
316 def loadSourceTree(project):
317 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
318 project.setInfo("FILE_LIST", fileList)
320 def findDefinitions(ftype, project):
321 L = project.info("FILE_LIST")
324 for filename in element[2]:
325 if fnmatch.fnmatch(filename, ftype):
326 definitions.append((filename, element[0]))
329 def loadCpuInfos(project):
331 for definition in findDefinitions(const.CPU_DEFINITION, project):
332 cpuInfos.append(getInfos(definition))
335 def getTagSet(cpu_info):
338 tag_set |= set([cpu["CPU_NAME"]])
339 tag_set |= set(cpu["CPU_TAGS"])
340 tag_set |= set([cpu["CORE_CPU"]])
341 tag_set |= set([cpu["TOOLCHAIN"]])
345 def getInfos(definition):
347 D.update(const.CPU_DEF)
348 def include(filename, dict = D, directory=definition[1]):
349 execfile(directory + "/" + filename, {}, D)
350 D["include"] = include
351 include(definition[0], D)
352 D["CPU_NAME"] = definition[0].split(".")[0]
353 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
357 def getCommentList(string):
358 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
359 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
362 def loadModuleDefinition(first_comment):
364 module_definition = {}
365 for num, line in enumerate(first_comment):
366 index = line.find("$WIZ$")
370 exec line[index + len("$WIZ$ "):] in {}, module_definition
372 raise ParseError(num, line[index:])
373 elif line.find("\\brief") != -1:
374 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
376 if "module_name" in module_definition:
377 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
378 del module_definition[const.MODULE_DEFINITION["module_name"]]
379 module_dict[module_name] = {}
380 if const.MODULE_DEFINITION["module_depends"] in module_definition:
381 depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
382 del module_definition[const.MODULE_DEFINITION["module_depends"]]
383 if type(depends) == str:
385 module_dict[module_name]["depends"] = depends
387 module_dict[module_name]["depends"] = ()
388 if const.MODULE_DEFINITION["module_configuration"] in module_definition:
389 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
390 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
392 module_dict[module_name]["configuration"] = ""
393 if "module_description" in module_definition:
394 module_dict[module_name]["description"] = module_definition["module_description"]
395 del module_definition["module_description"]
396 if const.MODULE_DEFINITION["module_harvard"] in module_definition:
397 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
398 if harvard == "both" or harvard == "pgm_memory":
399 module_dict[module_name]["harvard"] = harvard
400 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
401 if const.MODULE_DEFINITION["module_hw"] in module_definition:
402 hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
403 del module_definition[const.MODULE_DEFINITION["module_hw"]]
406 module_dict[module_name]["hw"] = hw
408 module_dict[module_name]["hw"] = ()
409 if const.MODULE_DEFINITION["module_supports"] in module_definition:
410 supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
411 del module_definition[const.MODULE_DEFINITION["module_supports"]]
412 module_dict[module_name]["supports"] = supports
413 module_dict[module_name]["constants"] = module_definition
414 module_dict[module_name]["enabled"] = False
415 return to_be_parsed, module_dict
417 def isSupported(project, module=None, property_id=None):
418 if not module and property_id:
419 item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
421 item = project.info("MODULES")[module]
422 tag_dict = project.info("ALL_CPU_TAGS")
423 if "supports" in item:
424 support_string = item["supports"]
427 exec "supported = " + support_string in tag_dict, supported
429 raise SupportedException(support_string)
430 return supported["supported"]
434 def loadDefineLists(comment_list):
436 for comment in comment_list:
437 for num, line in enumerate(comment):
438 index = line.find("$WIZ$")
441 exec line[index + len("$WIZ$ "):] in {}, define_list
443 raise ParseError(num, line[index:])
444 for key, value in define_list.items():
445 if type(value) == str:
446 define_list[key] = (value,)
449 def getDescriptionInformations(comment):
451 Take the doxygen comment and strip the wizard informations, returning the tuple
452 (comment, wizard_information)
457 for num, line in enumerate(comment):
458 index = line.find("$WIZ$")
461 brief += line[:index].strip()
463 description += " " + line[:index]
465 exec line[index + len("$WIZ$ "):] in {}, information
467 raise ParseError(num, line[index:])
470 brief += line.strip()
472 description += " " + line
473 description = description.strip()
474 return brief.strip(), description.strip(), information
476 def getDefinitionBlocks(text):
478 Take a text and return a list of tuple (description, name-value).
481 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
482 for match in block_tmp:
483 # Only the first element is needed
484 comment = match.group(1)
485 define = match.group(2)
486 start = match.start()
487 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
488 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
489 comment = match.group(1)
490 define = match.group(2)
491 start = match.start()
492 block.append(([comment], define, start))
493 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
494 comment = match.group(2)
495 define = match.group(1)
496 start = match.start()
497 block.append(([comment], define, start))
500 def loadModuleData(project):
501 module_info_dict = {}
503 configuration_info_dict = {}
505 for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
506 comment_list = getCommentList(open(path + "/" + filename, "r").read())
507 if len(comment_list) > 0:
509 configuration_info = {}
511 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
512 except ParseError, err:
513 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
514 for module, information in module_dict.items():
515 if "depends" not in information:
516 information["depends"] = ()
517 information["depends"] += (filename.split(".")[0],)
518 information["category"] = os.path.basename(path)
519 if "configuration" in information and len(information["configuration"]):
520 configuration = module_dict[module]["configuration"]
522 configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
523 except ParseError, err:
524 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
525 module_info_dict.update(module_dict)
526 configuration_info_dict.update(configuration_info)
529 list_dict = loadDefineLists(comment_list[1:])
530 list_info_dict.update(list_dict)
531 except ParseError, err:
532 raise DefineException.EnumDefineException(path, err.line_number, err.line)
533 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
534 comment_list = getCommentList(open(path + "/" + filename, "r").read())
535 list_info_dict.update(loadDefineLists(comment_list))
536 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
537 for filename, path in findDefinitions("*_" + tag + ".h", project):
538 comment_list = getCommentList(open(path + "/" + filename, "r").read())
539 list_info_dict.update(loadDefineLists(comment_list))
540 project.setInfo("MODULES", module_info_dict)
541 project.setInfo("LISTS", list_info_dict)
542 project.setInfo("CONFIGURATIONS", configuration_info_dict)
543 project.setInfo("FILES", file_dict)
545 def formatParamNameValue(text):
547 Take the given string and return a tuple with the name of the parameter in the first position
548 and the value in the second.
550 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
553 def loadConfigurationInfos(path):
555 Return the module configurations found in the given file as a dict with the
556 parameter name as key and a dict containig the fields above as value:
557 "value": the value of the parameter
558 "description": the description of the parameter
559 "informations": a dict containig optional informations:
560 "type": "int" | "boolean" | "enum"
561 "min": the minimum value for integer parameters
562 "max": the maximum value for integer parameters
563 "long": boolean indicating if the num is a long
564 "unsigned": boolean indicating if the num is an unsigned
565 "value_list": the name of the enum for enum parameters
567 configuration_infos = {}
568 configuration_infos["paramlist"] = []
569 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
570 name, value = formatParamNameValue(define)
571 brief, description, informations = getDescriptionInformations(comment)
572 configuration_infos["paramlist"].append((start, name))
573 configuration_infos[name] = {}
574 configuration_infos[name]["value"] = value
575 configuration_infos[name]["informations"] = informations
576 if not "type" in configuration_infos[name]["informations"]:
577 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
578 if ("type" in configuration_infos[name]["informations"] and
579 configuration_infos[name]["informations"]["type"] == "int" and
580 configuration_infos[name]["value"].find("L") != -1):
581 configuration_infos[name]["informations"]["long"] = True
582 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
583 if ("type" in configuration_infos[name]["informations"] and
584 configuration_infos[name]["informations"]["type"] == "int" and
585 configuration_infos[name]["value"].find("U") != -1):
586 configuration_infos[name]["informations"]["unsigned"] = True
587 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
588 configuration_infos[name]["description"] = description
589 configuration_infos[name]["brief"] = brief
590 return configuration_infos
592 def findParameterType(parameter):
593 if "value_list" in parameter["informations"]:
595 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
598 def sub(string, parameter, value):
600 Substitute the given value at the given parameter define in the given string
602 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
604 def isInt(informations):
606 Return True if the value is a simple int.
608 if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
613 def isLong(informations):
615 Return True if the value is a long.
617 if "long" in informations and informations["long"] and "unsigned" not in informations:
622 def isUnsigned(informations):
624 Return True if the value is an unsigned.
626 if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
631 def isUnsignedLong(informations):
633 Return True if the value is an unsigned long.
635 if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
640 class ParseError(Exception):
641 def __init__(self, line_number, line):
642 Exception.__init__(self)
643 self.line_number = line_number
646 class SupportedException(Exception):
647 def __init__(self, support_string):
648 Exception.__init__(self)
649 self.support_string = support_string