Extracting native code from C

Anthony Hannan ajh18 at cornell.edu
Wed Mar 13 16:19:41 UTC 2002


Below is a small C program that copies some of its machine code to
dynamic memory and executes it.  It works on my Linux-i86.  I was
thinking we could use this technique to dynamically translate bytecodes
into native code, without using machine-dependent assembly language.  I
would like to find out if this C example works on other platforms.  I
would appreciate people testing it.  Note, it does use a GNU C
extension, namely goto expressions.  But we use goto expressions already
in gnuify.  Is GNU used/available for most other platforms.  Ie. can we
base our portability on GNU-C instead of just ANSI-C?

Thanks,
Anthony


/* Test to see if compiled C code can be copied to dynamic memory and
executed from there */

#include <stdio.h>

int testResult; /* will equal 1 if this test succeeds */
int *newCode;  /* pointer to copied code in dynamic memory */
void test();

int main() 
{
  testResult = 0;
  test();
  if (testResult = 1)
    printf("It works!\n");
  else
    printf("Doesn't work.\n");
  return 0;
}

void test()
/* Copies part of its code to newCode then executes/gotos it */
{ int *j;
  int *i;

  /* Allocate memory for newCode */
  newCode = (int*)malloc(1000);

  /* Copy code from l1 to l2 (below) into newCode */
  j = newCode;
  for (i = (int*)&&l1; i < (int*)&&l2; i++) {
    *j = *i;
    j++;
  }

  /* Execute newCode */
  goto *(void*)newCode;

  /* newCode will return here after executing */
  l3: return;

  /* The following code gets copied into newCode */
  l1: testResult = 1;
  goto *(&&l3);

  /* marks end of copied code and should never be executed */
  l2: testResult = 2;
}



More information about the Squeak-dev mailing list