Fun function of the week:

void disassemble(address start, address end)
{
  const char *fmt = "/tmp/aztec-%d.%c";
  char c_file[BUFSIZ], o_file[BUFSIZ];
  sprintf(c_file, fmt, getpid(), 'c');
  sprintf(o_file, fmt, getpid(), 'o');

  FILE *fp = fopen(c_file, "w");
  if (fp == NULL)
    fatal("%s:%d: can't write file", __FILE__, __LINE__);

  fputs("unsigned char start[] = {", fp);
  for (address a = start; a < end; a++) {
    if (a != start)
      fputc(',', fp);
    fprintf(fp, "0x%02x", *a);
  }
  fputs("};\n", fp);
  fclose(fp);

  char cmd[BUFSIZ];
  sprintf(cmd, "gcc -c %s -o %s", c_file, o_file);
  if (system(cmd) != 0)
    fatal("%s:%d: can't compile file", __FILE__, __LINE__);

  putchar('\n');
  sprintf(cmd, "objdump -D -j .data %s | grep '^....:'", o_file);
  if (system(cmd) != 0)
    fatal("%s:%d: can't disassemble file", __FILE__, __LINE__);
  putchar('\n');

  unlink(c_file);
  unlink(o_file);
}

4 thoughts on “

  1.   for (address a = start; a < end; a++)
        fprintf(fp, "0x%02x,", *a);

    should work; trailing commas are okay.  And the whole thing can possibly be replaced by something like

      int fd = open(o_file, O_WRONLY);
      write(fd, start, end - start);
      close(fd);
      sprintf(cmd, "objdump -D -b binary -m i386 %s", o_file);
      system(cmd);
      unlink(c_file);

    (not sure -- untested, but I think it's about right).  Still a cute hack nevertheless.

  2. You might want to take a look at /usr/include/dis-asm.h provided by GNU binutils libopcodes (yum install binutils-devel). Nice simple disassembler under the GPL.

  3. That looks really nice… but it also looks like it might take a week to figure out what I’m supposed to do with it. I looked in objdump quickly, but there’s a lot more going on there than I really need.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.