Published in: Assembler
// Author: Orlando Llanes // // This code is hereby donated to the public domain // // asm.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <ctype.h> #include <math.h> #include <stdio.h> #include <string.h> typedef struct { int Source; int Target; int ActualSize; int Size; } TBranchOp; int main(int argc, char* argv[]) { char Src[] = "j4 :2 n n j5 :3 n j2 :4 j3 :5 r"; int SrcPos = 0; unsigned __int8 Code[1024]; int CodeOfs = 0; int Target[10]; TBranchOp Branch[1024]; int nBranch = 0; int Tmp; int i; int j; int k; int l; int SizeDiff; char Ch; FILE* Out; memset( Code, 0, sizeof Code ); memset( Target, 0xFF, sizeof Target ); memset( Branch, 0, sizeof Branch ); while( Src[SrcPos] ) { do { Ch = Src[SrcPos++]; } while( isspace(Ch) ); switch( Ch ) { case 'j': Ch = Src[SrcPos++]; printf( " jmp %c\n", Ch ); Branch[nBranch].Source = CodeOfs; Branch[nBranch].Target = Ch; Branch[nBranch].ActualSize = 2; Branch[nBranch].Size = 2; nBranch++; Code[CodeOfs++] = 0xEB; Code[CodeOfs++] = 0; break; case ':': Ch = Src[SrcPos++]; printf( "%c:\n", Ch ); if( Target[Ch - '0'] != -1 ) { printf( "Error: Label %c has already been declared\n", Ch ); return 0; } Target[Ch - '0'] = CodeOfs; break; case 'n': printf( " nop\n" ); Code[CodeOfs++] = 0x90; break; case 'r': printf( " ret\n" ); Code[CodeOfs++] = 0xC3; break; } } // Grow jump targets in place do { SizeDiff = 0; for( i = 0; i < nBranch; i++ ) { j = Branch[i].Source; k = Branch[i].Target; l = Target[k - '0']; if( l == -1 ) { printf( "Error: Label '%c' undeclared.\n", k ); return 0; } Tmp = l - j - Branch[i].Size; if( (abs(Tmp) > 128) && (Branch[i].Size <= 2) ) { for( k = 0; k < 10; k++ ) { if( Target[k] > Branch[i].Source ) { if( Target[k] ) Target[k]++; } } for( k = 0; k < nBranch; k++ ) { if( Branch[k].Source > Branch[i].Source ) Branch[k].Source++; } memmove( &Code[j + 3], &Code[j + 2], CodeOfs - j - 1 ); CodeOfs++; Code[j] = 0xE9; SizeDiff++; Branch[i].Size++; } } } while( SizeDiff ); // Fill in jump targets for( i = 0; i < nBranch; i++ ) { j = Branch[i].Source; k = Branch[i].Target; l = Target[k - '0']; Tmp = l - j - Branch[i].Size; Code[j + 1] = Tmp; if( Branch[i].Size >= 3 ) Code[j + 2] = Tmp >> 8; } Out = fopen("a.com", "w+b"); if( Out ) { fwrite( Code, 1, CodeOfs, Out ); fclose( Out ); } for( i = 0; i < CodeOfs; i++ ) printf( "0x%.2X\n", Code[i] ); return 0; }
You need to login to post a comment.
