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["TOOLCHAIN"] = project_info.info("TOOLCHAIN")
123 project_data["CPU_NAME"] = project_info.info("CPU_NAME")
124 project_data["SELECTED_FREQ"] = project_info.info("SELECTED_FREQ")
125 project_data["OUTPUT"] = project_info.info("OUTPUT")
126 project_data["WIZARD_VERSION"] = WIZARD_VERSION
127 return pickle.dumps(project_data)
129 def loadPlugin(plugin):
131 Returns the given plugin module.
133 return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
135 def versionFileGenerator(project_info, version_file):
136 version = bertosVersion(project_info.info("SOURCES_PATH"))
137 return version_file.replace('$version', version)
139 def userMkGenerator(project_info, makefile):
141 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
142 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
144 while makefile.find(key) != -1:
145 makefile = makefile.replace(key, mk_data[key])
148 def mkGenerator(project_info, makefile):
150 Generates the mk file for the current project.
153 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
154 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
155 cpu_mk_parameters = []
156 for key, value in project_info.info("CPU_INFOS").items():
157 if key.startswith(const.MK_PARAM_ID):
158 cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
159 mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
160 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
161 mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
162 mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
163 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
165 while makefile.find(key) != -1:
166 makefile = makefile.replace(key, mk_data[key])
169 def makefileGenerator(project_info, makefile):
171 Generate the Makefile for the current project.
173 # TODO write a general function that works for both the mk file and the Makefile
174 while makefile.find("$pname") != -1:
175 makefile = makefile.replace("$pname", os.path.basename(project_info.info("PROJECT_PATH")))
178 def csrcGenerator(project_info):
179 modules = project_info.info("MODULES")
180 files = project_info.info("FILES")
181 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
185 # file to be included in CSRC variable
187 # file to be included in PCSRC variable
189 # files to be included in CPPASRC variable
191 # files to be included in CXXSRC variable
193 # files to be included in ASRC variable
195 # constants to be included at the beginning of the makefile
197 for module, information in modules.items():
198 module_files = set([])
199 dependency_files = set([])
202 hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
203 if information["enabled"]:
204 if "constants" in information:
205 constants.update(information["constants"])
206 cfiles, sfiles = findModuleFiles(module, project_info)
207 module_files |= set(cfiles)
208 asm_files |= set(sfiles)
209 for file in information["hw"]:
210 if file.endswith(".c"):
211 module_files |= set([hwdir + "/" + os.path.basename(file)])
212 for file_dependency in information["depends"] + tuple(files.keys()):
213 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
214 dependency_files |= set(dependencyCFiles)
215 asm_files |= set(dependencySFiles)
216 for file in module_files:
217 if not harvard or information.get("harvard", "both") == "both":
219 if harvard and "harvard" in information:
221 for file in dependency_files:
223 for file in project_info.info("CPU_INFOS")["C_SRC"]:
225 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
227 for file in asm_files:
229 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
231 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
233 for file in project_info.info("CPU_INFOS")["ASRC"]:
236 csrc = " \\\n\t".join(csrc) + " \\"
238 pcsrc = " \\\n\t".join(pcsrc) + " \\"
239 cppasrc = set(cppasrc)
240 cppasrc = " \\\n\t".join(cppasrc) + " \\"
242 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
244 asrc = " \\\n\t".join(asrc) + " \\"
245 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + unicode(value) for key, value in constants.items()])
246 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
248 def findModuleFiles(module, project_info):
249 # Find the files related to the selected module
252 # .c files related to the module and the cpu architecture
253 for filename, path in project_info.searchFiles(module + ".c"):
254 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
255 path = replaceSeparators(path)
256 cfiles.append(path + "/" + filename)
257 # .s files related to the module and the cpu architecture
258 for filename, path in project_info.searchFiles(module + ".s") + \
259 project_info.searchFiles(module + ".S"):
260 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
261 path = replaceSeparators(path)
262 sfiles.append(path + "/" + filename)
263 # .c and .s files related to the module and the cpu tags
264 tags = project_info.info("CPU_INFOS")["CPU_TAGS"]
266 # Awful, but secure check for version
267 # TODO: split me in a method/function
269 version_string = bertosVersion(project_info.info("SOURCES_PATH"))
270 version_list = [int(i) for i in version_string.split()[-1].split('.')]
271 if version_list < [2, 5]:
272 # For older versions of BeRTOS add the toolchain to the tags
273 tags.append(project_info.info("CPU_INFOS")["TOOLCHAIN"])
275 # If the version file hasn't a valid version number do nothing
279 for filename, path in project_info.searchFiles(module + "_" + tag + ".c"):
280 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
282 path = replaceSeparators(path)
283 cfiles.append(path + "/" + filename)
284 for filename, path in project_info.searchFiles(module + "_" + tag + ".s") + \
285 project_info.searchFiles(module + "_" + tag + ".S"):
286 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
287 path = replaceSeparators(path)
288 sfiles.append(path + "/" + filename)
289 return cfiles, sfiles
291 def replaceSeparators(path):
293 Replace the separators in the given path with unix standard separator.
296 while path.find(os.sep) != -1:
297 path = path.replace(os.sep, "/")
301 path = os.environ["PATH"]
303 path = path.split(";")
305 path = path.split(":")
308 def findToolchains(path_list):
310 for element in path_list:
311 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
312 toolchains.append(toolchain)
313 return list(set(toolchains))
315 def getToolchainInfo(output):
317 expr = re.compile("Target: .*")
318 target = expr.findall(output)
320 info["target"] = target[0].split("Target: ")[1]
321 expr = re.compile("gcc version [0-9,.]*")
322 version = expr.findall(output)
323 if len(version) == 1:
324 info["version"] = version[0].split("gcc version ")[1]
325 expr = re.compile("gcc version [0-9,.]* \(.*\)")
326 build = expr.findall(output)
328 build = build[0].split("gcc version ")[1]
329 build = build[build.find("(") + 1 : build.find(")")]
330 info["build"] = build
331 expr = re.compile("Configured with: .*")
332 configured = expr.findall(output)
333 if len(configured) == 1:
334 info["configured"] = configured[0].split("Configured with: ")[1]
335 expr = re.compile("Thread model: .*")
336 thread = expr.findall(output)
338 info["thread"] = thread[0].split("Thread model: ")[1]
341 def getToolchainName(toolchain_info):
342 name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
345 def getTagSet(cpu_info):
348 tag_set |= set([cpu["CPU_NAME"]])
349 tag_set |= set(cpu["CPU_TAGS"])
350 tag_set |= set([cpu["TOOLCHAIN"]])
354 def getInfos(definition):
356 D.update(const.CPU_DEF)
357 def include(filename, dict = D, directory=definition[1]):
358 execfile(directory + "/" + filename, {}, D)
359 D["include"] = include
360 include(definition[0], D)
361 D["CPU_NAME"] = definition[0].split(".")[0]
362 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
366 def getCommentList(string):
367 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
368 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
371 def loadModuleDefinition(first_comment):
373 module_definition = {}
374 for num, line in enumerate(first_comment):
375 index = line.find("$WIZ$")
379 exec line[index + len("$WIZ$ "):] in {}, module_definition
381 raise ParseError(num, line[index:])
382 elif line.find("\\brief") != -1:
383 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
385 if "module_name" in module_definition:
386 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
387 del module_definition[const.MODULE_DEFINITION["module_name"]]
388 module_dict[module_name] = {}
389 if const.MODULE_DEFINITION["module_depends"] in module_definition:
390 depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
391 del module_definition[const.MODULE_DEFINITION["module_depends"]]
392 if type(depends) == str:
394 module_dict[module_name]["depends"] = depends
396 module_dict[module_name]["depends"] = ()
397 if const.MODULE_DEFINITION["module_configuration"] in module_definition:
398 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
399 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
401 module_dict[module_name]["configuration"] = ""
402 if "module_description" in module_definition:
403 module_dict[module_name]["description"] = module_definition["module_description"]
404 del module_definition["module_description"]
405 if const.MODULE_DEFINITION["module_harvard"] in module_definition:
406 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
407 module_dict[module_name]["harvard"] = harvard
408 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
409 if const.MODULE_DEFINITION["module_hw"] in module_definition:
410 hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
411 del module_definition[const.MODULE_DEFINITION["module_hw"]]
414 module_dict[module_name]["hw"] = hw
416 module_dict[module_name]["hw"] = ()
417 if const.MODULE_DEFINITION["module_supports"] in module_definition:
418 supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
419 del module_definition[const.MODULE_DEFINITION["module_supports"]]
420 module_dict[module_name]["supports"] = supports
421 module_dict[module_name]["constants"] = module_definition
422 module_dict[module_name]["enabled"] = False
423 return to_be_parsed, module_dict
425 def isSupported(project, module=None, property_id=None):
426 if not module and property_id:
427 item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
429 item = project.info("MODULES")[module]
430 tag_dict = project.info("ALL_CPU_TAGS")
431 if "supports" in item:
432 support_string = item["supports"]
435 exec "supported = " + support_string in tag_dict, supported
437 raise SupportedException(support_string)
438 return supported["supported"]
442 def loadDefineLists(comment_list):
444 for comment in comment_list:
445 for num, line in enumerate(comment):
446 index = line.find("$WIZ$")
449 exec line[index + len("$WIZ$ "):] in {}, define_list
451 raise ParseError(num, line[index:])
452 for key, value in define_list.items():
453 if type(value) == str:
454 define_list[key] = (value,)
457 def getDescriptionInformations(comment):
459 Take the doxygen comment and strip the wizard informations, returning the tuple
460 (comment, wizard_information)
465 for num, line in enumerate(comment):
466 index = line.find("$WIZ$")
469 brief += line[:index].strip()
471 description += " " + line[:index]
473 exec line[index + len("$WIZ$ "):] in {}, information
475 raise ParseError(num, line[index:])
478 brief += line.strip()
480 description += " " + line
481 description = description.strip()
482 return brief.strip(), description.strip(), information
484 def getDefinitionBlocks(text):
486 Take a text and return a list of tuple (description, name-value).
489 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
490 for match in block_tmp:
491 # Only the first element is needed
492 comment = match.group(1)
493 define = match.group(2)
494 start = match.start()
495 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
496 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
497 comment = match.group(1)
498 define = match.group(2)
499 start = match.start()
500 block.append(([comment], define, start))
501 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
502 comment = match.group(2)
503 define = match.group(1)
504 start = match.start()
505 block.append(([comment], define, start))
508 def formatParamNameValue(text):
510 Take the given string and return a tuple with the name of the parameter in the first position
511 and the value in the second.
513 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
516 def loadConfigurationInfos(path):
518 Return the module configurations found in the given file as a dict with the
519 parameter name as key and a dict containig the fields above as value:
520 "value": the value of the parameter
521 "description": the description of the parameter
522 "informations": a dict containig optional informations:
523 "type": "int" | "boolean" | "enum"
524 "min": the minimum value for integer parameters
525 "max": the maximum value for integer parameters
526 "long": boolean indicating if the num is a long
527 "unsigned": boolean indicating if the num is an unsigned
528 "value_list": the name of the enum for enum parameters
529 "conditional_deps": the list of conditional dependencies for boolean parameters
531 configuration_infos = {}
532 configuration_infos["paramlist"] = []
533 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
534 name, value = formatParamNameValue(define)
535 brief, description, informations = getDescriptionInformations(comment)
536 configuration_infos["paramlist"].append((start, name))
537 configuration_infos[name] = {}
538 configuration_infos[name]["value"] = value
539 configuration_infos[name]["informations"] = informations
540 if not "type" in configuration_infos[name]["informations"]:
541 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
542 if ("type" in configuration_infos[name]["informations"] and
543 configuration_infos[name]["informations"]["type"] == "int" and
544 configuration_infos[name]["value"].find("L") != -1):
545 configuration_infos[name]["informations"]["long"] = True
546 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
547 if ("type" in configuration_infos[name]["informations"] and
548 configuration_infos[name]["informations"]["type"] == "int" and
549 configuration_infos[name]["value"].find("U") != -1):
550 configuration_infos[name]["informations"]["unsigned"] = True
551 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
552 if "conditional_deps" in configuration_infos[name]["informations"]:
553 if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
554 type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
555 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
556 elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
559 configuration_infos[name]["informations"]["conditional_deps"] = ()
560 configuration_infos[name]["description"] = description
561 configuration_infos[name]["brief"] = brief
562 return configuration_infos
564 def updateConfigurationValues(def_conf, user_conf):
565 for param in def_conf["paramlist"]:
566 if param[1] in user_conf and "value" in user_conf[param[1]]:
567 def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
570 def findParameterType(parameter):
571 if "value_list" in parameter["informations"]:
573 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
576 def sub(string, parameter, value):
578 Substitute the given value at the given parameter define in the given string
580 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
582 def isInt(informations):
584 Return True if the value is a simple int.
586 if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
591 def isLong(informations):
593 Return True if the value is a long.
595 if "long" in informations and informations["long"] and "unsigned" not in informations:
600 def isUnsigned(informations):
602 Return True if the value is an unsigned.
604 if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
609 def isUnsignedLong(informations):
611 Return True if the value is an unsigned long.
613 if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
618 class ParseError(Exception):
619 def __init__(self, line_number, line):
620 Exception.__init__(self)
621 self.line_number = line_number
624 class SupportedException(Exception):
625 def __init__(self, support_string):
626 Exception.__init__(self)
627 self.support_string = support_string