Beispiel #1
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
Beispiel #2
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
    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)
Beispiel #4
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)
Beispiel #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()
    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)
Beispiel #7
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)
Beispiel #8
0
  while (a > 2) {
    print_ln(a);
    if (a -b < 9)
    {
     a--;
    }
    else
    {
     a -= 2;
    }
  }
  return add(a, b) - 133;
}

""")
x = c_to_ir(f, arch, coptions=coptions)
print(x, x.stats())
# optimize(x, level='2')
print(x, x.stats())

x.display()

wasm_module = ir_to_wasm(x)

print(wasm_module)
wasm_module.show()
print(wasm_module.to_bytes())

html_filename = os.path.join(this_dir, 'wasm_demo.html')
src = 'source'
main_js = """