about summary refs log tree commit diff
path: root/libAflDyninst.cpp
blob: 3374010e874514f0fbe8803aa8fcbedf1b6afee9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include "config.h"
#include <sys/types.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

static u8 *trace_bits;
static s32 shm_id;
static int __afl_temp_data;
static pid_t __afl_fork_pid;
static unsigned short prev_id;
static long saved_di;
register long rdi asm("di");    // the warning is fine - we need the warning because of a bug in dyninst

#define PRINT_ERROR(string) write(2, string, strlen(string))

void initAflForkServer() {
  // we can not use fprint* stdout/stderr functions here, it fucks up some programs
  char *shm_env_var = getenv(SHM_ENV_VAR);

  if (!shm_env_var) {
    PRINT_ERROR("Error getting shm\n");
    return;
  }
  shm_id = atoi(shm_env_var);
  trace_bits = (u8 *) shmat(shm_id, NULL, 0);
  if (trace_bits == (u8 *) - 1) {
    PRINT_ERROR("Error: shmat\n");
    return;
  }
  // enter fork() server thyme!
  int n = write(FORKSRV_FD + 1, &__afl_temp_data, 4);

  if (n != 4) {
    PRINT_ERROR("Error writting fork server\n");
    return;
  }
  while (1) {
    n = read(FORKSRV_FD, &__afl_temp_data, 4);
    if (n != 4) {
      PRINT_ERROR("Error reading fork server\n");
      return;
    }

    __afl_fork_pid = fork();
    if (__afl_fork_pid < 0) {
      PRINT_ERROR("Error on fork()\n");
      return;
    }
    if (__afl_fork_pid == 0) {
      close(FORKSRV_FD);
      close(FORKSRV_FD + 1);
      break;
    } else {
      // parrent stuff
      n = write(FORKSRV_FD + 1, &__afl_fork_pid, 4);
      pid_t temp_pid = waitpid(__afl_fork_pid, &__afl_temp_data, 2);

      if (temp_pid == 0) {
        return;
      }
      n = write(FORKSRV_FD + 1, &__afl_temp_data, 4);
    }
  }
}

// Should be called on basic block entry
void bbCallback(unsigned short id) {
  if (trace_bits) {
    trace_bits[prev_id ^ id]++;
    prev_id = id >> 1;
  }
}

void save_rdi() {
  saved_di = rdi;
}

void restore_rdi() {
  rdi = saved_di;
}