Ejemplo n.º 1
0
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)

    print(ir_libc, ir_libc.stats())
    optimize(ir_libc, level='2')

    with open(filename, 'r') as f:
        x = c_to_ir(f, arch, coptions=coptions)

    print(x, x.stats())
    optimize(x, level='2')
    print(x, x.stats())

    if verbose:
        x.display()

    wasm_module = ir_to_wasm(ir_link([ir_libc, x]))

    print('Completed generating wasm module', wasm_module)
    if verbose:
        wasm_module.show()
        print(wasm_module.to_bytes())
    # with open(wasm_filename, 'wb') as f:
    #    wasm_module.to_file(f)
    return wasm_module
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
    def test_single_sample(self):
        src = io.StringIO("""
        int add(int a, int b) {
          int g = a+b+55+1-2;
          return g + a+8*b;
        }
        """)
        mod = api.c_to_ir(src, 'x86_64')
        # For now optimize to the allocation of a variable on heap:
        api.optimize(mod, level='2')
        wasm_module = ir_to_wasm(mod)

        # W00t! Convert back to ir again! (because it is possible)
        mod2 = wasm_to_ir(
            wasm_module, api.get_arch('x86_64').info.get_type_info('ptr'))
        # TODO: find a way to execute this wasm code.
        ir_to_wasm(mod2)
Ejemplo n.º 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_c3 = io.StringIO("""
           module bsp;
           public function void putc(byte c);
           """)
        march = "arm"
        with html_reporter(list_filename) as reporter:
            ir_modules = build_sample_to_ir(src, lang, bsp_c3, march, reporter)

            # Test roundtrip of ir_modules
            for ir_module in ir_modules:
                verify_module(ir_module)
                serialization_roundtrip(ir_module)
                api.optimize(ir_module,
                             level=self.opt_level,
                             reporter=reporter)

            with open(sample_filename, "w") as f:
                api.ir_to_python(ir_modules, f, reporter=reporter)

                # Expose all functions as external symbols:
                for ir_module in ir_modules:
                    for routine in ir_module.functions:
                        print('_irpy_externals["{0}"] = {0}'.format(
                            routine.name),
                              file=f)

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

        res = run_python(sample_filename)
        self.assertEqual(expected_output, res)
Ejemplo n.º 5
0
    def compile(self, source):
        """ Compile the given source with current settings. """
        srcfile = io.StringIO(source)
        outfile = io.StringIO()
        if self.stage == "ast":
            src_ast = create_ast(srcfile, api.get_arch(self.arch).info)
            print_ast(src_ast, file=outfile)
        else:
            ir_module = api.c_to_ir(srcfile, self.arch)

            if self.optimize:
                api.optimize(ir_module, level=2)

            if self.stage == "ir":
                print_module(ir_module, file=outfile)
            else:
                text_stream = TextOutputStream(f=outfile, add_binary=True)
                api.ir_to_stream(ir_module, self.arch, text_stream)
        return outfile.getvalue()
Ejemplo n.º 6
0
    def do(self, src, expected_output, lang="c3"):
        base_filename = make_filename(self.id())
        list_filename = base_filename + ".html"

        bsp_c3 = io.StringIO("""
           module bsp;
           public function void putc(byte c);
           """)
        march = "arm"  # TODO: this must be wasm!
        with html_reporter(list_filename) as reporter:
            ir_modules = build_sample_to_ir(src, lang, bsp_c3, march, reporter)

            for ir_module in ir_modules:
                api.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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
from ppci.api import ir_to_python, c_to_ir, get_arch, COptions, optimize

arch = get_arch('example')
bsp = io.StringIO("""
module bsp;
public function void sleep(int ms);
public function void putc(byte c);
public function bool get_key(int* key);
""")

coptions = COptions()
coptions.add_include_path('../../librt/libc/include')

sources = ['../src/structs/structs.c', '../../librt/libc/lib.c']
ir_modules = []
for source in sources:
    with open(source, 'r') as f:
        ir_module = c_to_ir(f, arch, coptions=coptions)
        optimize(ir_module, level=2)
        ir_modules.append(ir_module)

with open('generated_python_structs.py', 'w') as f:
    print('import time', file=f)
    print('import sys', file=f)
    print('import threading', file=f)
    ir_to_python(ir_modules, f)
    # Invoke main:
    print('def bsp_putc(c):', file=f)
    print('    print(chr(c), end="")', file=f)
    print('main_main()', file=f)