03 November 2010

Quick and dirty ndisasm-clone disassembler

The project libdisasm is amazing! a bytecode to opcode translator

A quick introduction:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#include "libdis.h"

#define LINE_SIZE 4096

int main(int argc, char * argv[])
{
    char * buf;      /* buffer of bytes to disassemble */
    char * reentries;
    int descriptor = open(argv[1], O_RDONLY);
    if ( -1 == descriptor )
    {
        printf("Unable to open file\n");
        return EXIT_FAILURE;
    }
    size_t fsize = lseek(descriptor, 0, SEEK_END);
    lseek(descriptor, 0, SEEK_SET);
    buf = (char *)malloc(fsize);
    read(descriptor, buf, fsize);
    close(descriptor);    
    char line[LINE_SIZE];    /* buffer of line to print */
    int pos = 0;             /* current position in buffer */
    int apos = 0;
    int size;                /* size of instruction */
    x86_insn_t insn;         /* instruction */

    x86_init(opt_none, NULL, NULL);

    while ( pos < fsize )
    {
        /* disassemble address */
        size = x86_disasm(buf, fsize, 0, pos, &insn);
        printf("%.8X  ", pos);
        if ( size )
        {
            /* print instruction */
            x86_format_insn(&insn, line, LINE_SIZE, intel_syntax);
            int i;
            pos += size;
            for (i=apos; i < pos;i++ )
            {
                printf("%.2X", (unsigned char)buf[i]);
            }
            for ( i=size*2;i<24;i++)
            {
                printf(" ");
            }
            printf("%s\n", line);
        }
        else
        {
            printf("%.2X", (unsigned char)buf[pos]);
            int i;
            for ( i=2;i<24;i++)
            {
                printf(" ");
            }
            printf("db 0x%.2x\n", buf[pos]);
            //printf("Invalid instruction\n");
            pos++;
        }
        apos=pos;
    }

    x86_cleanup();

    return EXIT_SUCCESS;
}

Posted at BinaryCell

No comments:

Post a Comment


Disclaimer: In no event shall the blog owner, be liable for any damages, including without limitation, special, indirect or consequential damages, or any damages, whatsoever resulting from access or use, or inability to access or use this Website or arising out of any materials, information, qualifications or recommendations on this Website.