Пример #1
0
def test_sim(capsys):
    class Args():
        sim = None
        testbench = None
        target = None
        keep = False
        backendargs = None
        setup = True
        build_only = False
        no_export = False

        def __init__(self, system):
            self.system = system

    from fusesoc.config import Config
    from fusesoc.coremanager import CoreManager

    build_root = os.path.join(tests_dir, 'build')
    config = Config()
    config.build_root = build_root
    config.cache_root = cache_root

    common_cm = CoreManager(config)
    common_cm.add_cores_root(cores_root)
    args = Args(system="wb_common")
    with pytest.raises(SystemExit):
        sim(common_cm, args)
    out, err = capsys.readouterr()
    assert out == ""
    #Workaround since this test fails with Travis on Python2.7. No idea why
    import sys
    if sys.version_info[0] > 2:
        assert err == "No tool was supplied on command line or found in 'wb_common' core description\n"
Пример #2
0
def test_sim(capsys):

    class Args():
        sim = None
        testbench = None
        target = None
        keep = False
        backendargs = None
        setup = True
        build_only = False
        no_export = False
        def __init__(self, system):
            self.system = system

    from fusesoc.config import Config
    from fusesoc.coremanager import CoreManager

    build_root = os.path.join(tests_dir, 'build')
    config = Config()
    config.build_root = build_root
    config.cache_root = cache_root

    common_cm = CoreManager(config)
    common_cm.add_cores_root(cores_root)
    args = Args(system="wb_common")
    with pytest.raises(SystemExit):
        sim(common_cm, args)
    out, err = capsys.readouterr()
    assert out == ""
    #Workaround since this test fails with Travis on Python2.7. No idea why
    import sys
    if sys.version_info[0] > 2:
        assert err == "No tool was supplied on command line or found in 'wb_common' core description\n"
Пример #3
0
    def run(self):
        if Config().verbose:
            pr_info(self.cwd)
            pr_info('    ' + str(self))
        try:
            subprocess.check_call([self.cmd] + self.args,
                                  cwd=self.cwd,
                                  env=self.env,
                                  shell=self.shell,
                                  stderr=self.stderr,
                                  stdout=self.stdout,
                                  stdin=subprocess.PIPE),
        except FileNotFoundError:
            raise RuntimeError("Command '" + self.cmd +
                               "' not found. Make sure it is in $PATH")
        except subprocess.CalledProcessError:
            if self.stderr is None:
                output = "stderr"
            else:
                output = self.stderr.name
                if Config().verbose:
                    with open(self.stderr.name, 'r') as f:
                        pr_err(f.read())

            if self.errormsg is None:
                self.errormsg = '"' + str(
                    self
                ) + '" exited with an error code.\nERROR: See ' + output + ' for details.'
            raise RuntimeError(self.errormsg)
Пример #4
0
def init(cm, args):
    # Fix Python 2.x.
    global input
    try:
        input = raw_input
    except NameError:
        pass

    xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or \
                      os.path.join(os.path.expanduser('~'), '.config')
    config_file = os.path.join(xdg_config_home, 'fusesoc', 'fusesoc.conf')


    if os.path.exists(config_file):
        logger.warning("'{}' already exists. Aborting".format(config_file))
        exit(1)
        #TODO. Prepend cores_root to file if it doesn't exist
        f = open(config_file, 'w+')
    else:
        logger.info("Writing configuration file to '{}'".format(config_file))
        if not os.path.exists(os.path.dirname(config_file)):
            os.makedirs(os.path.dirname(config_file))
        f = open(config_file,'w+')

    config = Config(file=f)

    xdg_data_home = os.environ.get('XDG_DATA_HOME') or \
             os.path.join(os.path.expanduser('~'), '.local/share')
    library_root = os.path.join(xdg_data_home, 'fusesoc')
    _repo_paths = []
    for repo in REPOS:
        name = repo[0]
        library = {
                'sync-uri': repo[1],
                'sync-type': 'git'
                }

        default_dir = os.path.join(library_root, name)
        prompt = 'Directory to use for {} ({}) [{}] : '
        if args.y:
            location = None
        else:
            location = input(prompt.format(repo[0], repo[2], default_dir))
        if location:
            library['location'] = location
        else:
            location = default_dir
        if os.path.exists(location):
            logger.warning("'{}' already exists. This library will not be added to fusesoc.conf".format(location))
            #TODO: Prompt for overwrite
        else:
            logger.info("Initializing {}".format(name))
            try:
                config.add_library(name, library)
            except RuntimeError as e:
                logger.error("Init failed: " + str(e))
                exit(1)
    logger.info("FuseSoC is ready to use!")
Пример #5
0
def init(cm, args):
    warnings.warn(
        "The 'init' subcommand is deprecated and will be removed in the next "
        "release. It was intended to fetch the FuseSoC standard library. This can be done with 'fusesoc library add fusesoc_cores https://github.com/fusesoc/fusesoc-cores' instead.",
        FutureWarning,
    )
    # Fix Python 2.x.
    global input
    try:
        input = raw_input
    except NameError:
        pass

    xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
        os.path.expanduser("~"), ".config")
    config_file = os.path.join(xdg_config_home, "fusesoc", "fusesoc.conf")

    if os.path.exists(config_file):
        logger.warning(f"'{config_file}' already exists. Aborting")
        exit(1)
        # TODO. Prepend cores_root to file if it doesn't exist
        f = open(config_file, "w+")
    else:
        logger.info(f"Writing configuration file to '{config_file}'")
        if not os.path.exists(os.path.dirname(config_file)):
            os.makedirs(os.path.dirname(config_file))
        f = open(config_file, "w+")

    config = Config(file=f)

    _repo_paths = []
    for repo in REPOS:
        name = repo[0]
        uri = repo[1]
        default_dir = os.path.join(cm._lm.library_root, name)
        prompt = "Directory to use for {} ({}) [{}] : "
        if args.y:
            location = None
        else:
            location = input(prompt.format(repo[0], repo[2], default_dir))
        if not location:
            location = default_dir
        if os.path.exists(location):
            logger.warning(
                "'{}' already exists. This library will not be added to fusesoc.conf"
                .format(location))
            # TODO: Prompt for overwrite
        else:
            logger.info(f"Initializing {name}")
            try:
                library = Library(name, location, "git", uri, True)
                config.add_library(library)
            except RuntimeError as e:
                logger.error("Init failed: " + str(e))
                exit(1)
    logger.info("FuseSoC is ready to use!")
Пример #6
0
def test_library_update(caplog):
    from fusesoc.main import update, init_coremanager, init_logging

    clone_target = tempfile.mkdtemp()

    try:
        subprocess.call(['git', 'clone', sync_uri, clone_target])

        tcf = tempfile.TemporaryFile(mode="w+")
        tcf.write(
            EXAMPLE_CONFIG.format(build_root=build_root,
                                  cache_root=cache_root,
                                  cores_root=clone_target,
                                  library_root=library_root,
                                  auto_sync='false',
                                  sync_uri=sync_uri))
        tcf.seek(0)

        conf = Config(file=tcf)

        args = Namespace()

        init_logging(False, False)
        cm = init_coremanager(conf, [])

        # TODO find a better way to set up these defaults
        args.libraries = []

        with caplog.at_level(logging.INFO):
            update(cm, args)

        assert not "Updating 'test_lib'" in caplog.text

        caplog.clear()

        args.libraries = ['test_lib']

        with caplog.at_level(logging.INFO):
            update(cm, args)

        assert "Updating 'test_lib'" in caplog.text

        caplog.clear()

        args.libraries = []
        conf.libraries['test_lib']['auto-sync'] = True

        with caplog.at_level(logging.INFO):
            update(cm, args)

        assert "Updating 'test_lib'" in caplog.text

        caplog.clear()

    finally:
        shutil.rmtree(clone_target)
Пример #7
0
def init(cm, args):
    # Fix Python 2.x.
    global input
    try:
        input = raw_input
    except NameError:
        pass

    xdg_config_home = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
        os.path.expanduser("~"), ".config"
    )
    config_file = os.path.join(xdg_config_home, "fusesoc", "fusesoc.conf")

    if os.path.exists(config_file):
        logger.warning("'{}' already exists. Aborting".format(config_file))
        exit(1)
        # TODO. Prepend cores_root to file if it doesn't exist
        f = open(config_file, "w+")
    else:
        logger.info("Writing configuration file to '{}'".format(config_file))
        if not os.path.exists(os.path.dirname(config_file)):
            os.makedirs(os.path.dirname(config_file))
        f = open(config_file, "w+")

    config = Config(file=f)

    _repo_paths = []
    for repo in REPOS:
        name = repo[0]
        uri = repo[1]
        default_dir = os.path.join(cm._lm.library_root, name)
        prompt = "Directory to use for {} ({}) [{}] : "
        if args.y:
            location = None
        else:
            location = input(prompt.format(repo[0], repo[2], default_dir))
        if not location:
            location = default_dir
        if os.path.exists(location):
            logger.warning(
                "'{}' already exists. This library will not be added to fusesoc.conf".format(
                    location
                )
            )
            # TODO: Prompt for overwrite
        else:
            logger.info("Initializing {}".format(name))
            try:
                library = Library(name, location, "git", uri, True)
                config.add_library(library)
            except RuntimeError as e:
                logger.error("Init failed: " + str(e))
                exit(1)
    logger.info("FuseSoC is ready to use!")
Пример #8
0
def get_core(core):
    from fusesoc.coremanager import CoreManager
    from fusesoc.config import Config
    from fusesoc.main import _get_core

    config = Config()
    config.build_root = build_root
    config.cache_root = cache_root
    cm = CoreManager(config)
    cm.add_cores_root(cores_root)

    return _get_core(cm, core)
Пример #9
0
def get_core(core):
    import os
    from fusesoc.config import Config
    from fusesoc.coremanager import CoreManager
    from fusesoc.main import _get_core

    tests_dir = os.path.dirname(__file__)

    Config().build_root = os.path.join(tests_dir, 'build')
    Config().cache_root = os.path.join(tests_dir, 'cache')
    cores_root = os.path.join(tests_dir, 'cores')

    CoreManager().add_cores_root(cores_root)
    return _get_core(core)
Пример #10
0
def test_library_location():
    from fusesoc.main import run

    tcf = tempfile.TemporaryFile(mode="w+")
    tcf.write(EXAMPLE_CONFIG.format(
            build_root = build_root,
            cache_root = cache_root,
            cores_root = cores_root,
            library_root = library_root,
            auto_sync = 'false',
            sync_uri = sync_uri
            )
        )
    tcf.seek(0)

    conf = Config(file=tcf)

    args = Namespace()

    # TODO find a better way to set up these defaults
    args.verbose = False
    args.monochrome = False
    args.cores_root = []
    vars(args)['32'] = False
    vars(args)['64'] = False

    args.config = tcf
    args.func = _run_test_util

    run(args)
Пример #11
0
    def configure(self, args):
        if os.path.exists(self.work_root):
            for f in os.listdir(self.work_root):
                if os.path.isdir(os.path.join(self.work_root, f)):
                    shutil.rmtree(os.path.join(self.work_root, f))
                else:
                    os.remove(os.path.join(self.work_root, f))
        else:
            os.makedirs(self.work_root)

        for name in self.cores:
            pr_info("Preparing " + str(name))
            core = self.cm.get_core(name)
            dst_dir = os.path.join(Config().build_root,
                                   self.system.sanitized_name, 'src',
                                   core.sanitized_name)
            try:
                core.setup()
            except URLError as e:
                raise RuntimeError("Problem while fetching '" + core.name +
                                   "': " + str(e.reason))
            except HTTPError as e:
                raise RuntimeError("Problem while fetching '" + core.name +
                                   "': " + str(e.reason))
            core.export(dst_dir)
Пример #12
0
 def get_scripts(self, flags):
     scripts = {}
     if self.scripts:
         env = {'BUILD_ROOT': Config().build_root}
         if flags['flow'] is 'sim':
             for s in [
                     'pre_build_scripts', 'pre_run_scripts',
                     'post_run_scripts'
             ]:
                 v = getattr(self.scripts, s)
                 if v:
                     scripts[s] = [{x: {'env': env}} for x in v]
         #For backwards compatibility we only use the script from the
         #top-level core in synth flows. We also rename them here to match
         #the backend stages and set the SYSTEM_ROOT env var
         elif flags['flow'] is 'synth' and flags['is_toplevel']:
             env['SYSTEM_ROOT'] = self.files_root
             v = self.scripts.pre_synth_scripts
             if v:
                 scripts['pre_build_scripts'] = [{
                     x: {
                         'env': env
                     }
                 } for x in v]
             v = self.scripts.post_impl_scripts
             if v:
                 scripts['post_build_scripts'] = [{
                     x: {
                         'env': env
                     }
                 } for x in v]
     return scripts
Пример #13
0
def test_virtual():
    import os
    import tempfile

    from fusesoc.config import Config
    from fusesoc.coremanager import CoreManager
    from fusesoc.edalizer import Edalizer
    from fusesoc.librarymanager import Library
    from fusesoc.vlnv import Vlnv

    flags = {"tool": "icarus"}

    build_root = tempfile.mkdtemp(prefix="export_")
    work_root = os.path.join(build_root, "work")

    core_dir = os.path.join(os.path.dirname(__file__), "capi2_cores",
                            "virtual")

    cm = CoreManager(Config())
    cm.add_library(Library("virtual", core_dir))

    root_core = cm.get_core(Vlnv("::user"))

    edalizer = Edalizer(
        toplevel=root_core.name,
        flags=flags,
        core_manager=cm,
        work_root=work_root,
    )
    edalizer.run()

    deps = cm.get_depends(root_core.name, {})
    deps_names = [str(c) for c in deps]

    assert deps_names == ["::impl2:0", "::user:0"]
Пример #14
0
    def build_SysC(self, core, work_root, src_root):
        verilator_root = utils.get_verilator_root()
        args = ['-I.']
        args += ['-MMD']
        args += ['-I'+src_root]
        args += ['-I'+s for s in self.include_dirs]
        args += ['-Iobj_dir']
        args += ['-I'+os.path.join(verilator_root,'include')]
        args += ['-I'+os.path.join(verilator_root,'include', 'vltstd')]  
        args += ['-DVL_PRINTF=printf']
        args += ['-DVM_TRACE=1']
        args += ['-DVM_COVERAGE=0']
        if os.getenv('SYSTEMC_INCLUDE'):
            args += ['-I'+os.getenv('SYSTEMC_INCLUDE')]
        if os.getenv('SYSTEMC'):
            args += ['-I'+os.path.join(os.getenv('SYSTEMC'),'include')]
        args += ['-Wno-deprecated']
        if os.getenv('SYSTEMC_CXX_FLAGS'):
             args += [os.getenv('SYSTEMC_CXX_FLAGS')]
        args += ['-c']
        args += ['-g']

        for src_file in core.verilator.src_files:
            pr_info("Compiling " + src_file.name)
            l = utils.Launcher('g++', args + [os.path.join(src_root, core.sanitized_name, src_file.name)],
                         cwd=work_root,
                         stderr = open(os.path.join(work_root, 'g++.err.log'),'a'))
            if Config().verbose:
                pr_info("  SystemC compilation working dir: " + work_root)
                pr_info("  SystemC compilation command: g++ " + ' '.join(args) + ' ' + os.path.join(src_root, core.sanitized_name, src_file.name))
            l.run()
Пример #15
0
 def build_CPP(self, core, sim_root, src_root):
     verilator_root = utils.get_verilator_root()
     if verilator_root is None:
         verilator_root = utils.get_verilator_root()
     args = ['-c']
     args += ['-I' + src_root]
     args += [
         '-I' + os.path.join(src_root, core.sanitized_name, s)
         for s in self.include_dirs
     ]
     args += ['-Iobj_dir']
     args += ['-I' + os.path.join(verilator_root, 'include')]
     args += ['-I' + os.path.join(verilator_root, 'include', 'vltstd')]
     for src_file in core.verilator.src_files:
         pr_info("Compiling " + src_file.name)
         l = utils.Launcher(
             'g++',
             args +
             [os.path.join(src_root, core.sanitized_name, src_file.name)],
             cwd=sim_root,
             stderr=open(os.path.join(sim_root, 'g++.err.log'), 'a'))
         if Config().verbose:
             pr_info("  C++ compilation working dir: " + sim_root)
             pr_info(
                 "  C++ compilation command: g++ " + ' '.join(args) + ' ' +
                 os.path.join(src_root, core.sanitized_name, src_file.name))
         l.run()
Пример #16
0
    def build(self):
        super(Verilator, self).build()
        self.archives = []
        for core_name in self.cores:
            core = self.cm.get_core(core_name)
            if core.verilator:
                 if core.verilator.archive:
                      self.archives += [core_name+'.a']
                 self.libs += core.verilator.libs
                 self.include_dirs += [os.path.join(self.src_root, core_name, d) for d in core.verilator.include_dirs]
        self.include_dirs += [os.path.dirname(os.path.join(self.sim_root, self.tb_toplevel))]

        self.include_dirs += [self.src_root]

        pr_info("Verilating source")
        self._verilate()
        for core_name in self.cores:
            core = self.cm.get_core(core_name)
            if core.verilator:
                 self._build(core, self.sim_root, self.src_root)

        pr_info("Building verilator executable:")
        args = ['-f', 'V' + self.top_module + '.mk', 'V' + self.top_module]
        l = utils.Launcher('make', args,
                       cwd=os.path.join(self.sim_root, 'obj_dir'),
                       stdout = open(os.path.join(self.sim_root,
                                                  'verilator.make.log'),'w'))
        if Config().verbose:
             pr_info("  Verilator executable working dir: "
                     + os.path.join(self.sim_root, 'obj_dir'))
             pr_info("  Verilator executable command: make " + ' '.join(args))
        l.run()
Пример #17
0
def test_library_add():
    from fusesoc.main import add_library
    from fusesoc.coremanager import CoreManager

    tcf = tempfile.NamedTemporaryFile(mode="w+")

    conf = Config(file=tcf)
    cm = CoreManager(conf)

    args = Namespace()

    args.name = 'fusesoc-cores'
    args.location = None
    args.config = tcf
    args.no_auto_sync = False
    vars(args)['sync-uri'] = sync_uri

    add_library(cm, args)

    expected = """[library.fusesoc-cores]
sync-uri = https://github.com/fusesoc/fusesoc-cores"""

    tcf.seek(0)
    result = tcf.read().strip()

    assert expected == result
Пример #18
0
    def __init__(self, system, export):
        self.system = system
        self.export = export
        self.TOOL_NAME = self.__class__.__name__.lower()
        build_root = os.path.join(Config().build_root,
                                  self.system.sanitized_name)

        self.src_root = os.path.join(build_root, 'src')
        self.work_root = os.path.join(build_root,
                                      self.TOOL_TYPE + '-' + self.TOOL_NAME)
        self.cm = CoreManager()
        self.cores = self.cm.get_depends(self.system.name)

        self.env = os.environ.copy()

        #FIXME: Remove BUILD_ROOT once cores have had some time
        # to migrate to SRC_ROOT/WORK_ROOT
        self.env['BUILD_ROOT'] = os.path.abspath(build_root)
        self.env['SRC_ROOT'] = os.path.abspath(self.src_root)
        self.env['WORK_ROOT'] = os.path.abspath(self.work_root)

        self.plusarg = OrderedDict()
        self.vlogparam = OrderedDict()
        self.vlogdefine = OrderedDict()
        self.generic = OrderedDict()
        self.cmdlinearg = OrderedDict()
        self.parsed_args = False
Пример #19
0
def fusesoc(args):
    init_logging(args.verbose, args.monochrome, args.log_file)
    config = Config(file=args.config)

    cm = init_coremanager(config, args.cores_root)
    # Run the function
    args.func(cm, args)
Пример #20
0
    def configure(self):
        if os.path.exists(self.sim_root):
            for f in os.listdir(self.sim_root):
                if os.path.isdir(os.path.join(self.sim_root, f)):
                    shutil.rmtree(os.path.join(self.sim_root, f))
                else:
                    os.remove(os.path.join(self.sim_root, f))
        else:
            os.makedirs(self.sim_root)

        self.env['SIM_ROOT'] = os.path.abspath(self.sim_root)

        for name in self.cores:
            pr_info("Preparing " + name)
            dst_dir = os.path.join(Config().build_root, self.system.name,
                                   'src', name)
            core = self.cm.get_core(name)
            try:
                core.setup()
            except urllib.URLError as e:
                raise RuntimeError("Problem while fetching '" + core.name +
                                   "': " + str(e.reason))
            except urllib.HTTPError as e:
                raise RuntimeError("Problem while fetching '" + core.name +
                                   "': " + str(e.reason))
            core.export(dst_dir)
Пример #21
0
def test_copyto():
    tests_dir = os.path.dirname(__file__)
    core      = get_core("copytocore")
    flags = {'tool' : 'icarus'}
    
    export_root = None
    work_root   = os.path.join(tests_dir,
                               'build',
                               core.name.sanitized_name,
                               core.get_work_root(flags))
    if os.path.exists(work_root):
        for f in os.listdir(work_root):
            if os.path.isdir(os.path.join(work_root, f)):
                shutil.rmtree(os.path.join(work_root, f))
            else:
                os.remove(os.path.join(work_root, f))
    else:
        os.makedirs(work_root)

    eda_api = CoreManager(Config()).setup(core.name, flags, work_root, None)

    assert eda_api['files'] == [{'file_type': 'user',
                                 'logical_name': '',
                                 'name': 'copied.file',
                                 'is_include_file': False},
                                {'file_type': 'tclSource',
                                 'logical_name': '',
                                 'name': 'subdir/another.file',
                                 'is_include_file': False}]
    assert os.path.exists(os.path.join(work_root, 'copied.file'))
    assert os.path.exists(os.path.join(work_root, 'subdir', 'another.file'))
Пример #22
0
    def build(self):
        super(Verilator, self).build()
        self.archives = []
        for core in self.cores:
            if core.verilator:
                 if core.verilator.archive:
                      self.archives += [core.sanitized_name+'.a']
                 self.libs += core.verilator.libs
                 self.include_dirs += [os.path.join(self.src_root, core.sanitized_name, d) for d in core.verilator.include_dirs]
        self.include_dirs += [os.path.dirname(os.path.join(self.work_root, self.tb_toplevel))]

        self.include_dirs += [self.src_root]

        pr_info("Verilating source")
        self._verilate()
        for core in self.cores:
            if core.verilator:
                 self._build(core, self.work_root, self.src_root)

        # Do parallel builds with <number of cpus> * 2 jobs.
        make_job_count = multiprocessing.cpu_count() * 2

        pr_info("Building verilator executable:")
        args = ['-f', 'V' + self.top_module + '.mk', '-j', str(make_job_count), 'V' + self.top_module]
        l = utils.Launcher('make', args,
                       cwd=os.path.join(self.work_root, 'obj_dir'),
                       stdout = open(os.path.join(self.work_root,
                                                  'verilator.make.log'),'w'))
        if Config().verbose:
             pr_info("  Verilator executable working dir: "
                     + os.path.join(self.work_root, 'obj_dir'))
             pr_info("  Verilator executable command: make " + ' '.join(args))
        l.run()
Пример #23
0
def run(args):
    level = logging.DEBUG if args.verbose else logging.INFO

    setup_logging(level=level, monchrome=args.monochrome)
    logger.debug("Command line arguments: " + str(sys.argv))
    if os.getenv("FUSESOC_CORES"):
        logger.debug("FUSESOC_CORES: " +
                     str(os.getenv("FUSESOC_CORES").split(':')))
    if args.verbose:
        logger.debug("Verbose output")
    else:
        logger.debug("Concise output")

    if args.monochrome:
        logger.debug("Monochrome output")
    else:
        logger.debug("Colorful output")

    cm = CoreManager()
    config = Config()

    # Get the environment variable for further cores
    env_cores_root = []
    if os.getenv("FUSESOC_CORES"):
        env_cores_root = os.getenv("FUSESOC_CORES").split(":")
    env_cores_root.reverse()

    for cores_root in [
            config.cores_root, config.systems_root, env_cores_root,
            args.cores_root
    ]:
        try:
            cm.add_cores_root(cores_root)
        except (RuntimeError, IOError) as e:
            logger.warning("Failed to register cores root '{}'".format(str(e)))
    # Process global options
    if vars(args)['32']:
        config.archbits = 32
        logger.debug("Forcing 32-bit mode")
    elif vars(args)['64']:
        config.archbits = 64
        logger.debug("Forcing 64-bit mode")
    else:
        config.archbits = 64 if platform.architecture()[0] == '64bit' else 32
        logger.debug("Autodetected " + str(config.archbits) + "-bit mode")
    # Run the function
    args.func(args)
Пример #24
0
def test_eda_api_vpi():
    import os.path
    import tempfile

    from fusesoc.config import Config
    from fusesoc.coremanager import CoreManager
    from fusesoc.vlnv import Vlnv

    tests_dir = os.path.dirname(__file__)
    build_root = tempfile.mkdtemp()
    cache_root = os.path.join(tests_dir, 'cache')
    cores_root = os.path.join(tests_dir, 'capi2_cores')
    work_root = os.path.join(build_root, 'work')
    export_root = os.path.join(build_root, 'src')
    config = Config()
    config.build_root = build_root
    config.cache_root = cache_root
    cm = CoreManager(config)
    cm.add_cores_root(cores_root)
    eda_api = cm.setup(Vlnv("vpi"), {'tool': 'icarus'}, work_root, export_root)
    expected = {
        'files': [],
        'hooks': {},
        'name':
        'vpi_0',
        'parameters': [],
        'tool_options': {
            'icarus': {}
        },
        'toplevel':
        'not_used',
        'version':
        '0.1.2',
        'vpi': [{
            'src_files': ['../src/vpi_0/f1', '../src/vpi_0/f3'],
            'include_dirs': ['../src/vpi_0/'],
            'libs': ['some_lib'],
            'name': 'vpi1'
        }, {
            'src_files': ['../src/vpi_0/f4'],
            'include_dirs': [],
            'libs': [],
            'name': 'vpi2'
        }]
    }
    assert eda_api == expected
Пример #25
0
def run(args):
    cm = CoreManager()
    config = Config()
    for cores_root in [
            config.cores_root, config.systems_root, args.cores_root
    ]:
        try:
            cm.add_cores_root(cores_root)
        except (RuntimeError, IOError) as e:
            pr_warn("Failed to register cores root '{}'".format(str(e)))
    # Process global options
    if vars(args)['32']:
        config.archbits = 32
        logger.debug("Forcing 32-bit mode")
    elif vars(args)['64']:
        config.archbits = 64
        logger.debug("Forcing 64-bit mode")
    else:
        config.archbits = 64 if platform.architecture()[0] == '64bit' else 32
        logger.debug("Autodetected " + str(config.archbits) + "-bit mode")
    config.monochrome = vars(args)['monochrome']
    if config.monochrome:
        logger.debug("Monochrome output")
    else:
        logger.debug("Colorful output")
    config.verbose = vars(args)['verbose']
    if config.verbose:
        logger.debug("Verbose output")
    else:
        logger.debug("Concise output")
    # Run the function
    args.func(args)
Пример #26
0
    def __init__(self):
        cfg_file = _ConfigFile("")
        cfg = Config(file=cfg_file)

        self.cm = CoreManagerW(cfg)

        packages_dir = get_packages_dir()
        project_dir = os.path.dirname(packages_dir)
        self.cm.add_library(Library("project", project_dir))
Пример #27
0
    def _write_build_rtl_tcl_file(self, tcl_main):
        tcl_build_rtl  = open(os.path.join(self.sim_root, "fusesoc_build_rtl.tcl"), 'w')

        (src_files, incdirs) = self._get_fileset_files(['sim', 'modelsim'])
        vlog_include_dirs = ['+incdir+'+d for d in incdirs]

        libs = []
        for f in src_files:
            if not f.logical_name:
                f.logical_name = 'work'
            if not f.logical_name in libs:
                tcl_build_rtl.write("vlib {}\n".format(f.logical_name))
                libs.append(f.logical_name)
            if f.file_type in ["verilogSource",
		               "verilogSource-95",
		               "verilogSource-2001",
		               "verilogSource-2005"]:
                cmd = 'vlog'
                args = self.vlog_options[:]
                args += vlog_include_dirs
            elif f.file_type in ["systemVerilogSource",
			         "systemVerilogSource-3.0",
			         "systemVerilogSource-3.1",
			         "systemVerilogSource-3.1a"]:
                cmd = 'vlog'
                args = self.vlog_options[:]
                args += ['-sv']
                args += vlog_include_dirs
            elif f.file_type == 'vhdlSource':
                cmd = 'vcom'
                args = []
            elif f.file_type == 'vhdlSource-87':
                cmd = 'vcom'
                args = ['-87']
            elif f.file_type == 'vhdlSource-93':
                cmd = 'vcom'
                args = ['-93']
            elif f.file_type == 'vhdlSource-2008':
                cmd = 'vcom'
                args = ['-2008']
            elif f.file_type == 'tclSource':
                cmd = None
                tcl_main.write("do {}\n".format(f.name))
            elif f.file_type == 'user':
                cmd = None
            else:
                _s = "{} has unknown file type '{}'"
                pr_warn(_s.format(f.name,
                                  f.file_type))
                cmd = None
            if cmd:
                if not Config().verbose:
                    args += ['-quiet']
                args += ['-work', f.logical_name]
                args += [f.name]
                tcl_build_rtl.write("{} {}\n".format(cmd, ' '.join(args)))
Пример #28
0
def get_sim(sim, core, export=False):
    import os.path
    from fusesoc.coremanager import CoreManager
    from fusesoc.config import Config
    from fusesoc.main import _import

    flags = {'flow': 'sim', 'tool': sim}

    eda_api = CoreManager().get_eda_api(core.name, flags)
    export_root = os.path.join(Config().build_root, core.name.sanitized_name,
                               'src')
    work_root = os.path.join(Config().build_root, core.name.sanitized_name,
                             'sim-' + sim)

    CoreManager().setup(core.name,
                        flags,
                        export=export,
                        export_root=export_root)
    return _import(sim)(eda_api=eda_api, work_root=work_root)
Пример #29
0
    def _write_build_rtl_tcl_file(self, tcl_main):
        tcl_build_rtl = open(
            os.path.join(self.work_root, "fusesoc_build_rtl.tcl"), 'w')

        (src_files, incdirs) = self._get_fileset_files(['sim', 'modelsim'])
        vlog_include_dirs = [
            '+incdir+' + d.replace('\\', '/') for d in incdirs
        ]

        libs = []
        for f in src_files:
            if not f.logical_name:
                f.logical_name = 'work'
            if not f.logical_name in libs:
                tcl_build_rtl.write("vlib {}\n".format(f.logical_name))
                libs.append(f.logical_name)
            if f.file_type.startswith("verilogSource") or \
               f.file_type.startswith("systemVerilogSource"):
                cmd = 'vlog'
                args = []

                if self.system.modelsim is not None:
                    args += self.system.modelsim.vlog_options

                for k, v in self.vlogdefine.items():
                    args += ['+define+{}={}'.format(k, v)]

                if f.file_type.startswith("systemVerilogSource"):
                    args += ['-sv']
                args += vlog_include_dirs
            elif f.file_type.startswith("vhdlSource"):
                cmd = 'vcom'
                if f.file_type.endswith("-87"):
                    args = ['-87']
                if f.file_type.endswith("-93"):
                    args = ['-93']
                if f.file_type.endswith("-2008"):
                    args = ['-2008']
                else:
                    args = []
            elif f.file_type == 'tclSource':
                cmd = None
                tcl_main.write("do {}\n".format(f.name))
            elif f.file_type == 'user':
                cmd = None
            else:
                _s = "{} has unknown file type '{}'"
                logger.warning(_s.format(f.name, f.file_type))
                cmd = None
            if cmd:
                if not Config().verbose:
                    args += ['-quiet']
                args += ['-work', f.logical_name]
                args += [f.name.replace('\\', '/')]
                tcl_build_rtl.write("{} {}\n".format(cmd, ' '.join(args)))
Пример #30
0
    def __init__(self, system):
        config = Config()
        self.system = system
        self.build_root = os.path.join(config.build_root, self.system.name)
        self.src_root = os.path.join(self.build_root, 'src')

        self.cm = CoreManager()
        self.cores = self.cm.get_depends(self.system.name)

        self.env = os.environ.copy()
        self.env['BUILD_ROOT'] = os.path.abspath(self.build_root)
Пример #31
0
def main():

    args = parse_args()
    if not args:
        exit(0)

    init_logging(args.verbose, args.monochrome, args.log_file)
    config = Config(file=args.config)
    cm = init_coremanager(config, args.cores_root)

    # Run the function
    args.func(cm, args)
Пример #32
0
def run(args):
    cm = CoreManager()
    config = Config()
    for cores_root in [config.cores_root,
                       config.systems_root,
                       args.cores_root]:
        try:
            cm.add_cores_root(cores_root)
        except (RuntimeError, IOError) as e:
            pr_warn("Failed to register cores root '{}'".format(str(e)))
    # Process global options
    if vars(args)['32']:
        config.archbits = 32
        logger.debug("Forcing 32-bit mode")
    elif vars(args)['64']:
        config.archbits = 64
        logger.debug("Forcing 64-bit mode")
    else:
        config.archbits = 64 if platform.architecture()[0] == '64bit' else 32
        logger.debug("Autodetected " + str(config.archbits) + "-bit mode")
    config.monochrome = vars(args)['monochrome']
    if config.monochrome:
        logger.debug("Monochrome output")
    else:
        logger.debug("Colorful output")
    config.verbose = vars(args)['verbose']
    if config.verbose:
        logger.debug("Verbose output")
    else:
        logger.debug("Concise output")
    # Run the function
    args.func(args)