Example #1
0
    def generate(self):
        """Generate the .uvproj file"""
        cache = Cache(True, False)
        if cache_d:
            cache.cache_descriptors()

        srcs = self.resources.headers + self.resources.s_sources + \
               self.resources.c_sources + self.resources.cpp_sources + \
               self.resources.objects + self.resources.libraries
        ctx = {
            'name': self.project_name,
            # project_files => dict of generators - file group to generator of
            # UVFile tuples defined above
            'project_files': sorted(list(self.format_src(srcs).iteritems()),
                                    key=lambda (group, _): group.lower()),
            'linker_script':self.resources.linker_script,
            'include_paths': '; '.join(self.resources.inc_dirs).encode('utf-8'),
            'device': DeviceUvision(self.target),
        }
        # Turn on FPU optimizations if the core has an FPU
        ctx['fpu_setting'] = 1 if 'f' not in ctx['device'].core.lower() \
                                  or 'd' in ctx['device'].core.lower() else 2
        ctx.update(self.format_flags())
        self.gen_file('uvision/uvision.tmpl', ctx, self.project_name+".uvprojx")
        self.gen_file('uvision/uvision_debug.tmpl', ctx, self.project_name + ".uvoptx")
Example #2
0
    def __init__(self, target):
        cache = Cache(True, False)
        data_path = join(save_data_path('arm-pack-manager'), "index.json")
        if not exists(data_path) or not self.check_version(data_path):
            cache.cache_descriptors()

        t = TARGET_MAP[target]
        self.core = t.core
        try:
            cpu_name = t.device_name
            target_info = cache.index[cpu_name]
        # Target does not have device name or pdsc file
        except:
            try:
                # Try to find the core as a generic CMSIS target
                cpu_name = self.cpu_cmsis()
                target_info = cache.index[cpu_name]
            except:
                raise TargetNotSupportedException("Target not in CMSIS packs")

        self.target_info = target_info

        self.url = target_info['pdsc_file']
        self.pack_url, self.pack_id = ntpath.split(self.url)
        self.dname = cpu_name
        self.dfpu = target_info['processor']['fpu']
        self.debug, self.dvendor = self.vendor_debug(target_info['vendor'])
        self.dendian = target_info['processor'].get('endianness',
                                                    'Little-endian')
        self.debug_svd = target_info.get('debug', '')
        self.compile_header = target_info['compile']['header']
Example #3
0
    def generate(self):
        """Generate the .uvproj file"""
        cache = Cache(True, False)
        if cache_d:
            cache.cache_descriptors()

        srcs = self.resources.headers + self.resources.s_sources + \
               self.resources.c_sources + self.resources.cpp_sources + \
               self.resources.objects + self.resources.libraries
        ctx = {
            'name':
            self.project_name,
            # project_files => dict of generators - file group to generator of
            # UVFile tuples defined above
            'project_files':
            sorted(list(self.format_src(srcs).iteritems()),
                   key=lambda (group, _): group.lower()),
            'linker_script':
            self.resources.linker_script,
            'include_paths':
            '; '.join(self.resources.inc_dirs).encode('utf-8'),
            'device':
            DeviceUvision(self.target),
        }
        core = ctx['device'].core
        ctx['cputype'] = core.rstrip("FD")
        # Turn on FPU optimizations if the core has an FPU
        ctx['fpu_setting'] = 1 if 'F' not in core or 'D' in core else 2
        ctx['fputype'] = self.format_fpu(core)
        ctx.update(self.format_flags())
        self.gen_file('uvision/uvision.tmpl', ctx,
                      self.project_name + ".uvprojx")
        self.gen_file('uvision/uvision_debug.tmpl', ctx,
                      self.project_name + ".uvoptx")
Example #4
0
    def generate(self):
        """Generate the .uvproj file"""
        cache = Cache(True, False)
        if cache_d:
            cache.cache_descriptors()

        srcs = self.resources.headers + self.resources.s_sources + \
               self.resources.c_sources + self.resources.cpp_sources + \
               self.resources.objects + self.resources.libraries
        ctx = {
            'name': self.project_name,
            # project_files => dict of generators - file group to generator of
            # UVFile tuples defined above
            'project_files': sorted(list(self.format_src(srcs).iteritems()),
                                    key=lambda (group, _): group.lower()),
            'linker_script':self.toolchain.correct_scatter_shebang(
                self.resources.linker_script),
            'include_paths': '; '.join(self.resources.inc_dirs).encode('utf-8'),
            'device': DeviceUvision(self.target),
        }
        if ctx['linker_script'] is not self.resources.linker_script:
            self.generated_files.append(ctx['linker_script'])
        core = ctx['device'].core
        ctx['cputype'] = core.rstrip("FD")
        if core.endswith("FD"):
            ctx['fpu_setting'] = 3
        elif core.endswith("F"):
            ctx['fpu_setting'] = 2
        else:
            ctx['fpu_setting'] = 1
        ctx['fputype'] = self.format_fpu(core)
        ctx.update(self.format_flags())
        self.gen_file('uvision/uvision.tmpl', ctx, self.project_name+".uvprojx")
        self.gen_file('uvision/uvision_debug.tmpl', ctx, self.project_name + ".uvoptx")
Example #5
0
    def generate(self):
        """Generate the .uvproj file"""
        cache = Cache(True, False)
        if cache_d:
            cache.cache_descriptors()

        srcs = self.resources.headers + self.resources.s_sources + \
               self.resources.c_sources + self.resources.cpp_sources + \
               self.resources.objects + self.resources.libraries
        ctx = {
            'name': self.project_name,
            # project_files => dict of generators - file group to generator of
            # UVFile tuples defined above
            'project_files': sorted(list(self.format_src(srcs).iteritems()),
                                    key=lambda (group, _): group.lower()),
            'linker_script':self.resources.linker_script,
            'include_paths': '; '.join(self.resources.inc_dirs).encode('utf-8'),
            'device': DeviceUvision(self.target),
        }
        core = ctx['device'].core
        ctx['cputype'] = core.rstrip("FD")
        if core.endswith("FD"):
            ctx['fpu_setting'] = 3
        elif core.endswith("F"):
            ctx['fpu_setting'] = 2
        else:
            ctx['fpu_setting'] = 1
        ctx['fputype'] = self.format_fpu(core)
        ctx.update(self.format_flags())
        self.gen_file('uvision/uvision.tmpl', ctx, self.project_name+".uvprojx")
        self.gen_file('uvision/uvision_debug.tmpl', ctx, self.project_name + ".uvoptx")
Example #6
0
    def generate(self):
        """Generate the .uvproj file"""
        cache = Cache(True, False)
        if cache_d:
            cache.cache_descriptors()

        srcs = self.resources.headers + self.resources.s_sources + \
               self.resources.c_sources + self.resources.cpp_sources + \
               self.resources.objects + self.resources.libraries
        ctx = {
            'name': self.project_name,
            'project_files': self.format_src(srcs),
            'linker_script': self.resources.linker_script,
            'include_paths':
            '; '.join(self.resources.inc_dirs).encode('utf-8'),
            'device': DeviceUvision(self.target),
        }
        # Turn on FPU optimizations if the core has an FPU
        ctx['fpu_setting'] = 1 if 'f' not in ctx['device'].core.lower() \
                                  or 'd' in ctx['device'].core.lower() else 2
        ctx.update(self.format_flags())
        self.gen_file('uvision/uvision.tmpl', ctx,
                      self.project_name + ".uvprojx")
        self.gen_file('uvision/uvision_debug.tmpl', ctx,
                      self.project_name + ".uvoptx")
Example #7
0
 def regions(self):
     """Generate a list of regions from the config"""
     if not self.target.bootloader_supported:
         raise ConfigException("Bootloader not supported on this target.")
     cmsis_part = Cache(False, False).index[self.target.device_name]
     target_overrides = self.app_config_data['target_overrides'].get(
         self.target.name, {})
     if (('target.bootloader_img' in target_overrides
          or 'target.restrict_size' in target_overrides)
             and ('target.mbed_app_start' in target_overrides
                  or 'target.mbed_app_size' in target_overrides)):
         raise ConfigException(
             "target.bootloader_img and target.restirct_size are "
             "incompatible with target.mbed_app_start and "
             "target.mbed_app_size")
     try:
         rom_size = int(cmsis_part['memory']['IROM1']['size'], 0)
         rom_start = int(cmsis_part['memory']['IROM1']['start'], 0)
     except KeyError:
         raise ConfigException("Not enough information in CMSIS packs to "
                               "build a bootloader project")
     if ('target.bootloader_img' in target_overrides
             or 'target.restrict_size' in target_overrides):
         return self._generate_booloader_build(target_overrides, rom_size,
                                               rom_size)
     elif ('target.mbed_app_start' in target_overrides
           or 'target.mbed_app_size' in target_overrides):
         return self._generate_linker_overrides(target_overrides, rom_start,
                                                rom_size)
     else:
         raise ConfigException(
             "Bootloader build requested but no bootlader configuration")
def test_device_name():
    """Assert device name is in a pack"""
    cache = Cache(True, True)
    named_targets = (target for target in TARGETS if
                     hasattr(target, "device_name"))
    for target in named_targets:
        assert target.device_name in cache.index,\
            ("Target %s contains invalid device_name %s" %
             (target.name, target.device_name))
Example #9
0
 def sectors(self):
     """Return a list of tuples of sector start,size"""
     cache = Cache(False, False)
     if self.target.device_name not in cache.index:
         raise ConfigException("Bootloader not supported on this target: "
                               "targets.json `device_name` not found in "
                               "arm_pack_manager index.")
     cmsis_part = cache.index[self.target.device_name]
     sectors = cmsis_part['sectors']
     if sectors:
         return sectors
     raise ConfigException("No sector info available")
Example #10
0
def test_bl_has_sectors():
    """Assert a bootloader supporting pack has sector information"""
    cache = Cache(True, True)
    named_targets = (target for target in TARGETS
                     if (hasattr(target, "device_name")
                         and getattr(target, "bootloader_supported", False)))
    for target in named_targets:
        assert target.device_name in cache.index,\
            ("Target %s contains invalid device_name %s" %
             (target.name, target.device_name))
        assert cache.index[target.device_name]["sectors"],\
            ("Device name %s is misssing sector information" %
             (target.device_name))
Example #11
0
def main():
    """Generate flash algorithms"""
    parser = argparse.ArgumentParser(description='Flash generator')
    parser.add_argument("--rebuild_all",
                        action="store_true",
                        help="Rebuild entire cache")
    parser.add_argument("--rebuild_descriptors",
                        action="store_true",
                        help="Rebuild descriptors")
    parser.add_argument("--target",
                        default=None,
                        help="Name of target to generate algo for")
    parser.add_argument("--all",
                        action="store_true",
                        help="Build all flash algos for devcies")
    args = parser.parse_args()

    cache = Cache(True, True)
    if args.rebuild_all:
        cache.cache_everything()
        print("Cache rebuilt")
        return

    if args.rebuild_descriptors:
        cache.cache_descriptors()
        print("Descriptors rebuilt")
        return

    if args.target is None:
        device_and_filenames = [(target.device_name, target.name)
                                for target in TARGETS
                                if hasattr(target, "device_name")]
    else:
        device_and_filenames = [(args.target, args.target.replace("/", "-"))]

    try:
        os.mkdir("output")
    except OSError:
        # Directory already exists
        pass

    for device, filename in device_and_filenames:
        dev = cache.index[device]
        binaries = cache.get_flash_algorthim_binary(device, all=True)
        algos = [PackFlashAlgo(binary.read()) for binary in binaries]
        filtered_algos = algos if args.all else filter_algos(dev, algos)
        for idx, algo in enumerate(filtered_algos):
            file_name = ("%s_%i.c" % (filename, idx) if args.all
                         or len(filtered_algos) != 1 else "%s.c" % filename)
            output_path = join("output", file_name)
            algo.process_template(TEMPLATE_PATH, output_path)
        print("%s: %s      \r" % (device, filename))
Example #12
0
        def thunk(parsed_args):
            cache = Cache(not parsed_args.verbose, parsed_args.no_timeouts)
            argv = [
                arg['dest'] if 'dest' in arg else arg['name'] for arg in args
            ]
            argv = [
                (arg if isinstance(arg, basestring) else arg[-1]).strip('-')
                for arg in argv
            ]
            argv = {
                arg: vars(parsed_args)[arg]
                for arg in argv if vars(parsed_args)[arg] is not None
            }

            return command(cache, **argv)
Example #13
0
def main():
    """Generate flash algorithms"""
    parser = argparse.ArgumentParser(description='Flash generator')
    parser.add_argument("--rebuild_all", action="store_true",
                        help="Rebuild entire cache")
    parser.add_argument("--rebuild_descriptors", action="store_true",
                        help="Rebuild descriptors")
    parser.add_argument("--target", default=None,
                        help="Name of target to generate algo for")
    parser.add_argument("--all", action="store_true",
                        help="Build all flash algos for devcies")
    args = parser.parse_args()

    cache = Cache(True, True)
    if args.rebuild_all:
        cache.cache_everything()
        print("Cache rebuilt")
        return

    if args.rebuild_descriptors:
        cache.cache_descriptors()
        print("Descriptors rebuilt")
        return

    if args.target is None:
        device_and_filenames = [(target.device_name, target.name) for target
                                in TARGETS if hasattr(target, "device_name")]
    else:
        device_and_filenames = [(args.target, args.target.replace("/", "-"))]

    try:
        os.mkdir("output")
    except OSError:
        # Directory already exists
        pass

    for device, filename in device_and_filenames:
        dev = cache.index[device]
        binaries = cache.get_flash_algorthim_binary(device, all=True)
        algos = [PackFlashAlgo(binary.read()) for binary in binaries]
        filtered_algos = algos if args.all else filter_algos(dev, algos)
        for idx, algo in enumerate(filtered_algos):
            file_name = ("%s_%i.c" % (filename, idx)
                         if args.all or len(filtered_algos) != 1
                         else "%s.c" % filename)
            output_path = join("output", file_name)
            algo.process_template(TEMPLATE_PATH, output_path)
        print("%s: %s      \r" % (device, filename))
Example #14
0
 def regions(self):
     """Generate a list of regions from the config"""
     if not self.target.bootloader_supported:
         raise ConfigException("Bootloader not supported on this target.")
     if not hasattr(self.target, "device_name"):
         raise ConfigException("Bootloader not supported on this target: "
                               "targets.json `device_name` not specified.")
     cache = Cache(False, False)
     if self.target.device_name not in cache.index:
         raise ConfigException("Bootloader not supported on this target: "
                               "targets.json `device_name` not found in "
                               "arm_pack_manager index.")
     cmsis_part = cache.index[self.target.device_name]
     if ((self.target.bootloader_img or self.target.restrict_size)
             and (self.target.mbed_app_start or self.target.mbed_app_size)):
         raise ConfigException(
             "target.bootloader_img and target.restirct_size are "
             "incompatible with target.mbed_app_start and "
             "target.mbed_app_size")
     try:
         rom_size = int(cmsis_part['memory']['IROM1']['size'], 0)
         rom_start = int(cmsis_part['memory']['IROM1']['start'], 0)
     except KeyError:
         try:
             rom_size = int(cmsis_part['memory']['PROGRAM_FLASH']['size'],
                            0)
             rom_start = int(cmsis_part['memory']['PROGRAM_FLASH']['start'],
                             0)
         except KeyError:
             raise ConfigException(
                 "Not enough information in CMSIS packs to "
                 "build a bootloader project")
     if self.target.bootloader_img or self.target.restrict_size:
         return self._generate_bootloader_build(rom_start, rom_size)
     elif self.target.mbed_app_start or self.target.mbed_app_size:
         return self._generate_linker_overrides(rom_start, rom_size)
     else:
         raise ConfigException(
             "Bootloader build requested but no bootlader configuration")
Example #15
0
 def regions(self):
     """Generate a list of regions from the config"""
     if not self.target.bootloader_supported:
         raise ConfigException("Bootloader not supported on this target.")
     cmsis_part = Cache(False, False).index[self.target.device_name]
     start = 0
     target_overrides = self.app_config_data['target_overrides'].get(
         self.target.name, {})
     try:
         rom_size = int(cmsis_part['memory']['IROM1']['size'], 0)
         rom_start = int(cmsis_part['memory']['IROM1']['start'], 0)
     except KeyError:
         raise ConfigException("Not enough information in CMSIS packs to "
                               "build a bootloader project")
     if 'target.bootloader_img' in target_overrides:
         filename = target_overrides['target.bootloader_img']
         if not exists(filename):
             raise ConfigException("Bootloader %s not found" % filename)
         part = intelhex_offset(filename, offset=rom_start)
         if part.minaddr() != rom_start:
             raise ConfigException("bootloader executable does not "
                                   "start at 0x%x" % rom_start)
         part_size = (part.maxaddr() - part.minaddr()) + 1
         yield Region("bootloader", rom_start + start, part_size, False,
                      filename)
         start += part_size
     if 'target.restrict_size' in target_overrides:
         new_size = int(target_overrides['target.restrict_size'], 0)
         yield Region("application", rom_start + start, new_size, True,
                      None)
         start += new_size
         yield Region("post_application", rom_start + start,
                      rom_size - start, False, None)
     else:
         yield Region("application", rom_start + start, rom_size - start,
                      True, None)
     if start > rom_size:
         raise ConfigException("Not enough memory on device to fit all "
                               "application regions")
Example #16
0
def main():
    """Entry point"""
    # Parse Options
    parser = ArgumentParser()

    targetnames = TARGET_NAMES
    targetnames.sort()
    toolchainlist = EXPORTERS.keys()
    toolchainlist.sort()

    parser.add_argument("-m", "--mcu",
                        metavar="MCU",
                        default='LPC1768',
                        type=argparse_force_uppercase_type(targetnames, "MCU"),
                        help="generate project for the given MCU ({})".format(
                            ', '.join(targetnames)))

    parser.add_argument("-i",
                        dest="ide",
                        default='uvision',
                        type=argparse_force_lowercase_type(
                            toolchainlist, "toolchain"),
                        help="The target IDE: %s"% str(toolchainlist))

    parser.add_argument("-c", "--clean",
                        action="store_true",
                        default=False,
                        help="clean the export directory")

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument(
        "-p",
        type=test_known,
        dest="program",
        help="The index of the desired test program: [0-%s]"% (len(TESTS)-1))

    group.add_argument("-n",
                       type=test_name_known,
                       dest="program",
                       help="The name of the desired test program")

    parser.add_argument("-b",
                      dest="build",
                      default=False,
                      action="store_true",
                      help="use the mbed library build, instead of the sources")

    group.add_argument("-L", "--list-tests",
                       action="store_true",
                       dest="list_tests",
                       default=False,
                       help="list available programs in order and exit")

    group.add_argument("-S", "--list-matrix",
                       action="store_true",
                       dest="supported_ides",
                       default=False,
                       help="displays supported matrix of MCUs and IDEs")

    parser.add_argument("-E",
                        action="store_true",
                        dest="supported_ides_html",
                        default=False,
                        help="writes tools/export/README.md")

    parser.add_argument("--source",
                        action="append",
                        type=argparse_filestring_type,
                        dest="source_dir",
                        default=[],
                        help="The source (input) directory")

    parser.add_argument("-D",
                        action="append",
                        dest="macros",
                        help="Add a macro definition")

    parser.add_argument("--profile",
                        type=argparse_filestring_type,
                        default=[],
                        help="Toolchain profile")

    parser.add_argument("--update-packs",
                        dest="update_packs",
                        action="store_true",
                        default=False)

    options = parser.parse_args()

    # Print available tests in order and exit
    if options.list_tests is True:
        print '\n'.join([str(test) for test in  sorted(TEST_MAP.values())])
        sys.exit()

    # Only prints matrix of supported IDEs
    if options.supported_ides:
        print_large_string(mcu_ide_matrix())
        exit(0)

    # Only prints matrix of supported IDEs
    if options.supported_ides_html:
        html = mcu_ide_matrix(verbose_html=True)
        try:
            with open("./export/README.md", "w") as readme:
                readme.write("Exporter IDE/Platform Support\n")
                readme.write("-----------------------------------\n")
                readme.write("\n")
                readme.write(html)
        except IOError as exc:
            print "I/O error({0}): {1}".format(exc.errno, exc.strerror)
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise
        exit(0)

    if options.update_packs:
        from tools.arm_pack_manager import Cache
        cache = Cache(True, True)
        cache.cache_descriptors()

    # Clean Export Directory
    if options.clean:
        if exists(EXPORT_DIR):
            rmtree(EXPORT_DIR)

    for mcu in options.mcu:
        zip_proj = not bool(options.source_dir)

    # Target
    if not options.mcu:
        args_error(parser, "argument -m/--mcu is required")

    # Toolchain
    if not options.ide:
        args_error(parser, "argument -i is required")

    if (options.program is None) and (not options.source_dir):
        args_error(parser, "one of -p, -n, or --source is required")
        # Export to selected toolchain
    exporter, toolchain_name = get_exporter_toolchain(options.ide)
    if options.mcu not in exporter.TARGETS:
        args_error(parser, "%s not supported by %s"%(options.mcu,options.ide))
    profile = extract_profile(parser, options, toolchain_name)
    export(options.mcu, options.ide, build=options.build,
           src=options.source_dir, macros=options.macros,
           project_id=options.program, clean=options.clean,
           zip_proj=zip_proj, build_profile=profile)
Example #17
0
    def generate_bars(self, file_desc, device_name=None):
        """ Generates nice looking bars that represent the memory consumption

        Returns: string containing nice looking bars
        """

        # TODO add tty detection, and width detection probably
        WIDTH = 72
        try:
            # NOTE this only works on linux
            import sys, fcntl, termios, struct
            height, width, _, _ = struct.unpack(
                'HHHH',
                fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ,
                            struct.pack('HHHH', 0, 0, 0, 0)))
            WIDTH = min(width, WIDTH)
        except Exception:
            pass

        text = self.subtotal['.text']
        data = self.subtotal['.data']
        bss = self.subtotal['.bss']
        rom_used = self.mem_summary['total_flash']
        ram_used = self.mem_summary['static_ram']

        # No device_name = no cmsis-pack = we don't know the memory layout
        if device_name is not None:
            try:
                cache = Cache(False, False)
                cmsis_part = cache.index[device_name]
                rom_avail = int(cmsis_part['memory']['IROM1']['size'], 0)
                ram_avail = int(cmsis_part['memory']['IRAM1']['size'], 0)
            except KeyError:
                # If we don't have the expected regions, fall back to no device_name
                device_name = None

        PREFIXES = ['', 'K', 'M', 'G', 'T', 'P', 'E']

        def unit(n, u='B', p=3):
            if n == 0:
                return '0' + u

            scale = math.floor(math.log(n, 1024))
            return '{1:.{0}g}{2}{3}'.format(p, n / (1024**scale),
                                            PREFIXES[int(scale)], u)

        usage = "Text {} Data {} BSS {}".format(unit(text), unit(data),
                                                unit(bss))
        avail = "ROM {} RAM {}".format(unit(rom_used), unit(ram_used))
        output = [
            "{0} {1:>{2}}".format(
                usage, avail,
                abs(WIDTH - len(usage) - 1) if device_name is not None else 0)
        ]

        if device_name is not None:
            for region, avail, uses in [('ROM', rom_avail, [('|', text),
                                                            ('|', data)]),
                                        ('RAM', ram_avail, [('|', bss),
                                                            ('|', data)])]:
                barwidth = WIDTH - 17 - len(region)

                used = sum(use for c, use in uses)
                bars = [(c, (barwidth * use) // avail) for c, use in uses]
                bars.append((' ', barwidth - sum(width for c, width in bars)))
                bars = ''.join(c * width for c, width in bars)

                output.append("{0} [{2:<{1}}] {3:>13}".format(
                    region, barwidth, bars,
                    "{}/{}".format(unit(used), unit(avail))))

        return '\n'.join(output)
Example #18
0
class DeviceCMSIS():
    """CMSIS Device class

    Encapsulates target information retrieved by arm-pack-manager"""

    CACHE = Cache(True, False)

    def __init__(self, target):
        target_info = self.check_supported(target)
        if not target_info:
            raise TargetNotSupportedException(
                "Target not supported in CMSIS pack")
        self.url = target_info['pdsc_file']
        self.pack_url, self.pack_id = ntpath.split(self.url)
        self.dname = target_info["_cpu_name"]
        self.core = target_info["_core"]
        self.dfpu = target_info['processor']['fpu']
        self.debug, self.dvendor = self.vendor_debug(target_info['vendor'])
        self.dendian = target_info['processor'].get('endianness',
                                                    'Little-endian')
        self.debug_svd = target_info.get('debug', '')
        self.compile_header = target_info['compile']['header']
        self.target_info = target_info

    @staticmethod
    def check_supported(target):
        t = TARGET_MAP[target]
        try:
            cpu_name = t.device_name
            target_info = DeviceCMSIS.CACHE.index[cpu_name]
        # Target does not have device name or pdsc file
        except:
            try:
                # Try to find the core as a generic CMSIS target
                cpu_name = DeviceCMSIS.cpu_cmsis(t.core)
                target_info = DeviceCMSIS.CACHE.index[cpu_name]
            except:
                return False
        target_info["_cpu_name"] = cpu_name
        target_info["_core"] = t.core
        return target_info

    def vendor_debug(self, vendor):
        """Reads the vendor from a PDSC <dvendor> tag.
        This tag contains some additional numeric information that is meaningless
        for our purposes, so we use a regex to filter.

        Positional arguments:
        Vendor - information in <dvendor> tag scraped from ArmPackManager

        Returns a tuple of (debugger, vendor)
        """
        reg = "([\w\s]+):?\d*?"
        m = re.search(reg, vendor)
        vendor_match = m.group(1) if m else None
        debug_map = {
            'STMicroelectronics': 'ST-Link',
            'Silicon Labs': 'J-LINK',
            'Nuvoton': 'NULink'
        }
        return debug_map.get(vendor_match, "CMSIS-DAP"), vendor_match

    @staticmethod
    def cpu_cmsis(cpu):
        """
        Transforms information from targets.json to the way the generic cores are named
        in CMSIS PDSC files.
        Ex:
        Cortex-M4F => ARMCM4_FP, Cortex-M0+ => ARMCM0P
        Returns formatted CPU
        """
        cpu = cpu.replace("Cortex-", "ARMC")
        cpu = cpu.replace("+", "P")
        cpu = cpu.replace("F", "_FP")
        return cpu
def main():
    """Entry point"""
    # Parse Options
    options, parser = get_args(sys.argv[1:])

    # Print available tests in order and exit
    if options.list_tests:
        print('\n'.join(str(test) for test in sorted(TEST_MAP.values())))
    elif options.supported_ides:
        if options.supported_ides == "matrix":
            print_large_string(mcu_ide_matrix())
        elif options.supported_ides == "ides":
            print(mcu_ide_list())
    elif options.supported_ides_html:
        html = mcu_ide_matrix(verbose_html=True)
        with open("README.md", "w") as readme:
            readme.write("Exporter IDE/Platform Support\n")
            readme.write("-----------------------------------\n")
            readme.write("\n")
            readme.write(html)
    elif options.update_packs:
        from tools.arm_pack_manager import Cache
        cache = Cache(True, True)
        cache.cache_everything()
    else:
        # Check required arguments
        if not options.mcu:
            args_error(parser, "argument -m/--mcu is required")
        if not options.ide:
            args_error(parser, "argument -i is required")
        if (options.program is None) and (not options.source_dir):
            args_error(parser, "one of -p, -n, or --source is required")

        if options.clean:
            clean(options.source_dir)

        ide = resolve_exporter_alias(options.ide)
        exporter, toolchain_name = get_exporter_toolchain(ide)
        profile = extract_profile(parser,
                                  options,
                                  toolchain_name,
                                  fallback="debug")
        mcu = extract_mcus(parser, options)[0]
        if not exporter.is_target_supported(mcu):
            args_error(parser, "%s not supported by %s" % (mcu, ide))

        try:
            export(mcu,
                   ide,
                   build=options.build,
                   src=options.source_dir,
                   macros=options.macros,
                   project_id=options.program,
                   zip_proj=not bool(options.source_dir) or options.zip,
                   build_profile=profile,
                   app_config=options.app_config,
                   export_path=options.build_dir,
                   ignore=options.ignore)
        except NotSupportedException as exc:
            args_error(parser, "%s not supported by %s" % (mcu, ide))
            print("[Not Supported] %s" % str(exc))
    exit(0)
Example #20
0
class DeviceCMSIS():
    """CMSIS Device class

    Encapsulates target information retrieved by arm-pack-manager"""

    # TODO: This class uses the TARGET_MAP. Usage of the target map may
    # not work in the online compiler or may work but give the incorrect
    # information.
    CACHE = Cache(True, False)
    def __init__(self, target):
        target_info = self.check_supported(target)
        if not target_info:
            raise TargetNotSupportedException("Target not supported in CMSIS pack")
        self.pack_url = target_info['from_pack']['url']
        self.pack_id = "{}.{}.{}".format(
            target_info['from_pack']['vendor'],
            target_info['from_pack']['pack'],
            target_info['from_pack']['version']
        )
        self.dname = target_info["name"]
        self.core = target_info["_core"]
        self.dfpu = None
        try:
            self.dfpu = target_info['processor']['Symmetric']['fpu']
        except KeyError:
            # TODO: refactor this into a "base_core_for" function
            cmsis_core = self.core.replace("F", "").replace("-", "").replace("E", "")
            cmsis_core = cmsis_core.replace("NS", "")
            for core_name, proc in target_info['processor']['Asymmetric'].items():
                if proc['core'] == cmsis_core:
                    self.dfpu = proc['fpu']
                    self.dname = '{}:{}'.format(self.dname, core_name)
                    break
        self.debug, self.dvendor = self.vendor_debug(
            target_info.get('vendor') or target_info['from_pack']['vendor']
        )
        self.dendian = target_info['processor'].get(
            'endianness', 'Little-endian'
        )
        self.debug_svd = target_info.get('debug', '')
        self.target_info = target_info

    @staticmethod
    def check_supported(target):
        t = TARGET_MAP[target]
        try:
            cpu_name = t.device_name
            target_info = DeviceCMSIS.CACHE.index[cpu_name]
        # Target does not have device name or pdsc file
        except:
            try:
                # Try to find the core as a generic CMSIS target
                cpu_name = DeviceCMSIS.cpu_cmsis(t.core)
                target_info = DeviceCMSIS.CACHE.index[cpu_name]
            except:
                return False
        target_info["_cpu_name"] = cpu_name
        target_info["_core"] = t.core
        return target_info

    def vendor_debug(self, vendor):
        """Reads the vendor from a PDSC <dvendor> tag.
        This tag contains some additional numeric information that is meaningless
        for our purposes, so we use a regex to filter.

        Positional arguments:
        Vendor - information in <dvendor> tag scraped from ArmPackManager

        Returns a tuple of (debugger, vendor)
        """
        reg = "([\w\s]+):?\d*?"
        m = re.search(reg, vendor)
        vendor_match = m.group(1) if m else None
        debug_map ={
            'STMicroelectronics':'ST-Link',
            'Silicon Labs':'J-LINK',
            'Nuvoton':'NULink'
        }
        return debug_map.get(vendor_match, "CMSIS-DAP"), vendor_match

    @staticmethod
    def cpu_cmsis(cpu):
        """
        Transforms information from targets.json to the way the generic cores are named
        in CMSIS PDSC files.
        Ex:
        Cortex-M4F => ARMCM4_FP, Cortex-M0+ => ARMCM0P
        Returns formatted CPU
        """
        cpu = cpu.replace("Cortex-","ARMC")
        cpu = cpu.replace("+","P")
        cpu = cpu.replace("F","_FP")
        cpu = cpu.replace("-NS", "")
        return cpu
Example #21
0
def main():
    """Entry point"""
    # Parse Options
    parser = ArgumentParser()

    targetnames = TARGET_NAMES
    targetnames.sort()
    toolchainlist = EXPORTERS.keys()
    toolchainlist.sort()

    parser.add_argument("-m",
                        "--mcu",
                        metavar="MCU",
                        type=str.upper,
                        help="generate project for the given MCU ({})".format(
                            ', '.join(targetnames)))

    parser.add_argument("-i",
                        dest="ide",
                        type=argparse_force_lowercase_type(
                            toolchainlist, "toolchain"),
                        help="The target IDE: %s" % str(toolchainlist))

    parser.add_argument("-c",
                        "--clean",
                        action="store_true",
                        default=False,
                        help="clean the export directory")

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument("-p",
                       type=test_known,
                       dest="program",
                       help="The index of the desired test program: [0-%s]" %
                       (len(TESTS) - 1))

    group.add_argument("-n",
                       type=test_name_known,
                       dest="program",
                       help="The name of the desired test program")

    parser.add_argument(
        "-b",
        dest="build",
        default=False,
        action="store_true",
        help="use the mbed library build, instead of the sources")

    group.add_argument("-L",
                       "--list-tests",
                       action="store_true",
                       dest="list_tests",
                       default=False,
                       help="list available programs in order and exit")

    group.add_argument("-S",
                       "--list-matrix",
                       dest="supported_ides",
                       default=False,
                       const="matrix",
                       choices=["matrix", "ides"],
                       nargs="?",
                       help="displays supported matrix of MCUs and IDEs")

    parser.add_argument("-E",
                        action="store_true",
                        dest="supported_ides_html",
                        default=False,
                        help="writes tools/export/README.md")

    parser.add_argument("--source",
                        action="append",
                        type=argparse_filestring_type,
                        dest="source_dir",
                        default=[],
                        help="The source (input) directory")

    parser.add_argument("-D",
                        action="append",
                        dest="macros",
                        help="Add a macro definition")

    parser.add_argument("--profile", dest="profile", action="append",
                        type=argparse_profile_filestring_type,
                        help="Build profile to use. Can be either path to json" \
                        "file or one of the default one ({})".format(", ".join(list_profiles())),
                        default=[])

    parser.add_argument("--update-packs",
                        dest="update_packs",
                        action="store_true",
                        default=False)
    parser.add_argument("--app-config", dest="app_config", default=None)

    options = parser.parse_args()

    # Print available tests in order and exit
    if options.list_tests is True:
        print '\n'.join([str(test) for test in sorted(TEST_MAP.values())])
        sys.exit()

    # Only prints matrix of supported IDEs
    if options.supported_ides:
        if options.supported_ides == "matrix":
            print_large_string(mcu_ide_matrix())
        elif options.supported_ides == "ides":
            print mcu_ide_list()
        exit(0)

    # Only prints matrix of supported IDEs
    if options.supported_ides_html:
        html = mcu_ide_matrix(verbose_html=True)
        try:
            with open("./export/README.md", "w") as readme:
                readme.write("Exporter IDE/Platform Support\n")
                readme.write("-----------------------------------\n")
                readme.write("\n")
                readme.write(html)
        except IOError as exc:
            print "I/O error({0}): {1}".format(exc.errno, exc.strerror)
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise
        exit(0)

    if options.update_packs:
        from tools.arm_pack_manager import Cache
        cache = Cache(True, True)
        cache.cache_everything()

    # Target
    if not options.mcu:
        args_error(parser, "argument -m/--mcu is required")

    # Toolchain
    if not options.ide:
        args_error(parser, "argument -i is required")

    # Clean Export Directory
    if options.clean:
        if exists(EXPORT_DIR):
            rmtree(EXPORT_DIR)

    zip_proj = not bool(options.source_dir)

    if (options.program is None) and (not options.source_dir):
        args_error(parser, "one of -p, -n, or --source is required")
    exporter, toolchain_name = get_exporter_toolchain(options.ide)
    mcu = extract_mcus(parser, options)[0]
    if not exporter.is_target_supported(mcu):
        args_error(parser, "%s not supported by %s" % (mcu, options.ide))
    profile = extract_profile(parser,
                              options,
                              toolchain_name,
                              fallback="debug")
    if options.clean:
        rmtree(BUILD_DIR)
    try:
        export(mcu,
               options.ide,
               build=options.build,
               src=options.source_dir,
               macros=options.macros,
               project_id=options.program,
               zip_proj=zip_proj,
               build_profile=profile,
               app_config=options.app_config)
    except NotSupportedException as exc:
        print "[ERROR] %s" % str(exc)
Example #22
0
def main():
    """Entry point"""
    # Parse Options
    parser = ArgumentParser()

    targetnames = TARGET_NAMES
    targetnames.sort()
    toolchainlist = list(EXPORTERS.keys())
    toolchainlist.sort()

    parser.add_argument("-m", "--mcu",
                        metavar="MCU",
                        help="generate project for the given MCU ({})".format(
                            ', '.join(targetnames)))

    parser.add_argument("-i",
                        dest="ide",
                        type=argparse_force_lowercase_type(
                            toolchainlist, "toolchain"),
                        help="The target IDE: %s"% str(toolchainlist))

    parser.add_argument("-c", "--clean",
                        action="store_true",
                        default=False,
                        help="clean the export directory")

    group = parser.add_mutually_exclusive_group(required=False)
    group.add_argument(
        "-p",
        type=test_known,
        dest="program",
        help="The index of the desired test program: [0-%s]"% (len(TESTS)-1))

    group.add_argument("-n",
                       type=test_name_known,
                       dest="program",
                       help="The name of the desired test program")

    parser.add_argument("-b",
                      dest="build",
                      default=False,
                      action="store_true",
                      help="use the mbed library build, instead of the sources")

    group.add_argument("-L", "--list-tests",
                       action="store_true",
                       dest="list_tests",
                       default=False,
                       help="list available programs in order and exit")

    group.add_argument("-S", "--list-matrix",
                       dest="supported_ides",
                       default=False,
                       const="matrix",
                       choices=["matrix", "ides"],
                       nargs="?",
                       help="displays supported matrix of MCUs and IDEs")

    parser.add_argument("-E",
                        action="store_true",
                        dest="supported_ides_html",
                        default=False,
                        help="writes tools/export/README.md")

    parser.add_argument("--build",
                        type=argparse_filestring_type,
                        dest="build_dir",
                        default=None,
                        help="Directory for the exported project files")

    parser.add_argument("--source",
                        action="append",
                        type=argparse_filestring_type,
                        dest="source_dir",
                        default=[],
                        help="The source (input) directory")

    parser.add_argument("-D",
                        action="append",
                        dest="macros",
                        help="Add a macro definition")

    parser.add_argument("--profile", dest="profile", action="append",
                        type=argparse_profile_filestring_type,
                        help="Build profile to use. Can be either path to json" \
                        "file or one of the default one ({})".format(", ".join(list_profiles())),
                        default=[])

    parser.add_argument("--update-packs",
                        dest="update_packs",
                        action="store_true",
                        default=False)
    parser.add_argument("--app-config",
                        dest="app_config",
                        default=None)

    parser.add_argument("--ignore", dest="ignore", type=argparse_many(str),
                        default=None, help="Comma separated list of patterns to add to mbedignore (eg. ./main.cpp)")

    options = parser.parse_args()

    # Print available tests in order and exit
    if options.list_tests is True:
        print('\n'.join([str(test) for test in  sorted(TEST_MAP.values())]))
        sys.exit()

    # Only prints matrix of supported IDEs
    if options.supported_ides:
        if options.supported_ides == "matrix":
            print_large_string(mcu_ide_matrix())
        elif options.supported_ides == "ides":
            print(mcu_ide_list())
        exit(0)

    # Only prints matrix of supported IDEs
    if options.supported_ides_html:
        html = mcu_ide_matrix(verbose_html=True)
        try:
            with open("./export/README.md", "w") as readme:
                readme.write("Exporter IDE/Platform Support\n")
                readme.write("-----------------------------------\n")
                readme.write("\n")
                readme.write(html)
        except IOError as exc:
            print("I/O error({0}): {1}".format(exc.errno, exc.strerror))
        except:
            print("Unexpected error:", sys.exc_info()[0])
            raise
        exit(0)

    if options.update_packs:
        from tools.arm_pack_manager import Cache
        cache = Cache(True, True)
        cache.cache_everything()

    # Target
    if not options.mcu:
        args_error(parser, "argument -m/--mcu is required")

    # Toolchain
    if not options.ide:
        args_error(parser, "argument -i is required")

    # Clean Export Directory
    if options.clean:
        if exists(EXPORT_DIR):
            rmtree(EXPORT_DIR)

    zip_proj = not bool(options.source_dir)

    notify = TerminalNotifier()

    if (options.program is None) and (not options.source_dir):
        args_error(parser, "one of -p, -n, or --source is required")
    exporter, toolchain_name = get_exporter_toolchain(options.ide)
    mcu = extract_mcus(parser, options)[0]
    if not exporter.is_target_supported(mcu):
        args_error(parser, "%s not supported by %s"%(mcu,options.ide))
    profile = extract_profile(parser, options, toolchain_name, fallback="debug")
    if options.clean:
        for cls in EXPORTERS.values():
            try:
                cls.clean(basename(abspath(options.source_dir[0])))
            except (NotImplementedError, IOError, OSError):
                pass
        for f in list(EXPORTERS.values())[0].CLEAN_FILES:
            try:
                remove(f)
            except (IOError, OSError):
                pass
    try:
        export(mcu, options.ide, build=options.build,
               src=options.source_dir, macros=options.macros,
               project_id=options.program, zip_proj=zip_proj,
               build_profile=profile, app_config=options.app_config,
               export_path=options.build_dir, notify=notify,
               ignore=options.ignore)
    except NotSupportedException as exc:
        print("[ERROR] %s" % str(exc))