コード例 #1
0
ファイル: benchmark.py プロジェクト: ttwj/ppci
def compile_nos_for_riscv():
    """ Compile nOS for riscv architecture. """
    logging.basicConfig(level=logging.INFO)
    murax_folder = os.path.join(this_dir, "..", "examples", "riscvmurax")
    arch = api.get_arch("riscv")

    # Gather sources:
    path = os.path.join(murax_folder, "csrc", "nos")
    folders, srcs = get_sources(path, "*.c")
    folders += [os.path.join(murax_folder, "csrc")]
    print(srcs)

    coptions = COptions()
    for folder in folders:
        coptions.add_include_path(folder)

    # Build code:
    o1 = api.asm(os.path.join(murax_folder, "start.s"), arch)
    o2 = api.asm(os.path.join(murax_folder, "nOSPortasm.s"), arch)
    objs = [o1, o2]

    for src in srcs:
        with open(src) as f:
            objs.append(api.cc(f, "riscv", coptions=coptions, debug=True))

    # Link code:
    api.link(
        objs,
        os.path.join(murax_folder, "firmware.mmap"),
        use_runtime=True,
        debug=True,
    )
コード例 #2
0
def partial_build(src, lang, bsp_c3, opt_level, march, reporter):
    """ Compile source and return an object """
    if lang == 'c3':
        srcs = [relpath('..', 'librt', 'io.c3'), bsp_c3, io.StringIO(src)]
        o2 = c3c(srcs, [],
                 march,
                 opt_level=opt_level,
                 reporter=reporter,
                 debug=True)
        objs = [o2]
    elif lang == 'bf':
        o3 = bfcompile(src, march, reporter=reporter)
        o2 = c3c([bsp_c3], [], march, reporter=reporter)
        objs = [o2, o3]
    elif lang == 'c':
        o2 = c3c([bsp_c3], [], march, reporter=reporter)
        coptions = COptions()
        include_path1 = relpath('..', 'librt', 'libc')
        coptions.add_include_path(include_path1)
        with open(relpath('..', 'librt', 'libc', 'lib.c'), 'r') as f:
            o3 = cc(f, march, coptions=coptions, debug=True, reporter=reporter)
        o4 = cc(io.StringIO(src),
                march,
                coptions=coptions,
                debug=True,
                reporter=reporter)
        objs = [o2, o3, o4]
    else:
        raise NotImplementedError('language not implemented')
    obj = link(objs,
               partial_link=True,
               use_runtime=True,
               reporter=reporter,
               debug=True)
    return obj
コード例 #3
0
def build_sample_to_ir(src, lang, bsp_c3, march, reporter):
    """ Compile the given sample into ir-modules """
    if lang == "c3":
        ir_modules = [
            api.c3_to_ir(
                [bsp_c3, relpath("..", "librt", "io.c3"), io.StringIO(src)],
                [],
                march,
                reporter=reporter,
            )
        ]
    elif lang == "bf":
        ir_modules = [api.bf_to_ir(src, march)]
    elif lang == "c":
        coptions = COptions()
        include_path1 = relpath("..", "librt", "libc")
        lib = relpath("..", "librt", "libc", "lib.c")
        coptions.add_include_path(include_path1)
        with open(lib, "r") as f:
            mod1 = api.c_to_ir(f, march, coptions=coptions, reporter=reporter)
        mod2 = api.c_to_ir(
            io.StringIO(src), march, coptions=coptions, reporter=reporter
        )
        ir_modules = [mod1, mod2]
    elif lang == "pas":
        pascal_ir_modules = api.pascal_to_ir(
            [io.StringIO(src)], api.get_arch(march)
        )
        ir_modules = pascal_ir_modules
    else:  # pragma: no cover
        raise NotImplementedError("Language {} not implemented".format(lang))
    return ir_modules
コード例 #4
0
    def do(self, src, expected_output, lang='c3'):
        base_filename = make_filename(self.id())
        sample_filename = base_filename + '.py'
        list_filename = base_filename + '.html'

        bsp = io.StringIO("""
           module bsp;
           public function void putc(byte c);
           """)
        march = 'arm'
        with HtmlReportGenerator(open(list_filename, 'w')) as reporter:
            if lang == 'c3':
                ir_modules = [
                    c3_to_ir([
                        relpath('..', 'librt', 'io.c3'), bsp,
                        io.StringIO(src)
                    ], [],
                             march,
                             reporter=reporter)
                ]
            elif lang == 'bf':
                ir_modules = [bf_to_ir(src, march)]
            elif lang == 'c':
                coptions = COptions()
                include_path1 = relpath('..', 'librt', 'libc')
                lib = relpath('..', 'librt', 'libc', 'lib.c')
                coptions.add_include_path(include_path1)
                with open(lib, 'r') as f:
                    mod1 = c_to_ir(f,
                                   march,
                                   coptions=coptions,
                                   reporter=reporter)
                mod2 = c_to_ir(io.StringIO(src),
                               march,
                               coptions=coptions,
                               reporter=reporter)
                ir_modules = [mod1, mod2]
            else:  # pragma: no cover
                raise NotImplementedError(
                    'Language {} not implemented'.format(lang))

            # Test roundtrip of ir_modules

            for ir_module in ir_modules:
                serialization_roundtrip(ir_module)
                optimize(ir_module, level=self.opt_level, reporter=reporter)

            with open(sample_filename, 'w') as f:
                ir_to_python(ir_modules, f, reporter=reporter)

                # Add glue:
                print('', file=f)
                print('def bsp_putc(c):', file=f)
                print('    print(chr(c), end="")', file=f)
                print('main_main()', file=f)

        res = run_python(sample_filename)
        self.assertEqual(expected_output, res)
コード例 #5
0
def do_compile(filename):
    coptions = COptions()
    include_paths = [
        libc_includes,
        src_folder,
    ]
    coptions.add_include_paths(include_paths)
    with open(filename, 'r') as f:
        obj = cc(f, arch, coptions=coptions)
    return obj
コード例 #6
0
def do_compile(filename):
    include_paths = [
        os.path.join(musl_folder, 'include'),
        os.path.join(musl_folder, 'src', 'internal'),
        os.path.join(musl_folder, 'obj', 'include'),
        os.path.join(musl_folder, 'arch', 'x86_64'),
        os.path.join(musl_folder, 'arch', 'generic'),
    ]
    coptions = COptions()
    coptions.add_include_paths(include_paths)
    with open(filename, 'r') as f:
        obj = cc(f, 'x86_64', coptions=coptions)
    return obj
コード例 #7
0
def build_sample_to_code(src, lang, bsp_c3, opt_level, march, debug, reporter):
    """ Turn example sample into code objects. """
    if lang == "c3":
        srcs = [relpath("..", "librt", "io.c3"), bsp_c3, io.StringIO(src)]
        o2 = api.c3c(
            srcs,
            [],
            march,
            opt_level=opt_level,
            reporter=reporter,
            debug=debug,
        )
        objs = [o2]
    elif lang == "bf":
        o3 = api.bfcompile(src, march, reporter=reporter)
        o2 = api.c3c([bsp_c3], [], march, reporter=reporter)
        objs = [o2, o3]
    elif lang == "c":
        o2 = api.c3c([bsp_c3], [], march, reporter=reporter)
        coptions = COptions()
        libc_path = relpath("..", "librt", "libc")
        include_path1 = os.path.join(libc_path, "include")
        coptions.add_include_path(include_path1)
        with open(relpath("..", "librt", "libc", "lib.c"), "r") as f:
            o3 = api.cc(f,
                        march,
                        coptions=coptions,
                        debug=debug,
                        reporter=reporter)
        o4 = api.cc(
            io.StringIO(src),
            march,
            coptions=coptions,
            debug=debug,
            reporter=reporter,
        )
        objs = [o2, o3, o4]
    elif lang == "pas":
        o3 = api.pascal([io.StringIO(src)],
                        march,
                        reporter=reporter,
                        debug=debug)
        o2 = api.c3c([bsp_c3], [], march, reporter=reporter)
        objs = [o2, o3]
    else:
        raise NotImplementedError("language not implemented")
    return objs
コード例 #8
0
    def test_function(self):
        coptions = COptions()
        coptions.enable("trigraphs")
        coptions.add_include_path(test_t_directory)
        libc_dir = os.path.join(this_dir, "..", "..", "..", "librt", "libc")
        coptions.add_include_path(libc_dir)

        output_file = io.StringIO()
        with open(filename, "r") as f:
            preprocess(f, output_file, coptions)
        # TODO: check output for correct values:
        print(output_file.getvalue())
コード例 #9
0
def do_compile(filename):
    include_paths = [
        os.path.join(newlib_folder, 'libc', 'include'),
        libc_includes,
    ]
    coptions = COptions()
    coptions.add_include_paths(include_paths)
    coptions.add_define('HAVE_CONFIG_H')
    coptions.add_define('__MSP430__')
    with open(filename, 'r') as f:
        obj = cc(f, arch, coptions=coptions)
    return obj
コード例 #10
0
ファイル: compile_links.py プロジェクト: vpoulailleau/ppci
def main():
    t1 = time.time()
    failed = 0
    passed = 0
    sources = glob.iglob(os.path.join(links_folder, '*.c'))
    objs = []
    coptions = COptions()
    include_paths = [
        libc_includes,
        links_folder,
        '/usr/include',
        ]
    coptions.add_include_paths(include_paths)
    with open(report_filename, 'w') as f, HtmlReportGenerator(f) as reporter:
        for filename in sources:
            filename = os.path.join(links_folder, filename)
            print('      ======================')
            print('    ========================')
            print('  ==> Compiling', filename)
            try:
                obj = do_compile(filename, coptions, reporter)
                objs.append(obj)
            except CompilerError as ex:
                print('Error:', ex.msg, ex.loc)
                ex.print()
                print_exc()
                failed += 1
            except Exception as ex:
                print('General exception:', ex)
                print_exc()
                failed += 1
            else:
                print('Great success!')
                passed += 1

    t2 = time.time()
    elapsed = t2 - t1
    print('Passed:', passed, 'failed:', failed, 'in', elapsed, 'seconds')
    obj = link(objs)
    print(obj)
コード例 #11
0
ファイル: compile_lcc.py プロジェクト: vpoulailleau/ppci
def do_compile(filename, include_paths, arch, reporter):
    coptions = COptions()
    coptions.add_include_paths(include_paths)
    coptions.add_define("FPM_DEFAULT", "1")
    with open(filename, "r") as f:
        obj = cc(f, arch, coptions=coptions, reporter=reporter)
    return obj
コード例 #12
0
def main():
    t1 = time.time()
    failed = 0
    passed = 0
    include_paths = [
        # os.path.join(newlib_folder, 'libc', 'include'),
        # TODO: not sure about the include path below for stddef.h:
        # '/usr/lib/gcc/x86_64-pc-linux-gnu/7.1.1/include'
        libc_includes,
        micropython_folder,
        port_folder,
    ]
    coptions = COptions()
    coptions.add_include_paths(include_paths)
    coptions.enable('freestanding')
    coptions.add_define('NO_QSTR', '1')
    file_pattern = os.path.join(micropython_folder, 'py', '*.c')
    objs = []
    for filename in glob.iglob(file_pattern):
        print('==> Compiling', filename)
        try:
            obj = do_compile(filename, coptions)
        except CompilerError as ex:
            print('Error:', ex.msg, ex.loc)
            ex.print()
            print_exc()
            failed += 1
            # break
        except Exception as ex:
            print('General exception:', ex)
            print_exc()
            failed += 1
            # break
        else:
            print('Great success!', obj)
            passed += 1
            objs.append(obj)

    t2 = time.time()
    elapsed = t2 - t1
    print('Passed:', passed, 'failed:', failed, 'in', elapsed, 'seconds')
コード例 #13
0
def perform_test(filename):
    """ Try to compile the given snippet. """
    logger.info("Step 1: Compile %s!", filename)
    march = "x86_64"

    html_report = os.path.splitext(filename)[0] + "_report.html"

    coptions = COptions()
    root_folder = os.path.join(this_dir, "..", "..", "..")
    libc_folder = os.path.join(root_folder, "librt", "libc")
    libc_include = os.path.join(libc_folder, "include")
    coptions.add_include_path(libc_include)

    # TODO: this should be injected elsewhere?
    coptions.add_define('__LP64__', '1')
    # coptions.enable('freestanding')

    with html_reporter(html_report) as reporter:
        with open(filename, "r") as f:
            try:
                obj1 = api.cc(f, march, coptions=coptions, reporter=reporter)
            except CompilerError as ex:
                ex.print()
                raise
    logger.info("Compilation complete, %s", obj1)

    obj0 = api.asm(io.StringIO(STARTERCODE), march)
    obj2 = api.c3c([io.StringIO(BSP_C3_SRC)], [], march)
    with open(os.path.join(libc_include, "lib.c"), "r") as f:
        obj3 = api.cc(f, march, coptions=coptions)

    obj = api.link([obj0, obj1, obj2, obj3], layout=io.StringIO(ARCH_MMAP))

    logger.info("Step 2: Run it!")

    exe_filename = os.path.splitext(filename)[0] + "_executable.elf"
    with open(exe_filename, "wb") as f:
        write_elf(obj, f, type="executable")
    api.chmod_x(exe_filename)

    logger.info("Running %s", exe_filename)
    test_prog = subprocess.Popen(exe_filename, stdout=subprocess.PIPE)
    exit_code = test_prog.wait()
    assert exit_code == 0
    captured_stdout = test_prog.stdout.read().decode("ascii")

    with open(filename + ".expected", "r") as f:
        expected_stdout = f.read()

    # Compare stdout:
    assert captured_stdout == expected_stdout
コード例 #14
0
def perform_test(filename):
    """ Try to compile the given snippet. """
    logger.info("Step 1: Compile %s!", filename)
    march = "x86_64"
    coptions = COptions()
    libc_include = os.path.join(this_dir, "..", "..", "..", "librt", "libc")
    coptions.add_include_path(libc_include)
    coptions.enable('freestanding')
    with open(filename, "r") as f:
        try:
            obj = api.cc(f, march, coptions=coptions)
        except CompilerError as ex:
            ex.print()
            raise
    logger.info("Compilation complete, %s", obj)

    logger.info("Step 2: Run it!")
    logger.error("Running not yet implemented")
コード例 #15
0
ファイル: benchmark.py プロジェクト: ttwj/ppci
def compile_8cc():
    """ Compile the 8cc compiler.

    8cc homepage:
    https://github.com/rui314/8cc
    """

    home = os.environ['HOME']
    _8cc_folder = os.path.join(home, 'GIT', '8cc')
    libc_includes = os.path.join(this_dir, '..', 'librt', 'libc', 'include')
    linux_include_dir = '/usr/include'
    arch = api.get_arch('x86_64')
    coptions = COptions()
    include_paths = [
        libc_includes,
        _8cc_folder,
        linux_include_dir,
    ]
    coptions.add_include_paths(include_paths)
    coptions.add_define('BUILD_DIR', '"{}"'.format(_8cc_folder))

    sources = [
        'cpp.c',
        'debug.c',
        'dict.c',
        'gen.c',
        'lex.c',
        'vector.c',
        'parse.c',
        'buffer.c',
        'map.c',
        'error.c',
        'path.c',
        'file.c',
        'set.c',
        'encoding.c',
    ]
    objs = []
    for filename in sources:
        source_path = os.path.join(_8cc_folder, filename)
        with open(source_path, 'r') as f:
            objs.append(api.cc(f, arch, coptions=coptions))
コード例 #16
0
ファイル: mkfwc.py プロジェクト: ttwj/ppci
        for y in glob(os.path.join(x[0], extension)):
            resfiles.append(y)
        resdirs.append(x[0])
    return ((resdirs, resfiles))


with html_reporter('report.html') as reporter:
    arch = get_arch('riscv')
    o1 = asm("start.s", arch)
    o2 = asm("nOSPortasm.s", arch)
    path = os.path.join('.', 'csrc', argv[1])
    dirs, srcs = get_sources(path, '*.c')
    #srcs += [os.path.join('.','csrc','bsp.c')] + [os.path.join('.','csrc','lib.c')]
    dirs += [os.path.join('.', 'csrc')]
    obj = []
    coptions = COptions()
    for dir in dirs:
        coptions.add_include_path(dir)
    for src in srcs:
        with open(src) as f:
            obj.append(
                cc(f,
                   "riscv",
                   coptions=coptions,
                   debug=True,
                   reporter=reporter))
    obj = link([o1, o2] + obj,
               "firmware.mmap",
               use_runtime=True,
               reporter=reporter,
               debug=True)
コード例 #17
0
ファイル: analyze_c_code.py プロジェクト: ttwj/ppci
def analyze_sources(source_dir, defines):
    """ Analyze a directory with sourcecode """

    # Phase 1: acquire ast's:
    arch_info = get_arch('x86_64').info
    coptions = COptions()
    # TODO: infer defines from code:
    coptions.add_define('FPM_DEFAULT')
    coptions.add_include_path(source_dir)
    coptions.add_include_path(LIBC_INCLUDES)
    coptions.add_include_path('/usr/include')
    asts = []
    for source_filename in glob.iglob(os.path.join(source_dir, '*.c')):
        logger.info('Processing %s', source_filename)
        with open(source_filename, 'r') as f:
            source_code = f.read()
        f = io.StringIO(source_code)
        # ast = parse_text(source_code)
        try:
            ast = create_ast(
                f, arch_info, filename=source_filename, coptions=coptions)
            asts.append((source_filename, source_code, ast))
            # break
        except CompilerError as ex:
            print('Compiler error:', ex)
    logger.info("Got %s ast's", len(asts))

    # Phase 2: do some bad-ass analysis:
    global_variables = []
    functions = []
    for source_filename, source_code, ast in asts:
        for decl in ast.declarations:
            if isinstance(decl, declarations.VariableDeclaration):
                global_variables.append(decl)
            elif isinstance(decl, declarations.FunctionDeclaration):
                if decl.body is not None and decl.storage_class != 'static':
                    functions.append(decl)

    functions.sort(key=lambda d: d.name)

    # Phase 3: generate html report?
    with open('analyze_report.html', 'w') as f:
        c_lexer = CLexer()
        formatter = HtmlFormatter(lineanchors='fubar', linenos='inline')
        print('''<html>
        <head>
        <style>
        {}
        </style>
        </head>
        <body>
        '''.format(formatter.get_style_defs()), file=f)

        print('<h1>Overview</h1>', file=f)
        print('<table>', file=f)
        print(
            '<tr><th>Name</th><th>Location</th><th>typ</th></tr>',
            file=f)
        for func in functions:
            tagname = get_tag(func.location.filename)
            name = '<a href="#{2}-{1}">{0}</a>'.format(func.name, func.location.row, tagname)
            print(
                '<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>'.format(
                    name, '', ''),
                file=f)

        print('</table>', file=f)
        print('<h1>Files</h1>', file=f)

        for source_filename, source_code, ast in asts:
            tagname = get_tag(source_filename)
            formatter = HtmlFormatter(lineanchors=tagname, linenos='inline')
            print('<h2>{}</h2>'.format(source_filename), file=f)
            print('<table>', file=f)
            print(
                '<tr><th>Name</th><th>Location</th><th>typ</th></tr>',
                file=f)
            for decl in ast.declarations:
                if isinstance(decl, declarations.VariableDeclaration):
                    tp = 'var'
                elif isinstance(decl, declarations.FunctionDeclaration):
                    tp = 'func'
                else:
                    tp = 'other'

                tp += str(decl.storage_class)

                if source_filename == decl.location.filename:
                    name = '<a href="#{2}-{1}">{0}</a>'.format(decl.name, decl.location.row, tagname)
                else:
                    name = decl.name

                print(
                    '<tr><td>{}</td><td>{}</td><td>{}</td></tr>'.format(
                        name, decl.location, tp),
                    file=f)
            print('</table>', file=f)
            print('''  <div>''', file=f)
            print(highlight(source_code, c_lexer, formatter), file=f)
            print('''  </div>''', file=f)

        print('''</body>
        </html>
        ''', file=f)
コード例 #18
0
import argparse
import io
from ppci.api import get_current_arch
from ppci.lang.c import CLexer, CParser, COptions, CContext, CSemantics
from ppci.lang.c.nodes import types, declarations
from ppci.lang.c.preprocessor import prepare_for_parsing

parser = argparse.ArgumentParser(
    description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('source', type=str)
args = parser.parse_args()
# print('Source:', args.source)

# Parse into ast:
arch = get_current_arch()
coptions = COptions()
ccontext = CContext(coptions, arch.info)
semantics = CSemantics(ccontext)
cparser = CParser(coptions, semantics)
clexer = CLexer(COptions())
f = io.StringIO(args.source)
tokens = clexer.lex(f, '<snippet>')
tokens = prepare_for_parsing(tokens, cparser.keywords)
cparser.init_lexer(tokens)
semantics.begin()
decl = cparser.parse_declarations()[0]


# Explain:
def explain(x):
    if isinstance(x, declarations.VariableDeclaration):
コード例 #19
0
ファイル: compile_coremark.py プロジェクト: vpoulailleau/ppci
{
    main();
}

"""

home = os.environ['HOME']
core_mark_folder = os.path.join(home, 'GIT', 'coremark')
this_dir = os.path.abspath(os.path.dirname(__file__))
port_folder = os.path.join(core_mark_folder, 'linux64')
libc_folder = os.path.join(this_dir, "..", "librt", "libc")
linux64_folder = os.path.join(this_dir, '..', 'examples', 'linux64')

opt_level = 2
march = api.get_arch('x86_64')
coptions = COptions()
coptions.add_include_path(core_mark_folder)
coptions.add_include_path(port_folder)
coptions.add_include_path(libc_folder)
coptions.add_define('COMPILER_VERSION', '"ppci {}"'.format(ppci_version))
coptions.add_define('FLAGS_STR', '"-O{}"'.format(opt_level))

# Prevent malloc / free usage:
coptions.add_define('MEM_METHOD', 'MEM_STATIC')

# TODO: Hack to enable %f formatting:
coptions.add_define('__x86_64__', '1')

objs = []

crt0_asm = os.path.join(linux64_folder, 'glue.asm')
コード例 #20
0
ファイル: compile_nos.py プロジェクト: ttwj/ppci
from ppci.api import cc
from ppci.utils.reporting import html_reporter
from ppci.lang.c import COptions
from ppci.common import CompilerError, logformat

home = os.environ['HOME']
nos_folder = os.path.join(home, 'GIT', 'nOS')
nos_inc_folder = os.path.join(nos_folder, 'inc')
nos_src_folder = os.path.join(nos_folder, 'src')
this_dir = os.path.abspath(os.path.dirname(__file__))
report_filename = os.path.join(this_dir, 'report_nos.html')
libc_path = os.path.join(this_dir, '..', 'librt', 'libc')
libc_includes = os.path.join(libc_path, 'include')
arch = 'msp430'
coptions = COptions()
coptions.enable('freestanding')
include_paths = [
    libc_includes, nos_inc_folder,
    os.path.join(nos_inc_folder, 'port', 'GCC', 'MSP430')
]
coptions.add_include_paths(include_paths)


def do_compile(filename, reporter):
    with open(filename, 'r') as f:
        obj = cc(f, arch, coptions=coptions, reporter=reporter)
    print(filename, 'compiled into', obj)
    return obj

コード例 #21
0
 def setUp(self):
     coptions = COptions()
     coptions.enable('verbose')
     self.preprocessor = CPreProcessor(coptions)
コード例 #22
0
    def do(self, src, expected_output, lang='c3'):
        base_filename = make_filename(self.id())
        list_filename = base_filename + '.html'

        bsp = io.StringIO("""
           module bsp;
           public function void putc(byte c);
           """)
        march = 'arm'  # TODO: this must be wasm!
        with HtmlReportGenerator(open(list_filename, 'w')) as reporter:
            if lang == 'c3':
                ir_modules = [
                    c3_to_ir([
                        bsp,
                        relpath('..', 'librt', 'io.c3'),
                        io.StringIO(src)
                    ], [],
                             march,
                             reporter=reporter)
                ]
            elif lang == 'bf':
                ir_modules = [bf_to_ir(src, march)]
            elif lang == 'c':
                coptions = COptions()
                include_path1 = relpath('..', 'librt', 'libc')
                lib = relpath('..', 'librt', 'libc', 'lib.c')
                coptions.add_include_path(include_path1)
                with open(lib, 'r') as f:
                    mod1 = c_to_ir(f,
                                   march,
                                   coptions=coptions,
                                   reporter=reporter)
                mod2 = c_to_ir(io.StringIO(src),
                               march,
                               coptions=coptions,
                               reporter=reporter)
                ir_modules = [mod1, mod2]
            else:  # pragma: no cover
                raise NotImplementedError(
                    'Language {} not implemented'.format(lang))

            for ir_module in ir_modules:
                optimize(ir_module, level=self.opt_level, reporter=reporter)

            wasm_module = ir_to_wasm(ir_link(ir_modules), reporter=reporter)

        # Output wasm file:
        wasm_filename = base_filename + '.wasm'
        with open(wasm_filename, 'wb') as f:
            wasm_module.to_file(f)

        # Dat was 'm:
        wasm = wasm_module.to_bytes()
        wasm_text = str(list(wasm))
        wasm_data = 'var wasm_data = new Uint8Array(' + wasm_text + ');'

        # Output javascript file:
        js = NODE_JS_TEMPLATE.replace('JS_PLACEHOLDER', wasm_data)
        js_filename = base_filename + '.js'
        with open(js_filename, 'w') as f:
            f.write(js)

        # run node.js and compare output:
        res = run_nodejs(js_filename)
        self.assertEqual(expected_output, res)
コード例 #23
0
def build(base_filename,
          src,
          bsp_c3,
          crt0_asm,
          march,
          opt_level,
          mmap,
          lang='c3',
          bin_format=None,
          elf_format=None,
          code_image='code'):
    """ Construct object file from source snippet """
    list_filename = base_filename + '.html'

    with HtmlReportGenerator(open(list_filename, 'w')) as reporter:
        o1 = asm(crt0_asm, march)
        if lang == 'c3':
            srcs = [relpath('..', 'librt', 'io.c3'), bsp_c3, io.StringIO(src)]
            o2 = c3c(srcs, [],
                     march,
                     opt_level=opt_level,
                     reporter=reporter,
                     debug=True)
            objs = [o1, o2]
        elif lang == 'bf':
            o3 = bfcompile(src, march, reporter=reporter)
            o2 = c3c([bsp_c3], [], march, reporter=reporter)
            objs = [o1, o2, o3]
        elif lang == 'c':
            o2 = c3c([bsp_c3], [], march, reporter=reporter)
            coptions = COptions()
            include_path1 = relpath('..', 'librt', 'libc')
            coptions.add_include_path(include_path1)
            with open(relpath('..', 'librt', 'libc', 'lib.c'), 'r') as f:
                o3 = cc(f, march, coptions=coptions, reporter=reporter)
            o4 = cc(io.StringIO(src),
                    march,
                    coptions=coptions,
                    reporter=reporter)
            objs = [o1, o2, o3, o4]
        else:
            raise NotImplementedError('language not implemented')
        obj = link(objs,
                   layout=mmap,
                   use_runtime=True,
                   reporter=reporter,
                   debug=True)

    # Save object:
    obj_file = base_filename + '.oj'
    with open(obj_file, 'w') as f:
        obj.save(f)

    if elf_format:
        elf_filename = base_filename + '.' + elf_format
        objcopy(obj, code_image, elf_format, elf_filename)

    # Export code image to some format:
    if bin_format:
        sample_filename = base_filename + '.' + bin_format
        objcopy(obj, code_image, bin_format, sample_filename)

    return obj
コード例 #24
0
 def setUp(self):
     arch = ExampleArch()
     self.builder = CBuilder(arch.info, COptions())
コード例 #25
0
ファイル: compile_8cc.py プロジェクト: ttwj/ppci
from ppci import api
from ppci.utils.reporting import html_reporter
from ppci.format.elf import write_elf
from ppci.lang.c import COptions
from ppci.common import CompilerError, logformat

home = os.environ['HOME']
_8cc_folder = os.path.join(home, 'GIT', '8cc')
this_dir = os.path.abspath(os.path.dirname(__file__))
report_filename = os.path.join(this_dir, 'report_8cc.html')
libc_folder = os.path.join(this_dir, '..', 'librt', 'libc')
libc_includes = os.path.join(libc_folder, 'include')
linux_include_dir = '/usr/include'
arch = 'x86_64'
coptions = COptions()
include_paths = [
    libc_includes,
    _8cc_folder,
    linux_include_dir,
]
coptions.add_include_paths(include_paths)
coptions.add_define('BUILD_DIR', '"{}"'.format(_8cc_folder))


def do_compile(filename, reporter):
    with open(filename, 'r') as f:
        obj = api.cc(f, arch, coptions=coptions, reporter=reporter)
    print(filename, 'compiled into', obj)
    return obj
コード例 #26
0
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', '-v', action='count', default=0)
args = parser.parse_args()

if args.verbose:
    loglevel = logging.DEBUG
else:
    loglevel = logging.INFO

logging.basicConfig(level=loglevel)

this_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.join(this_dir, '..')
wasm_filename = os.path.join(this_dir, 'samples_in_wasm.wasm')
arch = get_arch('arm')
coptions = COptions()
libc_dir = os.path.join(this_dir, '..', 'librt', 'libc')
libc_include_path = os.path.join(libc_dir, 'include')
coptions.add_include_path(libc_include_path)

libc_filename = os.path.join(
    this_dir, '..', 'librt', 'libc', 'lib.c')
libio_filename = os.path.join(
    this_dir, '..', 'librt', 'io.c3')


def c_to_wasm(filename, verbose=False):
    # Compile c source:
    with open(libc_filename, 'r') as f:
        ir_libc = c_to_ir(f, arch, coptions=coptions)
コード例 #27
0
ファイル: compile_8cc.py プロジェクト: pmp-p/ppci-mirror
except ImportError:
    from traceback import print_exc

from ppci.api import cc
from ppci.utils.reporting import HtmlReportGenerator
from ppci.lang.c import COptions
from ppci.common import CompilerError, logformat

home = os.environ['HOME']
_8cc_folder = os.path.join(home, 'GIT', '8cc')
this_dir = os.path.abspath(os.path.dirname(__file__))
report_filename = os.path.join(this_dir, 'report_8cc.html')
libc_includes = os.path.join(this_dir, '..', 'librt', 'libc')
linux_include_dir = '/usr/include'
arch = 'x86_64'
coptions = COptions()
include_paths = [
    libc_includes,
    _8cc_folder,
    linux_include_dir,
    ]
coptions.add_include_paths(include_paths)


def do_compile(filename, reporter):
    with open(filename, 'r') as f:
        obj = cc(f, arch, coptions=coptions, reporter=reporter)
    print(filename, 'compiled into', obj)
    return obj