Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- include "string", "io", "re", "os", "fmt";
- IN = argv[1];
- OUT = "asmpp." $ IN;
- TMP_ASM = "__tmp.asm";
- TMP_ASM_OUT = "__tmp.o";
- RTYPES =
- {
- "i32" = [ 0x94939291, 4, "int32_t" ]
- };
- data = io_file_read( IN );
- ranges = re_match_all( data, "#<\\$.*?\\$>#s", RE_RETURN_BOTH );
- ranges.reverse();
- function str2cbin( str )
- {
- if( typeid(str) != VT_STRING )
- ERROR( "str2cbin: not a string" );
- out = [];
- len = str.length;
- for( i = 0; i < len; ++i )
- {
- cc = string_charcode( str, i );
- if( cc > 127 ) cc -= 256;
- out.push( cc );
- }
- return string_implode( out, "," );
- }
- foreach( i, range : ranges )
- {
- asm = string_cut( range[0][0], 2, -3 );
- //
- // prepare post-replacements
- //
- replist = [];
- reps = re_match_all( asm, "#:([a-zA-Z0-9]+)\\((.*?)\\)#s", RE_RETURN_BOTH );
- reps.reverse();
- foreach( rep : reps )
- {
- type = rep[1][0];
- src = rep[2][0];
- if( isset( RTYPES, type ) ){ val = RTYPES[type][0]; }
- else
- ERROR( "replacement type " $ type $ " was not recognized" );
- asm = string_part( asm, 0, rep[0][1] ) $ val $ string_part( asm, rep[0][2] );
- // 0: type, 1: source in C, 2: test value, 3: test value as bytes
- replist.unshift([ type, src, val, fmt_pack("l",val) ]);
- }
- //
- // assemble
- //
- io_file_write( TMP_ASM, asm );
- os_command( "as -o " $ TMP_ASM_OUT $ " -mnaked-reg -msyntax=intel -mmnemonic=intel " $ TMP_ASM );
- gen = io_file_read( TMP_ASM_OUT );
- gen_asm = string_part( gen, string_find( gen, ".bss" ) + 40 );
- gen_asm = string_part( gen_asm, 0, string_find( gen_asm, ".file" ) );
- // strip NOPs
- gen_asm = string_trim( gen_asm, "\x90" );
- gckey = "__asm" $ i;
- bcrw = "";
- foreach( rep : replist )
- {
- xdata = RTYPES[ rep[0] ];
- numbytes = xdata[1];
- pos = string_find_rev( gen_asm, rep[3] );
- gen_asm = string_part( gen_asm, 0, pos ) $ string_repeat( "\x00", numbytes ) $ string_part( gen_asm, pos + numbytes );
- bcrw $= fmt_text( " *({c}*)({c}+{c}) = {c}; ", xdata[2], gckey, pos, rep[1] );
- }
- printvar( gen_asm );
- gen_code = "{char " $ gckey $ "[] = {" $ str2cbin( gen_asm )
- $ "};" $ bcrw $ "APPEND_CODE(" $ gckey $ "," $ gen_asm.length $ ");}";
- data = string_part( data, 0, range[0][1] ) $ gen_code $ string_part( data, range[0][2] );
- }
- io_file_write( OUT, data );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement