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 from _wizard_version import WIZARD_VERSION
51 from LoadException import VersionException, ToolchainException
53 def isBertosDir(directory):
54 return os.path.exists(directory + "/VERSION")
56 def bertosVersion(directory):
57 return open(directory + "/VERSION").readline().strip()
59 def enabledModules(project_info):
61 for name, module in project_info.info("MODULES").items():
63 enabled_modules.append(name)
64 return enabled_modules
66 def presetList(directory):
68 Return the list of the preset found in the selected BeRTOS Version.
70 abspath = os.path.join(directory, const.PREDEFINED_BOARDS_DIR)
72 (os.path.join(abspath, preset_dir), presetInfo(os.path.join(abspath, preset_dir)))
73 for preset_dir in os.listdir(os.path.join(directory, const.PREDEFINED_BOARDS_DIR))
77 def presetInfo(preset_dir):
79 Return the preset-relevant info contined into the project_file.
81 preset_info = pickle.loads(open(os.path.join(preset_dir, "project.bertos"), "r").read())
83 description = open(os.path.join(preset_dir, "description"), "r").read()
85 # No description file found.
88 "CPU_NAME": preset_info.get("CPU_NAME"),
89 "SELECTED_FREQ": preset_info.get("SELECTED_FREQ"),
90 "WIZARD_VERSION": preset_info.get("WIZARD_VERSION", None),
91 "PRESET_NAME": preset_info.get("PROJECT_NAME"),
92 "PRESET_DESCRIPTION": description.decode("utf-8"),
96 def mergeSources(srcdir, new_sources, old_sources):
97 # The current mergeSources function provide only a raw copy of the sources in the
100 # TODO: implement the three way merge algorithm
102 shutil.rmtree(srcdir, True)
103 copytree.copytree(os.path.join(new_sources, "bertos"), srcdir, ignore_list=const.IGNORE_LIST)
105 def projectFileGenerator(project_info):
106 directory = project_info.info("PROJECT_PATH")
109 for module, information in project_info.info("MODULES").items():
110 if information["enabled"]:
111 enabled_modules.append(module)
112 project_data["ENABLED_MODULES"] = enabled_modules
113 if project_info.info("PRESET"):
114 # For presets save again the SOURCES_PATH into project file
115 project_data["PRESET"] = True
116 project_data["SOURCES_PATH"] = project_info.info("SOURCES_PATH")
118 # Use the local BeRTOS version instead of the original one
119 # project_data["SOURCES_PATH"] = project_info.info("SOURCES_PATH")
120 project_data["SOURCES_PATH"] = directory
121 project_data["PROJECT_NAME"] = project_info.info("PROJECT_NAME", os.path.basename(directory))
122 project_data["PROJECT_SRC_PATH"] = project_info.info("PROJECT_SRC_PATH")
123 project_data["TOOLCHAIN"] = project_info.info("TOOLCHAIN")
124 project_data["CPU_NAME"] = project_info.info("CPU_NAME")
125 project_data["SELECTED_FREQ"] = project_info.info("SELECTED_FREQ")
126 project_data["OUTPUT"] = project_info.info("OUTPUT")
127 project_data["WIZARD_VERSION"] = WIZARD_VERSION
128 return pickle.dumps(project_data)
130 def loadPlugin(plugin):
132 Returns the given plugin module.
134 return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
136 def versionFileGenerator(project_info, version_file):
137 version = bertosVersion(project_info.info("SOURCES_PATH"))
138 return version_file.replace('$version', version)
140 def userMkGenerator(project_info, makefile):
142 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
143 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
145 while makefile.find(key) != -1:
146 makefile = makefile.replace(key, mk_data[key])
149 def mkGenerator(project_info, makefile):
151 Generates the mk file for the current project.
154 mk_data["$pname"] = project_info.info("PROJECT_NAME")
155 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
156 cpu_mk_parameters = []
157 for key, value in project_info.info("CPU_INFOS").items():
158 if key.startswith(const.MK_PARAM_ID):
159 cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
160 mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
161 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
162 mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
163 mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
164 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
166 while makefile.find(key) != -1:
167 makefile = makefile.replace(key, mk_data[key])
170 def makefileGenerator(project_info, makefile):
172 Generate the Makefile for the current project.
174 # TODO write a general function that works for both the mk file and the Makefile
175 while makefile.find("$pname") != -1:
176 makefile = makefile.replace("$pname", project_info.info("PROJECT_NAME"))
179 def csrcGenerator(project_info):
180 modules = project_info.info("MODULES")
181 files = project_info.info("FILES")
182 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
186 # file to be included in CSRC variable
188 # file to be included in PCSRC variable
190 # files to be included in CPPASRC variable
192 # files to be included in CXXSRC variable
194 # files to be included in ASRC variable
196 # constants to be included at the beginning of the makefile
198 for module, information in modules.items():
199 module_files = set([])
200 dependency_files = set([])
203 hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
204 if information["enabled"]:
205 if "constants" in information:
206 constants.update(information["constants"])
207 cfiles, sfiles = findModuleFiles(module, project_info)
208 module_files |= set(cfiles)
209 asm_files |= set(sfiles)
210 for file in information["hw"]:
211 if file.endswith(".c"):
212 module_files |= set([hwdir + "/" + os.path.basename(file)])
213 for file_dependency in information["depends"] + tuple(files.keys()):
214 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
215 dependency_files |= set(dependencyCFiles)
216 asm_files |= set(dependencySFiles)
217 for file in module_files:
218 if not harvard or information.get("harvard", "both") == "both":
220 if harvard and "harvard" in information:
222 for file in dependency_files:
224 for file in project_info.info("CPU_INFOS")["C_SRC"]:
226 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
228 for file in asm_files:
230 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
232 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
234 for file in project_info.info("CPU_INFOS")["ASRC"]:
237 csrc = " \\\n\t".join(csrc) + " \\"
239 pcsrc = " \\\n\t".join(pcsrc) + " \\"
240 cppasrc = set(cppasrc)
241 cppasrc = " \\\n\t".join(cppasrc) + " \\"
243 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
245 asrc = " \\\n\t".join(asrc) + " \\"
246 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + unicode(value) for key, value in constants.items()])
247 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
249 def findModuleFiles(module, project_info):
250 # Find the files related to the selected module
253 # .c files related to the module and the cpu architecture
254 for filename, path in project_info.searchFiles(module + ".c"):
255 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
256 path = replaceSeparators(path)
257 cfiles.append(path + "/" + filename)
258 # .s files related to the module and the cpu architecture
259 for filename, path in project_info.searchFiles(module + ".s") + \
260 project_info.searchFiles(module + ".S"):
261 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
262 path = replaceSeparators(path)
263 sfiles.append(path + "/" + filename)
264 # .c and .s files related to the module and the cpu tags
265 tags = project_info.info("CPU_INFOS")["CPU_TAGS"]
267 # Awful, but secure check for version
268 # TODO: split me in a method/function
270 version_string = bertosVersion(project_info.info("SOURCES_PATH"))
271 version_list = [int(i) for i in version_string.split()[-1].split('.')]
272 if version_list < [2, 5]:
273 # For older versions of BeRTOS add the toolchain to the tags
274 tags.append(project_info.info("CPU_INFOS")["TOOLCHAIN"])
276 # If the version file hasn't a valid version number do nothing
280 for filename, path in project_info.searchFiles(module + "_" + tag + ".c"):
281 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
283 path = replaceSeparators(path)
284 cfiles.append(path + "/" + filename)
285 for filename, path in project_info.searchFiles(module + "_" + tag + ".s") + \
286 project_info.searchFiles(module + "_" + tag + ".S"):
287 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
288 path = replaceSeparators(path)
289 sfiles.append(path + "/" + filename)
290 return cfiles, sfiles
292 def replaceSeparators(path):
294 Replace the separators in the given path with unix standard separator.
297 while path.find(os.sep) != -1:
298 path = path.replace(os.sep, "/")
302 path = os.environ["PATH"]
304 path = path.split(";")
306 path = path.split(":")
309 def findToolchains(path_list):
311 for element in path_list:
312 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
313 toolchains.append(toolchain)
314 return list(set(toolchains))
316 def getToolchainInfo(output):
318 expr = re.compile("Target: .*")
319 target = expr.findall(output)
321 info["target"] = target[0].split("Target: ")[1]
322 expr = re.compile("gcc version [0-9,.]*")
323 version = expr.findall(output)
324 if len(version) == 1:
325 info["version"] = version[0].split("gcc version ")[1]
326 expr = re.compile("gcc version [0-9,.]* \(.*\)")
327 build = expr.findall(output)
329 build = build[0].split("gcc version ")[1]
330 build = build[build.find("(") + 1 : build.find(")")]
331 info["build"] = build
332 expr = re.compile("Configured with: .*")
333 configured = expr.findall(output)
334 if len(configured) == 1:
335 info["configured"] = configured[0].split("Configured with: ")[1]
336 expr = re.compile("Thread model: .*")
337 thread = expr.findall(output)
339 info["thread"] = thread[0].split("Thread model: ")[1]
342 def getToolchainName(toolchain_info):
343 name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
346 def getTagSet(cpu_info):
349 tag_set |= set([cpu["CPU_NAME"]])
350 tag_set |= set(cpu["CPU_TAGS"])
351 tag_set |= set([cpu["TOOLCHAIN"]])
355 def getInfos(definition):
357 D.update(const.CPU_DEF)
358 def include(filename, dict = D, directory=definition[1]):
359 execfile(directory + "/" + filename, {}, D)
360 D["include"] = include
361 include(definition[0], D)
362 D["CPU_NAME"] = definition[0].split(".")[0]
363 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
367 def getCommentList(string):
368 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
369 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
372 def loadModuleDefinition(first_comment):
374 module_definition = {}
375 for num, line in enumerate(first_comment):
376 index = line.find("$WIZ$")
380 exec line[index + len("$WIZ$ "):] in {}, module_definition
382 raise ParseError(num, line[index:])
383 elif line.find("\\brief") != -1:
384 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
386 if "module_name" in module_definition:
387 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
388 del module_definition[const.MODULE_DEFINITION["module_name"]]
389 module_dict[module_name] = {}
390 if const.MODULE_DEFINITION["module_depends"] in module_definition:
391 depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
392 del module_definition[const.MODULE_DEFINITION["module_depends"]]
393 if type(depends) == str:
395 module_dict[module_name]["depends"] = depends
397 module_dict[module_name]["depends"] = ()
398 if const.MODULE_DEFINITION["module_configuration"] in module_definition:
399 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
400 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
402 module_dict[module_name]["configuration"] = ""
403 if "module_description" in module_definition:
404 module_dict[module_name]["description"] = module_definition["module_description"]
405 del module_definition["module_description"]
406 if const.MODULE_DEFINITION["module_harvard"] in module_definition:
407 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
408 module_dict[module_name]["harvard"] = harvard
409 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
410 if const.MODULE_DEFINITION["module_hw"] in module_definition:
411 hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
412 del module_definition[const.MODULE_DEFINITION["module_hw"]]
415 module_dict[module_name]["hw"] = hw
417 module_dict[module_name]["hw"] = ()
418 if const.MODULE_DEFINITION["module_supports"] in module_definition:
419 supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
420 del module_definition[const.MODULE_DEFINITION["module_supports"]]
421 module_dict[module_name]["supports"] = supports
422 module_dict[module_name]["constants"] = module_definition
423 module_dict[module_name]["enabled"] = False
424 return to_be_parsed, module_dict
426 def isSupported(project, module=None, property_id=None):
427 if not module and property_id:
428 item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
430 item = project.info("MODULES")[module]
431 tag_dict = project.info("ALL_CPU_TAGS")
432 if "supports" in item:
433 support_string = item["supports"]
436 exec "supported = " + support_string in tag_dict, supported
438 raise SupportedException(support_string)
439 return supported["supported"]
443 def loadDefineLists(comment_list):
445 for comment in comment_list:
446 for num, line in enumerate(comment):
447 index = line.find("$WIZ$")
450 exec line[index + len("$WIZ$ "):] in {}, define_list
452 raise ParseError(num, line[index:])
453 for key, value in define_list.items():
454 if type(value) == str:
455 define_list[key] = (value,)
458 def getDescriptionInformations(comment):
460 Take the doxygen comment and strip the wizard informations, returning the tuple
461 (comment, wizard_information)
466 for num, line in enumerate(comment):
467 index = line.find("$WIZ$")
470 brief += line[:index].strip()
472 description += " " + line[:index]
474 exec line[index + len("$WIZ$ "):] in {}, information
476 raise ParseError(num, line[index:])
479 brief += line.strip()
481 description += " " + line
482 description = description.strip()
483 return brief.strip(), description.strip(), information
485 def getDefinitionBlocks(text):
487 Take a text and return a list of tuple (description, name-value).
490 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
491 for match in block_tmp:
492 # Only the first element is needed
493 comment = match.group(1)
494 define = match.group(2)
495 start = match.start()
496 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
497 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
498 comment = match.group(1)
499 define = match.group(2)
500 start = match.start()
501 block.append(([comment], define, start))
502 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
503 comment = match.group(2)
504 define = match.group(1)
505 start = match.start()
506 block.append(([comment], define, start))
509 def formatParamNameValue(text):
511 Take the given string and return a tuple with the name of the parameter in the first position
512 and the value in the second.
514 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
517 def loadConfigurationInfos(path):
519 Return the module configurations found in the given file as a dict with the
520 parameter name as key and a dict containig the fields above as value:
521 "value": the value of the parameter
522 "description": the description of the parameter
523 "informations": a dict containig optional informations:
524 "type": "int" | "boolean" | "enum"
525 "min": the minimum value for integer parameters
526 "max": the maximum value for integer parameters
527 "long": boolean indicating if the num is a long
528 "unsigned": boolean indicating if the num is an unsigned
529 "value_list": the name of the enum for enum parameters
530 "conditional_deps": the list of conditional dependencies for boolean parameters
532 configuration_infos = {}
533 configuration_infos["paramlist"] = []
534 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
535 name, value = formatParamNameValue(define)
536 brief, description, informations = getDescriptionInformations(comment)
537 configuration_infos["paramlist"].append((start, name))
538 configuration_infos[name] = {}
539 configuration_infos[name]["value"] = value
540 configuration_infos[name]["informations"] = informations
541 if not "type" in configuration_infos[name]["informations"]:
542 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
543 if ("type" in configuration_infos[name]["informations"] and
544 configuration_infos[name]["informations"]["type"] == "int" and
545 configuration_infos[name]["value"].find("L") != -1):
546 configuration_infos[name]["informations"]["long"] = True
547 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
548 if ("type" in configuration_infos[name]["informations"] and
549 configuration_infos[name]["informations"]["type"] == "int" and
550 configuration_infos[name]["value"].find("U") != -1):
551 configuration_infos[name]["informations"]["unsigned"] = True
552 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
553 if "conditional_deps" in configuration_infos[name]["informations"]:
554 if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
555 type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
556 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
557 elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
560 configuration_infos[name]["informations"]["conditional_deps"] = ()
561 configuration_infos[name]["description"] = description
562 configuration_infos[name]["brief"] = brief
563 return configuration_infos
565 def updateConfigurationValues(def_conf, user_conf):
566 for param in def_conf["paramlist"]:
567 if param[1] in user_conf and "value" in user_conf[param[1]]:
568 def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
571 def findParameterType(parameter):
572 if "value_list" in parameter["informations"]:
574 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
577 def sub(string, parameter, value):
579 Substitute the given value at the given parameter define in the given string
581 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
583 def isInt(informations):
585 Return True if the value is a simple int.
587 if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
592 def isLong(informations):
594 Return True if the value is a long.
596 if "long" in informations and informations["long"] and "unsigned" not in informations:
601 def isUnsigned(informations):
603 Return True if the value is an unsigned.
605 if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
610 def isUnsignedLong(informations):
612 Return True if the value is an unsigned long.
614 if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
619 class ParseError(Exception):
620 def __init__(self, line_number, line):
621 Exception.__init__(self)
622 self.line_number = line_number
625 class SupportedException(Exception):
626 def __init__(self, support_string):
627 Exception.__init__(self)
628 self.support_string = support_string