Esempio n. 1
0
File: arm.py Progetto: MayAmmar/mbed
 def __init__(self,
              target,
              notify=None,
              macros=None,
              silent=False,
              extra_verbose=False,
              build_profile=None,
              build_dir=None):
     target.default_toolchain = "uARM"
     if int(target.build_tools_metadata["version"]) > 0:
         # At this point we already know that we want to use ARMC5+Microlib
         # so check for if they are supported For, AC6+Microlib we still
         # use ARMC6 class
         if not set(
             ("ARMC5", "uARM")).issubset(set(target.supported_toolchains)):
             raise NotSupportedException(
                 "ARM/uARM compiler support is required for ARM build")
     else:
         if not set(("ARM", "uARM")).intersection(
                 set(target.supported_toolchains)):
             raise NotSupportedException(
                 "ARM/uARM compiler support is required for ARM build")
     ARM.__init__(self,
                  target,
                  notify,
                  macros,
                  build_dir=build_dir,
                  build_profile=build_profile)
Esempio n. 2
0
 def __init__(
         self,
         target,
         notify=None,
         macros=None,
         build_profile=None,
         build_dir=None
 ):
     ARM.__init__(
         self,
         target,
         notify,
         macros,
         build_dir=build_dir,
         build_profile=build_profile
     )
     if int(target.build_tools_metadata["version"]) > 0:
         # check only for ARMC5 because ARM_STD means using ARMC5, and thus
         # supported_toolchains must include ARMC5
         if not set(target.supported_toolchains).intersection(
                 set(("ARMC5", "ARM"))
         ):
             raise NotSupportedException(
                 "ARM compiler 5 support is required for ARM build"
             )
     else:
         if not set(("ARM", "uARM")).intersection(set(
                 target.supported_toolchains
         )):
             raise NotSupportedException(
                 "ARM/uARM compiler support is required for ARM build"
             )
Esempio n. 3
0
def target(name, json_data):
    """Construct a target object"""
    if name.startswith("_"):
        raise Exception(
            "Invalid target name '%s' specified,"
            " target name should not start with '_'" % name
        )
    try:
        resolution_order = get_resolution_order(json_data, name, [])
    except KeyError as exc:
        raise_from(NotSupportedException(
            "target {} has an incomplete target definition".format(name)
        ), exc)
    resolution_order_names = [tgt for tgt, _ in resolution_order]
    return Target(
        name=name,
        json_data={key: value for key, value in json_data.items()
                   if key in resolution_order_names},
        resolution_order=resolution_order,
        resolution_order_names=resolution_order_names,
        build_tools_metadata=json_data.get(
            "__build_tools_metadata__",
            default_build_tools_metadata
        )
    )
Esempio n. 4
0
    def __init__(self, target, *args, **kwargs):
        mbedToolchain.__init__(self, target, *args, **kwargs)

        if not set(
            ("ARM", "ARMC6")).intersection(set(target.supported_toolchains)):
            raise NotSupportedException(
                "ARM/ARMC6 compiler support is required for ARMC6 build")

        if target.core.lower().endswith("fd"):
            self.flags['common'].append("-mcpu=%s" % target.core.lower()[:-2])
            self.flags['ld'].append("--cpu=%s" % target.core.lower()[:-2])
        elif target.core.lower().endswith("f"):
            self.flags['common'].append("-mcpu=%s" % target.core.lower()[:-1])
            self.flags['ld'].append("--cpu=%s" % target.core.lower()[:-1])
        elif target.core.lower().endswith("ns"):
            self.flags['common'].append("-mcpu=%s" % target.core.lower()[:-3])
            self.flags['ld'].append("--cpu=%s" % target.core.lower()[:-3])
        else:
            self.flags['common'].append("-mcpu=%s" % target.core.lower())
            self.flags['ld'].append("--cpu=%s" % target.core.lower())

        if target.core == "Cortex-M4F":
            self.flags['common'].append("-mfpu=fpv4-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
        elif target.core == "Cortex-M7F":
            self.flags['common'].append("-mfpu=fpv5-sp-d16")
            self.flags['common'].append("-mfloat-abi=softfp")
        elif target.core == "Cortex-M7FD":
            self.flags['common'].append("-mfpu=fpv5-d16")
            self.flags['common'].append("-mfloat-abi=softfp")
        elif target.core.startswith("Cortex-M23"):
            self.flags['common'].append("-march=armv8-m.base")
        elif target.core.startswith("Cortex-M33"):
            self.flags['common'].append("-march=armv8-m.main")

        if target.core == "Cortex-M23" or target.core == "Cortex-M33":
            self.flags['common'].append("-mcmse")

        asm_cpu = {
            "Cortex-M0+": "Cortex-M0",
            "Cortex-M4F": "Cortex-M4.fp",
            "Cortex-M7F": "Cortex-M7.fp.sp",
            "Cortex-M7FD": "Cortex-M7.fp.dp",
            "Cortex-M23-NS": "Cortex-M23",
            "Cortex-M33-NS": "Cortex-M33"
        }.get(target.core, target.core)

        self.flags['asm'].append("--cpu=%s" % asm_cpu)

        self.cc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                   self.flags['common'] + self.flags['c'])
        self.cppc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                     self.flags['common'] + self.flags['cxx'])
        self.asm = [join(TOOLCHAIN_PATHS["ARMC6"], "armasm")
                    ] + self.flags['asm']
        self.ld = [join(TOOLCHAIN_PATHS["ARMC6"], "armlink")
                   ] + self.flags['ld']
        self.ar = [join(TOOLCHAIN_PATHS["ARMC6"], "armar")]
        self.elf2bin = join(TOOLCHAIN_PATHS["ARMC6"], "fromelf")
Esempio n. 5
0
 def __init__(self, target, notify=None, macros=None,
              silent=False, extra_verbose=False, build_profile=None,
              build_dir=None):
     ARM.__init__(self, target, notify, macros, silent,
                  build_dir=build_dir, extra_verbose=extra_verbose,
                  build_profile=build_profile)
     if not set(("ARM", "uARM")).intersection(set(target.supported_toolchains)):
         raise NotSupportedException("ARM/uARM compiler support is required for ARM build")
Esempio n. 6
0
    def __init__(self,
                 target,
                 notify=None,
                 macros=None,
                 build_profile=None,
                 build_dir=None,
                 coverage_patterns=None):
        mbedToolchain.__init__(self,
                               target,
                               notify,
                               macros,
                               build_dir=build_dir,
                               build_profile=build_profile)
        if target.core not in self.SUPPORTED_CORES:
            raise NotSupportedException(
                "this compiler does not support the core %s" % target.core)

        self.check_c_lib_supported(target, "arm")

        if (getattr(target, "default_toolchain", "ARM") == "uARM"
                or getattr(target, "c_lib", "std") == "small"):
            if "-DMBED_RTOS_SINGLE_THREAD" not in self.flags['common']:
                self.flags['common'].append("-DMBED_RTOS_SINGLE_THREAD")
            if "-D__MICROLIB" not in self.flags['common']:
                self.flags['common'].append("-D__MICROLIB")
            if "--library_type=microlib" not in self.flags['ld']:
                self.flags['ld'].append("--library_type=microlib")
            if "--library_type=microlib" not in self.flags['common']:
                self.flags['common'].append("--library_type=microlib")

        self.check_and_add_minimal_printf(target)

        cpu = {
            "Cortex-M0+": "Cortex-M0plus",
            "Cortex-M4F": "Cortex-M4.fp.sp",
            "Cortex-M7F": "Cortex-M7.fp.sp",
            "Cortex-M7FD": "Cortex-M7.fp.dp"
        }.get(target.core, target.core)

        ARM_BIN = join(TOOLCHAIN_PATHS['ARM'], "bin")

        main_cc = join(ARM_BIN, "armcc")

        self.flags['common'] += ["--cpu=%s" % cpu]

        self.asm = [main_cc] + self.flags['common'] + self.flags['asm']
        self.cc = [main_cc] + self.flags['common'] + self.flags['c']
        self.cppc = ([main_cc] + self.flags['common'] + self.flags['c'] +
                     self.flags['cxx'])

        self.ld = [join(ARM_BIN, "armlink")] + self.flags['ld']

        self.ar = join(ARM_BIN, "armar")
        self.elf2bin = join(ARM_BIN, "fromelf")

        self.SHEBANG += " --cpu=%s" % cpu

        self.product_name = None
Esempio n. 7
0
    def __init__(self,
                 target,
                 notify=None,
                 macros=None,
                 build_profile=None,
                 build_dir=None):
        mbedToolchain.__init__(self,
                               target,
                               notify,
                               macros,
                               build_dir=build_dir,
                               build_profile=build_profile)
        if target.core not in self.SUPPORTED_CORES:
            raise NotSupportedException(
                "this compiler does not support the core %s" % target.core)

        if getattr(target, "default_toolchain", "ARM") == "uARM":
            if "-DMBED_RTOS_SINGLE_THREAD" not in self.flags['common']:
                self.flags['common'].append("-DMBED_RTOS_SINGLE_THREAD")
            if "-D__MICROLIB" not in self.flags['common']:
                self.flags['common'].append("-D__MICROLIB")
            if "--library_type=microlib" not in self.flags['ld']:
                self.flags['ld'].append("--library_type=microlib")
            if "--library_type=microlib" not in self.flags['common']:
                self.flags['common'].append("--library_type=microlib")

        if target.core == "Cortex-M0+":
            cpu = "Cortex-M0"
        elif target.core == "Cortex-M4F":
            cpu = "Cortex-M4.fp"
        elif target.core == "Cortex-M7FD":
            cpu = "Cortex-M7.fp.dp"
        elif target.core == "Cortex-M7F":
            cpu = "Cortex-M7.fp.sp"
        else:
            cpu = target.core

        ARM_BIN = join(TOOLCHAIN_PATHS['ARM'], "bin")
        ARM_INC = join(TOOLCHAIN_PATHS['ARM'], "include")

        main_cc = join(ARM_BIN, "armcc")

        self.flags['common'] += ["--cpu=%s" % cpu]

        self.asm = [main_cc] + self.flags['common'] + self.flags['asm']
        self.cc = [main_cc] + self.flags['common'] + self.flags['c']
        self.cppc = [
            main_cc
        ] + self.flags['common'] + self.flags['c'] + self.flags['cxx']

        self.ld = [join(ARM_BIN, "armlink")] + self.flags['ld']

        self.ar = join(ARM_BIN, "armar")
        self.elf2bin = join(ARM_BIN, "fromelf")

        self.SHEBANG += " --cpu=%s" % cpu
Esempio n. 8
0
def target(name, json_data):
    """Construct a target object"""
    try:
        resolution_order = get_resolution_order(json_data, name, [])
    except KeyError as exc:
        raise_from(NotSupportedException(
            "target {} has an incomplete target definition".format(name)
        ), exc)
    resolution_order_names = [tgt for tgt, _ in resolution_order]
    return Target(name=name,
                  json_data={key: value for key, value in json_data.items()
                             if key in resolution_order_names},
                  resolution_order=resolution_order,
                  resolution_order_names=resolution_order_names)
Esempio n. 9
0
    def generate(self):
        """Generate the .eww, .ewd, and .ewp files"""
        if not self.resources.linker_script:
            raise NotSupportedException("No linker script found.")
        srcs = self.resources.headers + self.resources.s_sources + \
               self.resources.c_sources + self.resources.cpp_sources + \
               self.resources.objects + self.libraries
        flags = self.flags
        c_flags = list(
            set(flags['common_flags'] + flags['c_flags'] + flags['cxx_flags']))
        # Flags set in template to be set by user in IDE
        template = ["--vla", "--no_static_destruction"]
        # Flag invalid if set in template
        # Optimizations are also set in template
        invalid_flag = lambda x: x in template or re.match(
            "-O(\d|time|n|hz?)", x)
        flags['c_flags'] = [flag for flag in c_flags if not invalid_flag(flag)]

        try:
            debugger = DeviceCMSIS(self.target).debug.replace('-', '').upper()
        except TargetNotSupportedException:
            debugger = "CMSISDAP"

        trustZoneMode = 0
        if self.toolchain.target.core.endswith("-NS"):
            trustZoneMode = 1

        ctx = {
            'name':
            self.project_name,
            'groups':
            self.iar_groups(self.format_src(srcs)),
            'linker_script':
            self.format_file(self.resources.linker_script),
            'include_paths':
            [self.format_file(src) for src in self.resources.inc_dirs],
            'device':
            self.iar_device(),
            'ewp':
            sep + self.project_name + ".ewp",
            'debugger':
            debugger,
            'trustZoneMode':
            trustZoneMode,
        }
        ctx.update(flags)

        self.gen_file('iar/eww.tmpl', ctx, self.project_name + ".eww")
        self.gen_file('iar/ewd.tmpl', ctx, self.project_name + ".ewd")
        self.gen_file('iar/ewp.tmpl', ctx, self.project_name + ".ewp")
Esempio n. 10
0
    def __init__(self,
                 target,
                 notify=None,
                 macros=None,
                 silent=False,
                 extra_verbose=False,
                 build_profile=None,
                 build_dir=None):
        mbedToolchain.__init__(self,
                               target,
                               notify,
                               macros,
                               silent,
                               build_dir=build_dir,
                               extra_verbose=extra_verbose,
                               build_profile=build_profile)
        if target.core not in self.SUPPORTED_CORES:
            raise NotSupportedException(
                "this compiler does not support the core %s" % target.core)

        if target.core == "Cortex-M0+":
            cpu = "Cortex-M0"
        elif target.core == "Cortex-M4F":
            cpu = "Cortex-M4.fp"
        elif target.core == "Cortex-M7FD":
            cpu = "Cortex-M7.fp.dp"
        elif target.core == "Cortex-M7F":
            cpu = "Cortex-M7.fp.sp"
        else:
            cpu = target.core

        ARM_BIN = join(TOOLCHAIN_PATHS['ARM'], "bin")
        ARM_INC = join(TOOLCHAIN_PATHS['ARM'], "include")

        main_cc = join(ARM_BIN, "armcc")

        self.flags['common'] += ["--cpu=%s" % cpu]

        self.asm = [main_cc] + self.flags['common'] + self.flags['asm']
        self.cc = [main_cc] + self.flags['common'] + self.flags['c']
        self.cppc = [
            main_cc
        ] + self.flags['common'] + self.flags['c'] + self.flags['cxx']

        self.ld = [join(ARM_BIN, "armlink")] + self.flags['ld']

        self.ar = join(ARM_BIN, "armar")
        self.elf2bin = join(ARM_BIN, "fromelf")

        self.SHEBANG += " --cpu=%s" % cpu
Esempio n. 11
0
 def __init__(self,
              target,
              notify=None,
              macros=None,
              build_profile=None,
              build_dir=None):
     ARM.__init__(self,
                  target,
                  notify,
                  macros,
                  build_dir=build_dir,
                  build_profile=build_profile)
     if "ARM" not in target.supported_toolchains:
         raise NotSupportedException(
             "ARM compiler support is required for ARM build")
Esempio n. 12
0
    def compile_output(self, output=[]):
        _rc = output[0]
        _stderr = output[1]
        command = output[2]

        # Parse output for Warnings and Errors
        self.parse_output(_stderr)
        self.debug("Return: %s"% _rc)
        for error_line in _stderr.splitlines():
            self.debug("Output: %s"% error_line)

        # Check return code
        if _rc != 0:
            if self.is_not_supported_error(_stderr):
                raise NotSupportedException(_stderr)
            else:
                raise ToolException(_stderr)
Esempio n. 13
0
    def __init__(self, target, *args, **kwargs):
        mbedToolchain.__init__(self, target, *args, **kwargs)
        if target.core not in self.SUPPORTED_CORES:
            raise NotSupportedException(
                "this compiler does not support the core %s" % target.core)

        if not set(
            ("ARM", "ARMC6")).intersection(set(target.supported_toolchains)):
            raise NotSupportedException(
                "ARM/ARMC6 compiler support is required for ARMC6 build")

        if target.core.lower().endswith("fd"):
            self.flags['common'].append("-mcpu=%s" % target.core.lower()[:-2])
            self.flags['ld'].append("--cpu=%s" % target.core.lower()[:-2])
            self.SHEBANG += " -mcpu=%s" % target.core.lower()[:-2]
        elif target.core.lower().endswith("f"):
            self.flags['common'].append("-mcpu=%s" % target.core.lower()[:-1])
            self.flags['ld'].append("--cpu=%s" % target.core.lower()[:-1])
            self.SHEBANG += " -mcpu=%s" % target.core.lower()[:-1]
        elif target.core.lower().endswith("ns"):
            self.flags['common'].append("-mcpu=%s" % target.core.lower()[:-3])
            self.flags['ld'].append("--cpu=%s" % target.core.lower()[:-3])
            self.SHEBANG += " -mcpu=%s" % target.core.lower()[:-3]
        else:
            self.flags['common'].append("-mcpu=%s" % target.core.lower())
            self.flags['ld'].append("--cpu=%s" % target.core.lower())
            self.SHEBANG += " -mcpu=%s" % target.core.lower()

        if target.core == "Cortex-M4F":
            self.flags['common'].append("-mfpu=fpv4-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
        elif target.core == "Cortex-M7F":
            self.flags['common'].append("-mfpu=fpv5-sp-d16")
            self.flags['common'].append("-mfloat-abi=softfp")
        elif target.core == "Cortex-M7FD":
            self.flags['common'].append("-mfpu=fpv5-d16")
            self.flags['common'].append("-mfloat-abi=softfp")
        elif target.core.startswith("Cortex-M23"):
            self.flags['common'].append("-march=armv8-m.base")
        elif target.core.startswith("Cortex-M33"):
            self.flags['common'].append("-march=armv8-m.main")

        if target.core == "Cortex-M23" or target.core == "Cortex-M33":
            self.flags['common'].append("-mcmse")

        # Create Secure library
        if ((target.core == "Cortex-M23" or self.target.core == "Cortex-M33")
                and kwargs.get('build_dir', False)):
            build_dir = kwargs['build_dir']
            secure_file = join(build_dir, "cmse_lib.o")
            self.flags["ld"] += ["--import_cmse_lib_out=%s" % secure_file]
        # Add linking time preprocessor macro __DOMAIN_NS
        if target.core == "Cortex-M23-NS" or self.target.core == "Cortex-M33-NS":
            define_string = self.make_ld_define("__DOMAIN_NS", 1)
            self.flags["ld"].append(define_string)

        asm_cpu = {
            "Cortex-M0+": "Cortex-M0",
            "Cortex-M4F": "Cortex-M4.fp",
            "Cortex-M7F": "Cortex-M7.fp.sp",
            "Cortex-M7FD": "Cortex-M7.fp.dp",
            "Cortex-M23-NS": "Cortex-M23",
            "Cortex-M33-NS": "Cortex-M33"
        }.get(target.core, target.core)

        self.flags['asm'].append("--cpu=%s" % asm_cpu)

        self.cc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                   self.flags['common'] + self.flags['c'])
        self.cppc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                     self.flags['common'] + self.flags['cxx'])
        self.asm = [join(TOOLCHAIN_PATHS["ARMC6"], "armasm")
                    ] + self.flags['asm']
        self.ld = [join(TOOLCHAIN_PATHS["ARMC6"], "armlink")
                   ] + self.flags['ld']
        self.ar = [join(TOOLCHAIN_PATHS["ARMC6"], "armar")]
        self.elf2bin = join(TOOLCHAIN_PATHS["ARMC6"], "fromelf")
Esempio n. 14
0
    def generate(self):
        """
        Generate the .project and .cproject files.
        """
        if not self.resources.linker_script:
            raise NotSupportedException("No linker script found.")

        self.resources.win_to_unix()

        # TODO: use some logger to display additional info if verbose

        libraries = []
        # print 'libraries'
        # print self.resources.libraries
        for lib in self.libraries:
            l, _ = splitext(basename(lib))
            libraries.append(l[3:])

        self.system_libraries = ['stdc++', 'supc++', 'm', 'c', 'gcc', 'nosys']

        # Read in all profiles, we'll extract compiler options.
        profiles = self.get_all_profiles()

        profile_ids = [s.lower() for s in profiles]
        profile_ids.sort()

        # TODO: get the list from existing .cproject
        build_folders = [s.capitalize() for s in profile_ids]
        build_folders.append('BUILD')
        # print build_folders

        objects = [self.filter_dot(s) for s in self.resources.objects]
        for bf in build_folders:
            objects = [o for o in objects if not o.startswith(bf + '/')]
        # print 'objects'
        # print objects

        self.compute_exclusions()

        self.include_path = [
            self.filter_dot(s) for s in self.resources.inc_dirs
        ]

        self.as_defines = self.toolchain.get_symbols(True)
        self.c_defines = self.toolchain.get_symbols()
        self.cpp_defines = self.c_defines

        self.ld_script = self.filter_dot(self.resources.linker_script)

        self.options = {}
        profile_ids.remove('develop')
        for id in profile_ids:

            # There are 4 categories of options, a category common too
            # all tools and a specific category for each of the tools.
            opts = {}
            opts['common'] = {}
            opts['as'] = {}
            opts['c'] = {}
            opts['cpp'] = {}
            opts['ld'] = {}

            opts['id'] = id
            opts['name'] = opts['id'].capitalize()

            print

            profile = profiles[id]

            # A small hack, do not bother with src_path again,
            # pass an empty string to avoid crashing.
            src_paths = ['']
            target_name = self.toolchain.target.name
            toolchain = prepare_toolchain(src_paths,
                                          "",
                                          target_name,
                                          self.TOOLCHAIN,
                                          build_profile=[profile])

            # Hack to fill in build_dir
            toolchain.build_dir = self.toolchain.build_dir

            flags = self.toolchain_flags(toolchain)

            # Most GNU ARM Eclipse options have a parent,
            # either debug or release.
            if '-O0' in flags['common_flags'] or '-Og' in flags['common_flags']:
                opts['parent_id'] = 'debug'
            else:
                opts['parent_id'] = 'release'

            self.process_options(opts, flags, libraries)

            opts['as']['defines'] = self.as_defines
            opts['c']['defines'] = self.c_defines
            opts['cpp']['defines'] = self.cpp_defines

            opts['common']['include_paths'] = self.include_path
            opts['common']['excluded_folders'] = '|'.join(
                self.excluded_folders)
            self.excluded_folders = [
                item.replace("\\", "/") for item in self.excluded_folders
            ]

            opts['ld']['library_paths'] = [
                self.filter_dot(s) for s in self.resources.lib_dirs
            ]

            opts['ld']['object_files'] = objects
            opts['ld']['user_libraries'] = libraries
            opts['ld']['system_libraries'] = self.system_libraries
            opts['ld']['script'] = "linker-script-%s.ld" % id
            opts['cpp_cmd'] = " ".join(toolchain.preproc)

            # Unique IDs used in multiple places.
            # Those used only once are implemented with {{u.id}}.
            u = UID()
            uid = {}
            uid['config'] = u.id
            uid['tool_c_compiler'] = u.id
            uid['tool_c_compiler_input'] = u.id
            uid['tool_cpp_compiler'] = u.id
            uid['tool_cpp_compiler_input'] = u.id

            opts['uid'] = uid

            self.options[id] = opts

        jinja_ctx = {
            'name': self.project_name,
            'ld_script': self.ld_script,

            # Compiler & linker command line options
            'options': self.options,

            # Must be an object with an `id` property, which
            # will be called repeatedly, to generate multiple UIDs.
            'u': u,
        }

        self.gen_file('mcuxpresso/.project.tmpl',
                      jinja_ctx,
                      '.project',
                      trim_blocks=True,
                      lstrip_blocks=True)
        self.gen_file('mcuxpresso/{0}_cproject.tmpl'.format(target_name),
                      jinja_ctx,
                      '.cproject',
                      trim_blocks=True,
                      lstrip_blocks=True)
        self.gen_file('mcuxpresso/makefile.targets.tmpl',
                      jinja_ctx,
                      'makefile.targets',
                      trim_blocks=True,
                      lstrip_blocks=True)
        self.gen_file_nonoverwrite('mcuxpresso/mbedignore.tmpl', jinja_ctx,
                                   '.mbedignore')

        print('Done. Import the \'{0}\' project in MCUXpresso.'.format(
            self.project_name))
Esempio n. 15
0
    def process_options(self, opts, flags_in, libraries):
        """
        CDT managed projects store lots of build options in separate
        variables, with separate IDs in the .cproject file.
        When the CDT build is started, all these options are brought
        together to compose the compiler and linker command lines.

        Here the process is reversed, from the compiler and linker
        command lines, the options are identified and various flags are
        set to control the template generation process.

        Once identified, the options are removed from the command lines.

        The options that were not identified are options that do not
        have CDT equivalents and will be passed in the 'Other options'
        categories.

        Although this process does not have a very complicated logic,
        given the large number of explicit configuration options
        used by the GNU ARM Eclipse managed build plug-in, it is tedious...
        """

        # Make a copy of the flags, to be one by one removed after processing.
        flags = copy.deepcopy(flags_in)

        # Initialise the 'last resort' options where all unrecognised
        # options will be collected.
        opts['as']['other'] = ''
        opts['c']['other'] = ''
        opts['cpp']['other'] = ''
        opts['ld']['other'] = ''

        MCPUS = {
            'Cortex-M0': {
                'mcpu': 'cortex-m0',
                'fpu_unit': None
            },
            'Cortex-M0+': {
                'mcpu': 'cortex-m0plus',
                'fpu_unit': None
            },
            'Cortex-M1': {
                'mcpu': 'cortex-m1',
                'fpu_unit': None
            },
            'Cortex-M3': {
                'mcpu': 'cortex-m3',
                'fpu_unit': None
            },
            'Cortex-M4': {
                'mcpu': 'cortex-m4',
                'fpu_unit': None
            },
            'Cortex-M4F': {
                'mcpu': 'cortex-m4',
                'fpu_unit': 'fpv4spd16'
            },
            'Cortex-M7': {
                'mcpu': 'cortex-m7',
                'fpu_unit': None
            },
            'Cortex-M7F': {
                'mcpu': 'cortex-m7',
                'fpu_unit': 'fpv4spd16'
            },
            'Cortex-M7FD': {
                'mcpu': 'cortex-m7',
                'fpu_unit': 'fpv5d16'
            },
            'Cortex-A5': {
                'mcpu': 'cortex-a5',
                'fpu_unit': 'vfpv3'
            },
            'Cortex-A9': {
                'mcpu': 'cortex-a9',
                'fpu_unit': 'vfpv3'
            }
        }

        MCPU_NXP = {
            'cortex-m7': 'cm7',
            'cortex-m4': 'cm4',
            'cortex-m3': 'cm3',
            'cortex-m1': 'cm1',
            'cortex-m0': 'cm0',
            'cortex-m0.small-multiply': 'cm0.smallmul',
            'cortex-m0plus': 'cm0plus',
            'cortex-m0plus.small-multiply': 'cm0plus.smallmul'
        }

        # Remove options that are supplied by CDT
        self.remove_option(flags['common_flags'], '-c')
        self.remove_option(flags['common_flags'], '-MMD')

        # As 'plan B', get the CPU from the target definition.
        core = self.toolchain.target.core

        opts['common']['arm.target.family'] = None

        # cortex-m0, cortex-m0-small-multiply, cortex-m0plus,
        # cortex-m0plus-small-multiply, cortex-m1, cortex-m1-small-multiply,
        # cortex-m3, cortex-m4, cortex-m7.
        str = self.find_options(flags['common_flags'], '-mcpu=')
        if str != None:
            opts['common']['arm.target.family'] = str[len('-mcpu='):]
            opts['common']['arm.target.family_nxp'] = MCPU_NXP[
                str[len('-mcpu='):]]
            self.remove_option(flags['common_flags'], str)
            self.remove_option(flags['ld_flags'], str)
        else:
            if core not in MCPUS:
                raise NotSupportedException(
                    'Target core {0} not supported.'.format(core))
            opts['common']['arm.target.family'] = MCPUS[core]['mcpu']

        opts['common']['arm.target.arch'] = 'none'
        str = self.find_options(flags['common_flags'], '-march=')
        arch = str[len('-march='):]
        archs = {
            'armv6-m': 'armv6-m',
            'armv7-m': 'armv7-m',
            'armv7-a': 'armv7-a'
        }
        if arch in archs:
            opts['common']['arm.target.arch'] = archs[arch]
            self.remove_option(flags['common_flags'], str)

        opts['common']['arm.target.instructionset'] = 'thumb'
        if '-mthumb' in flags['common_flags']:
            self.remove_option(flags['common_flags'], '-mthumb')
            self.remove_option(flags['ld_flags'], '-mthumb')
        elif '-marm' in flags['common_flags']:
            opts['common']['arm.target.instructionset'] = 'arm'
            self.remove_option(flags['common_flags'], '-marm')
            self.remove_option(flags['ld_flags'], '-marm')

        opts['common']['arm.target.thumbinterwork'] = False
        if '-mthumb-interwork' in flags['common_flags']:
            opts['common']['arm.target.thumbinterwork'] = True
            self.remove_option(flags['common_flags'], '-mthumb-interwork')

        opts['common']['arm.target.endianness'] = None
        if '-mlittle-endian' in flags['common_flags']:
            opts['common']['arm.target.endianness'] = 'little'
            self.remove_option(flags['common_flags'], '-mlittle-endian')
        elif '-mbig-endian' in flags['common_flags']:
            opts['common']['arm.target.endianness'] = 'big'
            self.remove_option(flags['common_flags'], '-mbig-endian')

        opts['common']['arm.target.fpu.unit'] = None
        opts['common']['arm.target.fpu.unit_nxp'] = None
        # default, fpv4spd16, fpv5d16, fpv5spd16
        str = self.find_options(flags['common_flags'], '-mfpu=')
        if str != None:
            fpu = str[len('-mfpu='):]
            fpus = {
                'fpv4-sp-d16': 'fpv4spd16',
                'fpv5-d16': 'fpv5d16',
                'fpv5-sp-d16': 'fpv5spd16'
            }
            fpus_nxp = {
                'fpv4-sp-d16': 'fpv4',
                'fpv5-d16': 'fpv5dp',
                'fpv5-sp-d16': 'fpv5sp'
            }
            if fpu in fpus:
                opts['common']['arm.target.fpu.unit'] = fpus[fpu]
                opts['common']['arm.target.fpu.unit_nxp'] = fpus_nxp[fpu]

                self.remove_option(flags['common_flags'], str)
                self.remove_option(flags['ld_flags'], str)
        if opts['common']['arm.target.fpu.unit'] == None:
            if core not in MCPUS:
                raise NotSupportedException(
                    'Target core {0} not supported.'.format(core))
            if MCPUS[core]['fpu_unit']:
                opts['common']['arm.target.fpu.unit'] = MCPUS[core]['fpu_unit']

        # soft, softfp, hard.
        str = self.find_options(flags['common_flags'], '-mfloat-abi=')
        if str != None:
            opts['common']['arm.target.fpu.abi'] = str[len('-mfloat-abi='):]
            self.remove_option(flags['common_flags'], str)
            self.remove_option(flags['ld_flags'], str)
            if opts['common']['arm.target.fpu.abi'] == 'hard':
                opts['common']['arm.target.fpu.unit_nxp'] += '.hard'

        # Default optimisation level for Release.
        opts['common']['optimization.level'] = '-Os'

        # If the project defines an optimisation level, it is used
        # only for the Release configuration, the Debug one used '-Og'.
        str = self.find_options(flags['common_flags'], '-O')
        if str != None:
            levels = {
                '-O0': 'none',
                '-O1': 'optimize',
                '-O2': 'more',
                '-O3': 'most',
                '-Os': 'size',
                '-Og': 'debug'
            }
            if str in levels:
                opts['common']['optimization.level'] = levels[str]
                self.remove_option(flags['common_flags'], str)

        include_files = []
        for all_flags in [
                flags['common_flags'], flags['c_flags'], flags['cxx_flags']
        ]:
            while '-include' in all_flags:
                ix = all_flags.index('-include')
                str = all_flags[ix + 1]
                if str not in include_files:
                    include_files.append(str)
                self.remove_option(all_flags, '-include')
                self.remove_option(all_flags, str)

        opts['common']['include_files'] = include_files

        if '-ansi' in flags['c_flags']:
            opts['c']['compiler.std'] = '-ansi'
            self.remove_option(flags['c_flags'], str)
        else:
            str = self.find_options(flags['c_flags'], '-std')
            std = str[len('-std='):]
            c_std = {
                'c90': 'c90',
                'c89': 'c90',
                'gnu90': 'gnu90',
                'gnu89': 'gnu90',
                'c99': 'c99',
                'c9x': 'c99',
                'gnu99': 'gnu99',
                'gnu9x': 'gnu98',
                'c11': 'c11',
                'c1x': 'c11',
                'gnu11': 'gnu11',
                'gnu1x': 'gnu11'
            }
            if std in c_std:
                opts['c']['compiler.std'] = c_std[std]
                self.remove_option(flags['c_flags'], str)

        if '-ansi' in flags['cxx_flags']:
            opts['cpp']['compiler.std'] = '-ansi'
            self.remove_option(flags['cxx_flags'], str)
        else:
            str = self.find_options(flags['cxx_flags'], '-std')
            std = str[len('-std='):]
            cpp_std = {
                'c++98': 'cpp98',
                'c++03': 'cpp03',
                'gnu++98': 'gnupp98',
                'gnu++03': 'gnupp03',
                'c++0x': 'cpp03',
                'gnu++0x': 'gnupp03',
                'c++11': 'cpp11',
                'gnu++11': 'gnupp11',
                'c++1y': 'cpp11',
                'gnu++1y': 'gnupp11',
                'c++14': 'cpp14',
                'gnu++14': 'gnupp14',
                'c++1z': 'cpp1z',
                'gnu++1z': 'gnupp1z',
            }
            if std in cpp_std:
                opts['cpp']['compiler.std'] = cpp_std[std]
                self.remove_option(flags['cxx_flags'], str)

        # Common optimisation options.
        optimization_options = {
            '-flto': 'optimization.lto',
            '--ffat-lto-objects': 'optimization.lto_objects'
        }
        for option in optimization_options:
            opts['common'][optimization_options[option]] = False
            if option in flags['common_flags']:
                opts['common'][optimization_options[option]] = True
                self.remove_option(flags['common_flags'], option)

        # Common warning options.
        warning_options = {
            '-fsyntax-only': 'warnings.syntaxonly',
            '-pedantic': 'warnings.pedantic',
            '-pedantic-errors': 'warnings.pedanticerrors',
            '-w': 'warnings.nowarn',
            '-Wall': 'warnings.allwarn',
            '-Wextra': 'warnings.extrawarn',
            '-Wconversion': 'warnings.conversion',
            '-Werror': 'warnings.toerrors',
        }

        for option in warning_options:
            opts['common'][warning_options[option]] = False
            if option in flags['common_flags']:
                opts['common'][warning_options[option]] = True
                self.remove_option(flags['common_flags'], option)

        # Common debug options.
        debug_levels = {
            '-g': 'default',
            '-g1': 'minimal',
            '-g3': 'max',
        }
        opts['common']['debugging.level'] = 'none'
        for option in debug_levels:
            if option in flags['common_flags']:
                opts['common']['debugging.level'] = debug_levels[option]
                self.remove_option(flags['common_flags'], option)

        opts['common']['debugging.prof'] = False
        if '-p' in flags['common_flags']:
            opts['common']['debugging.prof'] = True
            self.remove_option(flags['common_flags'], '-p')

        opts['common']['debugging.gprof'] = False
        if '-pg' in flags['common_flags']:
            opts['common']['debugging.gprof'] = True
            self.remove_option(flags['common_flags'], '-gp')

        # Assembler options.
        opts['as']['usepreprocessor'] = False
        while '-x' in flags['asm_flags']:
            ix = flags['asm_flags'].index('-x')
            str = flags['asm_flags'][ix + 1]

            if str == 'assembler-with-cpp':
                opts['as']['usepreprocessor'] = True
            else:
                # Collect all other assembler options.
                opts['as']['other'] += ' -x ' + str

            self.remove_option(flags['asm_flags'], '-x')
            self.remove_option(flags['asm_flags'], 'assembler-with-cpp')

        opts['as']['nostdinc'] = False
        if '-nostdinc' in flags['asm_flags']:
            opts['as']['nostdinc'] = True
            self.remove_option(flags['asm_flags'], '-nostdinc')

        opts['as']['verbose'] = False
        if '-v' in flags['asm_flags']:
            opts['as']['verbose'] = True
            self.remove_option(flags['asm_flags'], '-v')

        # C options.
        opts['c']['nostdinc'] = False
        if '-nostdinc' in flags['c_flags']:
            opts['c']['nostdinc'] = True
            self.remove_option(flags['c_flags'], '-nostdinc')

        opts['c']['verbose'] = False
        if '-v' in flags['c_flags']:
            opts['c']['verbose'] = True
            self.remove_option(flags['c_flags'], '-v')

        # C++ options.
        opts['cpp']['nostdinc'] = False
        if '-nostdinc' in flags['cxx_flags']:
            opts['cpp']['nostdinc'] = True
            self.remove_option(flags['cxx_flags'], '-nostdinc')

        opts['cpp']['nostdincpp'] = False
        if '-nostdinc++' in flags['cxx_flags']:
            opts['cpp']['nostdincpp'] = True
            self.remove_option(flags['cxx_flags'], '-nostdinc++')

        optimization_options = {
            '-fno-exceptions': 'optimization.noexceptions',
            '-fno-rtti': 'optimization.nortti',
            '-fno-use-cxa-atexit': 'optimization.nousecxaatexit',
            '-fno-threadsafe-statics': 'optimization.nothreadsafestatics',
        }

        for option in optimization_options:
            opts['cpp'][optimization_options[option]] = False
            if option in flags['cxx_flags']:
                opts['cpp'][optimization_options[option]] = True
            if option in flags['common_flags']:
                opts['cpp'][optimization_options[option]] = True

        opts['cpp']['verbose'] = False
        if '-v' in flags['cxx_flags']:
            opts['cpp']['verbose'] = True
            self.remove_option(flags['cxx_flags'], '-v')

        # Linker options.
        linker_options = {
            '-nostartfiles': 'nostart',
            '-nodefaultlibs': 'nodeflibs',
            '-nostdlib': 'nostdlibs',
        }

        for option in linker_options:
            opts['ld'][linker_options[option]] = False
            if option in flags['ld_flags']:
                opts['ld'][linker_options[option]] = True
                self.remove_option(flags['ld_flags'], option)

        opts['ld']['gcsections'] = False
        if '-Wl,--gc-sections' in flags['ld_flags']:
            opts['ld']['gcsections'] = True
            self.remove_option(flags['ld_flags'], '-Wl,--gc-sections')

        opts['ld']['flags'] = []
        to_remove = []
        for opt in flags['ld_flags']:
            if opt.startswith('-Wl,--wrap,'):
                opts['ld']['flags'].append('--wrap=' +
                                           opt[len('-Wl,--wrap,'):])
                to_remove.append(opt)
        for opt in to_remove:
            self.remove_option(flags['ld_flags'], opt)

        # Other tool remaining options are separated by category.
        opts['as']['otherwarnings'] = self.find_options(
            flags['asm_flags'], '-W')

        opts['c']['otherwarnings'] = self.find_options(flags['c_flags'], '-W')
        opts['c']['otheroptimizations'] = self.find_options(
            flags['c_flags'], '-f')

        opts['cpp']['otherwarnings'] = self.find_options(
            flags['cxx_flags'], '-W')
        opts['cpp']['otheroptimizations'] = self.find_options(
            flags['cxx_flags'], '-f')

        # Other common remaining options are separated by category.
        opts['common']['optimization.other'] = self.find_options(
            flags['common_flags'], '-f')
        opts['common']['warnings.other'] = self.find_options(
            flags['common_flags'], '-W')

        # Remaining common flags are added to each tool.
        opts['as']['other'] += ' ' + \
            ' '.join(flags['common_flags']) + ' ' + \
            ' '.join(flags['asm_flags'])
        opts['c']['other'] += ' ' + \
            ' '.join(flags['common_flags']) + ' ' + ' '.join(flags['c_flags'])
        opts['cpp']['other'] += ' ' + \
            ' '.join(flags['common_flags']) + ' ' + \
            ' '.join(flags['cxx_flags'])
        opts['ld']['other'] += ' ' + \
            ' '.join(flags['common_flags']) + ' ' + ' '.join(flags['ld_flags'])

        if len(self.system_libraries) > 0:
            opts['ld']['other'] += ' -Wl,--start-group '
            opts['ld']['other'] += ' '.join(
                '-l' + s for s in self.system_libraries) + ' '
            opts['ld']['other'] += ' '.join('-l' + s for s in libraries)
            opts['ld']['other'] += ' -Wl,--end-group '

        # Strip all 'other' flags, since they might have leading spaces.
        opts['as']['other'] = opts['as']['other'].strip()
        opts['c']['other'] = opts['c']['other'].strip()
        opts['cpp']['other'] = opts['cpp']['other'].strip()
        opts['ld']['other'] = opts['ld']['other'].strip()
Esempio n. 16
0
    def generate(self):
        """
        Generate the .project and .cproject files.
        """
        if not self.resources.linker_script:
            raise NotSupportedException("No linker script found.")

        print
        print 'Create a GNU ARM Eclipse C++ managed project'
        print 'Project name: {0}'.format(self.project_name)
        print 'Target: {0}'.format(self.toolchain.target.name)
        print 'Toolchain: {0}'.format(self.TOOLCHAIN)

        self.resources.win_to_unix()

        # TODO: use some logger to display additional info if verbose

        libraries = []
        # print 'libraries'
        # print self.resources.libraries
        for lib in self.resources.libraries:
            l, _ = splitext(basename(lib))
            libraries.append(l[3:])

        self.system_libraries = ['stdc++', 'supc++', 'm', 'c', 'gcc', 'nosys']

        # Read in all profiles, we'll extract compiler options.
        profiles = self.get_all_profiles()

        profile_ids = [s.lower() for s in profiles]
        profile_ids.sort()

        # TODO: get the list from existing .cproject
        build_folders = [s.capitalize() for s in profile_ids]
        build_folders.append('BUILD')
        # print build_folders

        objects = [self.filter_dot(s) for s in self.resources.objects]
        for bf in build_folders:
            objects = [o for o in objects if not o.startswith(bf + '/')]
        # print 'objects'
        # print objects

        self.compute_exclusions()

        self.include_path = [
            self.filter_dot(s) for s in self.resources.inc_dirs
        ]
        print 'Include folders: {0}'.format(len(self.include_path))

        self.as_defines = self.toolchain.get_symbols(True)
        self.c_defines = self.toolchain.get_symbols()
        self.cpp_defines = self.c_defines
        print 'Symbols: {0}'.format(len(self.c_defines))

        self.ld_script = self.filter_dot(self.resources.linker_script)
        print 'Linker script: {0}'.format(self.ld_script)

        self.options = {}
        for id in profile_ids:

            # There are 4 categories of options, a category common too
            # all tools and a specific category for each of the tools.
            opts = {}
            opts['common'] = {}
            opts['as'] = {}
            opts['c'] = {}
            opts['cpp'] = {}
            opts['ld'] = {}

            opts['id'] = id
            opts['name'] = opts['id'].capitalize()

            print
            print 'Build configuration: {0}'.format(opts['name'])

            profile = profiles[id]
            profile_toolchain = profile[self.TOOLCHAIN]

            # A small hack, do not bother with src_path again,
            # pass an empty string to avoid crashing.
            src_paths = ['']
            target_name = self.toolchain.target.name
            toolchain = prepare_toolchain(src_paths,
                                          "",
                                          target_name,
                                          self.TOOLCHAIN,
                                          build_profile=profile_toolchain)

            # Hack to fill in build_dir
            toolchain.build_dir = self.toolchain.build_dir

            flags = self.toolchain_flags(toolchain)

            print 'Common flags:', ' '.join(flags['common_flags'])
            print 'C++ flags:', ' '.join(flags['cxx_flags'])
            print 'C flags:', ' '.join(flags['c_flags'])
            print 'ASM flags:', ' '.join(flags['asm_flags'])
            print 'Linker flags:', ' '.join(flags['ld_flags'])

            # Most GNU ARM Eclipse options have a parent,
            # either debug or release.
            if '-O0' in flags['common_flags'] or '-Og' in flags['common_flags']:
                opts['parent_id'] = 'debug'
            else:
                opts['parent_id'] = 'release'

            self.process_options(opts, flags)

            opts['as']['defines'] = self.as_defines
            opts['c']['defines'] = self.c_defines
            opts['cpp']['defines'] = self.cpp_defines

            opts['common']['include_paths'] = self.include_path
            opts['common']['excluded_folders'] = '|'.join(
                self.excluded_folders)

            opts['ld']['library_paths'] = [
                self.filter_dot(s) for s in self.resources.lib_dirs
            ]

            opts['ld']['object_files'] = objects
            opts['ld']['user_libraries'] = libraries
            opts['ld']['system_libraries'] = self.system_libraries
            opts['ld']['script'] = self.ld_script

            # Unique IDs used in multiple places.
            # Those used only once are implemented with {{u.id}}.
            uid = {}
            uid['config'] = u.id
            uid['tool_c_compiler'] = u.id
            uid['tool_c_compiler_input'] = u.id
            uid['tool_cpp_compiler'] = u.id
            uid['tool_cpp_compiler_input'] = u.id

            opts['uid'] = uid

            self.options[id] = opts

        jinja_ctx = {
            'name': self.project_name,

            # Compiler & linker command line options
            'options': self.options,

            # Must be an object with an `id` property, which
            # will be called repeatedly, to generate multiple UIDs.
            'u': u,
        }

        # TODO: it would be good to have jinja stop if one of the
        # expected context values is not defined.
        self.gen_file('gnuarmeclipse/.project.tmpl',
                      jinja_ctx,
                      '.project',
                      trim_blocks=True,
                      lstrip_blocks=True)
        self.gen_file('gnuarmeclipse/.cproject.tmpl',
                      jinja_ctx,
                      '.cproject',
                      trim_blocks=True,
                      lstrip_blocks=True)
        self.gen_file('gnuarmeclipse/makefile.targets.tmpl',
                      jinja_ctx,
                      'makefile.targets',
                      trim_blocks=True,
                      lstrip_blocks=True)

        if not exists('.mbedignore'):
            print
            print 'Create .mbedignore'
            with open('.mbedignore', 'w') as f:
                for bf in build_folders:
                    print bf + '/'
                    f.write(bf + '/\n')

        print
        print 'Done. Import the \'{0}\' project in Eclipse.'.format(
            self.project_name)
Esempio n. 17
0
    def generate(self):
        """Generate the makefile

        Note: subclasses should not need to override this method
        """
        if not self.resources.linker_script:
            raise NotSupportedException("No linker script found.")

        self.resources.win_to_unix()

        to_be_compiled = [
            splitext(src)[0] + ".o" for src in self.resources.s_sources +
            self.resources.c_sources + self.resources.cpp_sources
        ]

        libraries = [
            self.prepare_lib(basename(lib)) for lib in self.resources.libraries
        ]
        sys_libs = [
            self.prepare_sys_lib(lib) for lib in self.toolchain.sys_libs
        ]

        ctx = {
            'name':
            self.project_name,
            'to_be_compiled':
            to_be_compiled,
            'object_files':
            self.resources.objects,
            'include_paths':
            list(set(self.resources.inc_dirs)),
            'library_paths':
            self.resources.lib_dirs,
            'linker_script':
            self.resources.linker_script,
            'libraries':
            libraries,
            'ld_sys_libs':
            sys_libs,
            'hex_files':
            self.resources.hex_files,
            'vpath': (["../../.."] if
                      (basename(dirname(dirname(self.export_dir)))
                       == "projectfiles") else [".."]),
            'cc_cmd':
            " ".join([
                "\'" + part + "\'"
                for part in ([basename(self.toolchain.cc[0])] +
                             self.toolchain.cc[1:])
            ]),
            'cppc_cmd':
            " ".join([
                "\'" + part + "\'"
                for part in ([basename(self.toolchain.cppc[0])] +
                             self.toolchain.cppc[1:])
            ]),
            'asm_cmd':
            " ".join([
                "\'" + part + "\'"
                for part in ([basename(self.toolchain.asm[0])] +
                             self.toolchain.asm[1:])
            ]),
            'ld_cmd':
            "\'" + basename(self.toolchain.ld[0]) + "\'",
            'elf2bin_cmd':
            "\'" + basename(self.toolchain.elf2bin) + "\'",
            'link_script_ext':
            self.toolchain.LINKER_EXT,
            'link_script_option':
            self.LINK_SCRIPT_OPTION,
            'user_library_flag':
            self.USER_LIBRARY_FLAG,
        }

        if hasattr(self.toolchain, "preproc"):
            ctx['pp_cmd'] = " ".join([
                "\'" + part + "\'"
                for part in ([basename(self.toolchain.preproc[0])] +
                             self.toolchain.preproc[1:] +
                             self.toolchain.ld[1:])
            ])
        else:
            ctx['pp_cmd'] = None

        for key in [
                'include_paths', 'library_paths', 'linker_script', 'hex_files'
        ]:
            if isinstance(ctx[key], list):
                ctx[key] = [ctx['vpath'][0] + "/" + t for t in ctx[key]]
            else:
                ctx[key] = ctx['vpath'][0] + "/" + ctx[key]
        if "../." not in ctx["include_paths"]:
            ctx["include_paths"] += ['../.']
        for key in [
                'include_paths', 'library_paths', 'hex_files', 'to_be_compiled'
        ]:
            ctx[key] = sorted(ctx[key])
        ctx.update(self.format_flags())

        for templatefile in \
            ['makefile/%s_%s.tmpl' % (self.TEMPLATE,
                                      self.target.lower())] + \
            ['makefile/%s_%s.tmpl' % (self.TEMPLATE,
                                      label.lower()) for label
             in self.toolchain.target.extra_labels] +\
            ['makefile/%s.tmpl' % self.TEMPLATE]:
            try:
                self.gen_file(templatefile, ctx, 'Makefile')
                break
            except TemplateNotFound:
                pass
        else:
            raise NotSupportedException("This make tool is in development")
Esempio n. 18
0
    def generate(self):
        """Generate the makefile

        Note: subclasses should not need to override this method
        """
        if not self.resources.linker_script:
            raise NotSupportedException("No linker script found.")

        self.resources.win_to_unix()

        to_be_compiled = [
            splitext(src)[0] + ".o" for src in self.resources.s_sources +
            self.resources.c_sources + self.resources.cpp_sources
        ]

        libraries = [self.prepare_lib(basename(lib)) for lib in self.libraries]
        sys_libs = [
            self.prepare_sys_lib(lib) for lib in self.toolchain.sys_libs
        ]

        ctx = {
            'name': self.project_name,
            'to_be_compiled': to_be_compiled,
            'object_files': self.resources.objects,
            'include_paths': list(set(self.resources.inc_dirs)),
            'library_paths': self.resources.lib_dirs,
            'linker_script': self.resources.linker_script,
            'libraries': libraries,
            'ld_sys_libs': sys_libs,
            'hex_files': self.hex_files,
            'vpath': ([".."]),
            'cc_cmd': basename(self.toolchain.cc[0]),
            'cppc_cmd': basename(self.toolchain.cppc[0]),
            'asm_cmd': basename(self.toolchain.asm[0]),
            'ld_cmd': basename(self.toolchain.ld[0]),
            'elf2bin_cmd': basename(self.toolchain.elf2bin),
            'link_script_ext': self.toolchain.LINKER_EXT,
            'link_script_option': self.LINK_SCRIPT_OPTION,
            'user_library_flag': self.USER_LIBRARY_FLAG,
            'needs_asm_preproc': self.PREPROCESS_ASM,
            'shell_escape': shell_escape,
            'response_option': self.RESPONSE_OPTION,
        }

        if hasattr(self.toolchain, "preproc"):
            ctx['pp_cmd'] = " ".join([basename(self.toolchain.preproc[0])] +
                                     self.toolchain.preproc[1:] +
                                     self.toolchain.ld[1:])
        else:
            ctx['pp_cmd'] = None

        for key in [
                'include_paths', 'library_paths', 'linker_script', 'hex_files'
        ]:
            if isinstance(ctx[key], list):
                ctx[key] = [ctx['vpath'][0] + "/" + t for t in ctx[key]]
            else:
                ctx[key] = ctx['vpath'][0] + "/" + ctx[key]
        if "../." not in ctx["include_paths"]:
            ctx["include_paths"] += ['../.']
        for key in [
                'include_paths', 'library_paths', 'hex_files', 'to_be_compiled'
        ]:
            ctx[key] = sorted(ctx[key])
        ctx.update(self.format_flags())
        ctx['asm_flags'].extend(self.toolchain.asm[1:])
        ctx['c_flags'].extend(self.toolchain.cc[1:])
        ctx['cxx_flags'].extend(self.toolchain.cppc[1:])

        # Add the virtual path the the include option in the ASM flags
        new_asm_flags = []
        for flag in ctx['asm_flags']:
            if flag.startswith('--cpreproc_opts='):
                sub_flags = flag.split(',')
                new_sub_flags = []
                for sub_flag in sub_flags:
                    new_sub_flags.append(_fix_include_asm_flag(sub_flag, ctx))
                new_asm_flags.append(','.join(new_sub_flags))
            else:
                new_asm_flags.append(_fix_include_asm_flag(flag, ctx))
        ctx['asm_flags'] = new_asm_flags

        for templatefile in \
            ['makefile/%s_%s.tmpl' % (self.TEMPLATE,
                                      self.target.lower())] + \
            ['makefile/%s_%s.tmpl' % (self.TEMPLATE,
                                      label.lower()) for label
             in self.toolchain.target.extra_labels] +\
            ['makefile/%s.tmpl' % self.TEMPLATE]:
            try:
                self.gen_file(templatefile, ctx, 'Makefile')
                break
            except TemplateNotFound:
                pass
        else:
            raise NotSupportedException("This make tool is in development")
Esempio n. 19
0
 def validate_resources(self):
     if not self.resources.linker_script:
         raise NotSupportedException("No linker script found.")
Esempio n. 20
0
    def __init__(self, target, *args, **kwargs):
        mbedToolchain.__init__(self, target, *args, **kwargs)
        if target.core not in self.SUPPORTED_CORES:
            raise NotSupportedException(
                "this compiler does not support the core %s" % target.core)

        if int(target.build_tools_metadata["version"]) > 0:
            if not set(("ARM", "ARMC6", "uARM")).intersection(
                    set(target.supported_toolchains)):
                raise NotSupportedException(
                    "ARM/ARMC6 compiler support is required for ARMC6 build")
        else:
            if not set(("ARM", "ARMC6")).intersection(
                    set(target.supported_toolchains)):
                raise NotSupportedException(
                    "ARM/ARMC6 compiler support is required for ARMC6 build")

        if getattr(target, "default_toolchain", "ARMC6") == "uARM":
            if "-DMBED_RTOS_SINGLE_THREAD" not in self.flags['common']:
                self.flags['common'].append("-DMBED_RTOS_SINGLE_THREAD")
            if "-D__MICROLIB" not in self.flags['common']:
                self.flags['common'].append("-D__MICROLIB")
            if "--library_type=microlib" not in self.flags['ld']:
                self.flags['ld'].append("--library_type=microlib")
            if "-Wl,--library_type=microlib" not in self.flags['c']:
                self.flags['c'].append("-Wl,--library_type=microlib")
            if "-Wl,--library_type=microlib" not in self.flags['cxx']:
                self.flags['cxx'].append("-Wl,--library_type=microlib")
            if "--library_type=microlib" not in self.flags['asm']:
                self.flags['asm'].append("--library_type=microlib")

        core = target.core
        if CORE_ARCH[target.core] == 8:
            if ((not target.core.endswith("-NS"))
                    and kwargs.get('build_dir', False)):
                # Create Secure library
                build_dir = kwargs['build_dir']
                secure_file = join(build_dir, "cmse_lib.o")
                self.flags["ld"] += ["--import_cmse_lib_out=%s" % secure_file]

            # Add linking time preprocessor macro DOMAIN_NS
            if target.core.endswith("-NS"):
                define_string = self.make_ld_define("DOMAIN_NS", "0x1")
                self.flags["ld"].append(define_string)
                core = target.core[:-3]
            else:
                # Add secure build flag
                self.flags['cxx'].append("-mcmse")
                self.flags['c'].append("-mcmse")

        cpu = {
            "Cortex-M0+": "cortex-m0plus",
            "Cortex-M4F": "cortex-m4",
            "Cortex-M7F": "cortex-m7",
            "Cortex-M7FD": "cortex-m7",
            "Cortex-M33": "cortex-m33+nodsp",
            "Cortex-M33F": "cortex-m33+nodsp",
            "Cortex-M33FE": "cortex-m33"
        }.get(core, core)

        cpu = cpu.lower()
        self.flags['common'].append("-mcpu=%s" % cpu)
        self.SHEBANG += " -mcpu=%s" % cpu

        # FPU handling
        if core == "Cortex-M4F":
            self.flags['common'].append("-mfpu=fpv4-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m4")
        elif core == "Cortex-M7F":
            self.flags['common'].append("-mfpu=fpv5-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m7.fp.sp")
        elif core == "Cortex-M7FD":
            self.flags['common'].append("-mfpu=fpv5-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m7")
        elif core == "Cortex-M33F":
            self.flags['common'].append("-mfpu=fpv5-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m33.no_dsp")
        elif core == "Cortex-M33":
            self.flags['common'].append("-mfpu=none")
            self.flags['ld'].append("--cpu=cortex-m33.no_dsp.no_fp")
        else:
            self.flags['ld'].append("--cpu=%s" % cpu)

        asm_cpu = {
            "Cortex-M0+": "Cortex-M0",
            "Cortex-M4F": "Cortex-M4.fp",
            "Cortex-M7F": "Cortex-M7.fp.sp",
            "Cortex-M7FD": "Cortex-M7.fp.dp",
            "Cortex-M33": "Cortex-M33.no_dsp.no_fp",
            "Cortex-M33F": "Cortex-M33.no_dsp",
            "Cortex-M33FE": "Cortex-M33"
        }.get(core, core)

        self.flags['asm'].append("--cpu=%s" % asm_cpu)

        self.cc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                   self.flags['common'] + self.flags['c'])
        self.cppc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                     self.flags['common'] + self.flags['cxx'])
        self.asm = [join(TOOLCHAIN_PATHS["ARMC6"], "armasm")]
        self.asm += self.flags['asm']
        self.ld = [join(TOOLCHAIN_PATHS["ARMC6"], "armlink")]
        self.ld += self.flags['ld']
        self.ar = join(TOOLCHAIN_PATHS["ARMC6"], "armar")
        self.elf2bin = join(TOOLCHAIN_PATHS["ARMC6"], "fromelf")

        # Adding this for safety since this inherits the `version_check`
        # function but does not call the constructor of ARM_STD, so the
        # `product_name` variable is not initialized.
        self.product_name = None
Esempio n. 21
0
    def __init__(self, target, *args, **kwargs):
        mbedToolchain.__init__(self, target, *args, **kwargs)
        if target.core not in self.SUPPORTED_CORES:
            raise NotSupportedException(
                "this compiler does not support the core %s" % target.core)
        if CORE_ARCH[target.core] < 8:
            self.notify.cc_info({
                'severity':
                "Error",
                'file':
                "",
                'line':
                "",
                'col':
                "",
                'message':
                "ARMC6 does not support ARM architecture v{}"
                " targets".format(CORE_ARCH[target.core]),
                'text':
                '',
                'target_name':
                self.target.name,
                'toolchain_name':
                self.name
            })

        if not set(
            ("ARM", "ARMC6")).intersection(set(target.supported_toolchains)):
            raise NotSupportedException(
                "ARM/ARMC6 compiler support is required for ARMC6 build")

        core = target.core
        if CORE_ARCH[target.core] == 8:
            if (not target.core.endswith("-NS")) and kwargs.get(
                    'build_dir', False):
                # Create Secure library
                build_dir = kwargs['build_dir']
                secure_file = join(build_dir, "cmse_lib.o")
                self.flags["ld"] += ["--import_cmse_lib_out=%s" % secure_file]

            # Add linking time preprocessor macro DOMAIN_NS
            if target.core.endswith("-NS"):
                define_string = self.make_ld_define("DOMAIN_NS", "0x1")
                self.flags["ld"].append(define_string)
                core = target.core[:-3]
            else:
                # Add secure build flag
                self.flags['cxx'].append("-mcmse")
                self.flags['c'].append("-mcmse")

        cpu = {
            "Cortex-M0+": "cortex-m0plus",
            "Cortex-M4F": "cortex-m4",
            "Cortex-M7F": "cortex-m7",
            "Cortex-M7FD": "cortex-m7",
            "Cortex-M33": "cortex-m33+nodsp",
            "Cortex-M33F": "cortex-m33+nodsp",
            "Cortex-M33FE": "cortex-m33"
        }.get(core, core)

        cpu = cpu.lower()
        self.flags['common'].append("-mcpu=%s" % cpu)
        self.SHEBANG += " -mcpu=%s" % cpu

        # FPU handling
        if core == "Cortex-M4F":
            self.flags['common'].append("-mfpu=fpv4-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m4")
        elif core == "Cortex-M7F":
            self.flags['common'].append("-mfpu=fpv5-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m7.fp.sp")
        elif core == "Cortex-M7FD":
            self.flags['common'].append("-mfpu=fpv5-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m7")
        elif core == "Cortex-M33F":
            self.flags['common'].append("-mfpu=fpv5-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
            self.flags['ld'].append("--cpu=cortex-m33.no_dsp")
        elif core == "Cortex-M33":
            self.flags['common'].append("-mfpu=none")
            self.flags['ld'].append("--cpu=cortex-m33.no_dsp.no_fp")
        else:
            self.flags['ld'].append("--cpu=%s" % cpu)

        asm_cpu = {
            "Cortex-M0+": "Cortex-M0",
            "Cortex-M4F": "Cortex-M4.fp",
            "Cortex-M7F": "Cortex-M7.fp.sp",
            "Cortex-M7FD": "Cortex-M7.fp.dp",
            "Cortex-M33": "Cortex-M33.no_dsp.no_fp",
            "Cortex-M33F": "Cortex-M33.no_dsp",
            "Cortex-M33FE": "Cortex-M33"
        }.get(core, core)

        self.flags['asm'].append("--cpu=%s" % asm_cpu)

        self.cc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                   self.flags['common'] + self.flags['c'])
        self.cppc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                     self.flags['common'] + self.flags['cxx'])
        self.asm = [join(TOOLCHAIN_PATHS["ARMC6"], "armasm")
                    ] + self.flags['asm']
        self.ld = [join(TOOLCHAIN_PATHS["ARMC6"], "armlink")
                   ] + self.flags['ld']
        self.ar = join(TOOLCHAIN_PATHS["ARMC6"], "armar")
        self.elf2bin = join(TOOLCHAIN_PATHS["ARMC6"], "fromelf")
Esempio n. 22
0
    def __init__(self, target, *args, **kwargs):
        mbedToolchain.__init__(self, target, *args, **kwargs)
        if target.core not in self.SUPPORTED_CORES:
            raise NotSupportedException(
                "this compiler does not support the core %s" % target.core)

        if int(target.build_tools_metadata["version"]) > 0:
            if not set(("ARM", "ARMC6", "uARM")).intersection(set(
                    target.supported_toolchains
            )):
                raise NotSupportedException(
                    "ARM/ARMC6 compiler support is required for ARMC6 build"
                )
        else:
            if not set(("ARM", "ARMC6")).intersection(set(
                    target.supported_toolchains
            )):
                raise NotSupportedException(
                    "ARM/ARMC6 compiler support is required for ARMC6 build"
                )

        self.check_c_lib_supported(target, "arm")

        if (
            getattr(target, "default_toolchain", "ARMC6") == "uARM"
            or getattr(target, "default_lib", "std") == "small"
        ):
            if "-DMBED_RTOS_SINGLE_THREAD" not in self.flags['common']:
                self.flags['common'].append("-DMBED_RTOS_SINGLE_THREAD")
            if "-D__MICROLIB" not in self.flags['common']:
                self.flags['common'].append("-D__MICROLIB")
            if "--library_type=microlib" not in self.flags['ld']:
                self.flags['ld'].append("--library_type=microlib")
            if "-Wl,--library_type=microlib" not in self.flags['c']:
                self.flags['c'].append("-Wl,--library_type=microlib")
            if "-Wl,--library_type=microlib" not in self.flags['cxx']:
                self.flags['cxx'].append("-Wl,--library_type=microlib")
            if "--library_type=microlib" not in self.flags['asm']:
                self.flags['asm'].append("--library_type=microlib")

        self.check_and_add_minimal_printf(target)

        if target.is_TrustZone_secure_target:
            if kwargs.get('build_dir', False):
                # Output secure import library
                build_dir = kwargs['build_dir']
                secure_file = join(build_dir, "cmse_lib.o")
                self.flags["ld"] += ["--import_cmse_lib_out=%s" % secure_file]

            # Enable compiler security extensions
            self.flags['cxx'].append("-mcmse")
            self.flags['c'].append("-mcmse")

        if target.is_TrustZone_non_secure_target:
            # Add linking time preprocessor macro DOMAIN_NS
            # (DOMAIN_NS is passed to compiler and assembler via CORTEX_SYMBOLS
            # in mbedToolchain.get_symbols)
            define_string = self.make_ld_define("DOMAIN_NS", "0x1")
            self.flags["ld"].append(define_string)

        core = target.core_without_NS
        cpu = {
            "Cortex-M0+": "cortex-m0plus",
            "Cortex-M4F": "cortex-m4",
            "Cortex-M7F": "cortex-m7",
            "Cortex-M7FD": "cortex-m7",
            "Cortex-M33": "cortex-m33+nodsp",
            "Cortex-M33F": "cortex-m33+nodsp",
            "Cortex-M33E": "cortex-m33",
            "Cortex-M33FE": "cortex-m33"}.get(core, core)

        cpu = cpu.lower()
        self.flags['common'].append("-mcpu=%s" % cpu)
        self.SHEBANG += " -mcpu=%s" % cpu

        # FPU handling
        if core in ["Cortex-M4", "Cortex-M7", "Cortex-M33", "Cortex-M33E"]:
            self.flags['common'].append("-mfpu=none")
        elif core == "Cortex-M4F":
            self.flags['common'].append("-mfpu=fpv4-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
        elif core == "Cortex-M7F" or core.startswith("Cortex-M33F"):
            self.flags['common'].append("-mfpu=fpv5-sp-d16")
            self.flags['common'].append("-mfloat-abi=hard")
        elif core == "Cortex-M7FD":
            self.flags['common'].append("-mfpu=fpv5-d16")
            self.flags['common'].append("-mfloat-abi=hard")

        asm_ld_cpu = {
            "Cortex-M0+": "Cortex-M0plus",
            "Cortex-M4": "Cortex-M4.no_fp",
            "Cortex-M4F": "Cortex-M4",
            "Cortex-M7": "Cortex-M7.no_fp",
            "Cortex-M7F": "Cortex-M7.fp.sp",
            "Cortex-M7FD": "Cortex-M7",
            "Cortex-M33": "Cortex-M33.no_dsp.no_fp",
            "Cortex-M33E": "Cortex-M33.no_fp",
            "Cortex-M33F": "Cortex-M33.no_dsp",
            "Cortex-M33FE": "Cortex-M33"}.get(core, core)

        self.flags['asm'].append("--cpu=%s" % asm_ld_cpu)
        self.flags['ld'].append("--cpu=%s" % asm_ld_cpu)

        self.cc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                   self.flags['common'] + self.flags['c'])
        self.cppc = ([join(TOOLCHAIN_PATHS["ARMC6"], "armclang")] +
                     self.flags['common'] + self.flags['cxx'])
        self.asm = [join(TOOLCHAIN_PATHS["ARMC6"], "armasm")]
        self.asm += self.flags['asm']
        self.ld = [join(TOOLCHAIN_PATHS["ARMC6"], "armlink")]
        self.ld += self.flags['ld']
        self.ar = join(TOOLCHAIN_PATHS["ARMC6"], "armar")
        self.elf2bin = join(TOOLCHAIN_PATHS["ARMC6"], "fromelf")

        # Adding this for safety since this inherits the `version_check`
        # function but does not call the constructor of ARM_STD, so the
        # `product_name` variable is not initialized.
        self.product_name = None
Esempio n. 23
0
    def generate(self):
        """Generate the makefile

        Note: subclasses should not need to override this method
        """
        self.resources.win_to_unix()

        to_be_compiled = [
            splitext(src)[0] + ".o" for src in self.resources.s_sources +
            self.resources.c_sources + self.resources.cpp_sources
        ]

        libraries = [splitext(lib)[0][3:] for lib in self.resources.libraries]

        ctx = {
            'name':
            self.project_name,
            'to_be_compiled':
            to_be_compiled,
            'object_files':
            self.resources.objects,
            'include_paths':
            list(set(self.resources.inc_dirs)),
            'library_paths':
            self.resources.lib_dirs,
            'linker_script':
            self.resources.linker_script,
            'libraries':
            libraries,
            'hex_files':
            self.resources.hex_files,
            'vpath': (["../../.."] if
                      (basename(dirname(dirname(self.export_dir)))
                       == "projectfiles") else [".."]),
            'cc_cmd':
            " ".join(["\"" + part + "\"" for part in self.toolchain.cc]),
            'cppc_cmd':
            " ".join(["\"" + part + "\"" for part in self.toolchain.cppc]),
            'asm_cmd':
            " ".join(["\"" + part + "\"" for part in self.toolchain.asm]),
            'ld_cmd':
            " ".join(["\"" + part + "\"" for part in self.toolchain.ld]),
            'elf2bin_cmd':
            self.toolchain.elf2bin,
            'link_script_ext':
            self.toolchain.LINKER_EXT,
            'link_script_option':
            self.LINK_SCRIPT_OPTION,
        }

        for key in [
                'include_paths', 'library_paths', 'linker_script', 'hex_files'
        ]:
            if isinstance(ctx[key], list):
                ctx[key] = [ctx['vpath'][0] + "/" + t for t in ctx[key]]
            else:
                ctx[key] = ctx['vpath'][0] + "/" + ctx[key]
        if "../." not in ctx["include_paths"]:
            ctx["include_paths"] += ['../.']
        for key in [
                'include_paths', 'library_paths', 'hex_files', 'to_be_compiled'
        ]:
            ctx[key] = sorted(ctx[key])
        ctx.update(self.flags)

        for templatefile in \
            ['makefile/%s_%s.tmpl' % (self.NAME.lower(),
                                      self.target.lower())] + \
            ['makefile/%s_%s.tmpl' % (self.NAME.lower(),
                                      label.lower()) for label
             in self.toolchain.target.extra_labels] +\
            ['makefile/%s.tmpl' % self.NAME.lower()]:
            try:
                self.gen_file(templatefile, ctx, 'Makefile')
                break
            except TemplateNotFound:
                pass
        else:
            raise NotSupportedException("This make tool is in development")