1/*
2 * Copyright (c) 2007 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Gabe Black
29 */
30
31#include <sys/ptrace.h>
32#include <stdint.h>
33
34#include <cerrno>
35#include <cstring>
36#include <iomanip>
37#include <iostream>
38
39#include "arch/amd64/tracechild.hh"
40
41using namespace std;
42
43bool
44AMD64TraceChild::sendState(int socket)
45{
46    uint64_t regVal64 = 0;
47    uint32_t regVal32 = 0;
48    for (int x = 0; x <= R15; x++) {
49        regVal64 = getRegVal(x);
50        if (write(socket, &regVal64, sizeof(regVal64)) == -1) {
51            cerr << "Write failed! " << strerror(errno) << endl;
52            tracing = false;
53            return false;
54        }
55    }
56    regVal64 = getRegVal(RIP);
57    if (write(socket, &regVal64, sizeof(regVal64)) == -1) {
58        cerr << "Write failed! " << strerror(errno) << endl;
59        tracing = false;
60        return false;
61    }
62    for (int x = MMX0_0; x <= MMX7_1; x++) {
63        regVal32 = getRegVal(x);
64        if (write(socket, &regVal32, sizeof(regVal32)) == -1) {
65            cerr << "Write failed! " << strerror(errno) << endl;
66            tracing = false;
67            return false;
68        }
69    }
70    for (int x = XMM0_0; x <= XMM15_3; x++) {
71        regVal32 = getRegVal(x);
72        if (write(socket, &regVal32, sizeof(regVal32)) == -1) {
73            cerr << "Write failed! " << strerror(errno) << endl;
74            tracing = false;
75            return false;
76        }
77    }
78    return true;
79}
80
81int64_t
82AMD64TraceChild::getRegs(user_regs_struct & myregs,
83        user_fpregs_struct & myfpregs, int num)
84{
85    assert(num < numregs && num >= 0);
86    switch (num) {
87      //GPRs
88      case RAX: return myregs.rax;
89      case RBX: return myregs.rbx;
90      case RCX: return myregs.rcx;
91      case RDX: return myregs.rdx;
92      //Index registers
93      case RSI: return myregs.rsi;
94      case RDI: return myregs.rdi;
95      //Base pointer and stack pointer
96      case RBP: return myregs.rbp;
97      case RSP: return myregs.rsp;
98      //New 64 bit mode registers
99      case R8: return myregs.r8;
100      case R9: return myregs.r9;
101      case R10: return myregs.r10;
102      case R11: return myregs.r11;
103      case R12: return myregs.r12;
104      case R13: return myregs.r13;
105      case R14: return myregs.r14;
106      case R15: return myregs.r15;
107      //Segmentation registers
108      case CS: return myregs.cs;
109      case DS: return myregs.ds;
110      case ES: return myregs.es;
111      case FS: return myregs.fs;
112      case GS: return myregs.gs;
113      case SS: return myregs.ss;
114      case FS_BASE: return myregs.fs_base;
115      case GS_BASE: return myregs.gs_base;
116      //PC
117      case RIP: return myregs.rip;
118      //Flags
119      case EFLAGS: return myregs.eflags;
120      //MMX
121      case MMX0_0: return myfpregs.st_space[0];
122      case MMX0_1: return myfpregs.st_space[1];
123      case MMX1_0: return myfpregs.st_space[2];
124      case MMX1_1: return myfpregs.st_space[3];
125      case MMX2_0: return myfpregs.st_space[4];
126      case MMX2_1: return myfpregs.st_space[5];
127      case MMX3_0: return myfpregs.st_space[6];
128      case MMX3_1: return myfpregs.st_space[7];
129      case MMX4_0: return myfpregs.st_space[8];
130      case MMX4_1: return myfpregs.st_space[9];
131      case MMX5_0: return myfpregs.st_space[10];
132      case MMX5_1: return myfpregs.st_space[11];
133      case MMX6_0: return myfpregs.st_space[12];
134      case MMX6_1: return myfpregs.st_space[13];
135      case MMX7_0: return myfpregs.st_space[14];
136      case MMX7_1: return myfpregs.st_space[15];
137      //XMM
138      case XMM0_0: return myfpregs.xmm_space[0];
139      case XMM0_1: return myfpregs.xmm_space[1];
140      case XMM0_2: return myfpregs.xmm_space[2];
141      case XMM0_3: return myfpregs.xmm_space[3];
142      case XMM1_0: return myfpregs.xmm_space[4];
143      case XMM1_1: return myfpregs.xmm_space[5];
144      case XMM1_2: return myfpregs.xmm_space[6];
145      case XMM1_3: return myfpregs.xmm_space[7];
146      case XMM2_0: return myfpregs.xmm_space[8];
147      case XMM2_1: return myfpregs.xmm_space[9];
148      case XMM2_2: return myfpregs.xmm_space[10];
149      case XMM2_3: return myfpregs.xmm_space[11];
150      case XMM3_0: return myfpregs.xmm_space[12];
151      case XMM3_1: return myfpregs.xmm_space[13];
152      case XMM3_2: return myfpregs.xmm_space[14];
153      case XMM3_3: return myfpregs.xmm_space[15];
154      case XMM4_0: return myfpregs.xmm_space[16];
155      case XMM4_1: return myfpregs.xmm_space[17];
156      case XMM4_2: return myfpregs.xmm_space[18];
157      case XMM4_3: return myfpregs.xmm_space[19];
158      case XMM5_0: return myfpregs.xmm_space[20];
159      case XMM5_1: return myfpregs.xmm_space[21];
160      case XMM5_2: return myfpregs.xmm_space[22];
161      case XMM5_3: return myfpregs.xmm_space[23];
162      case XMM6_0: return myfpregs.xmm_space[24];
163      case XMM6_1: return myfpregs.xmm_space[25];
164      case XMM6_2: return myfpregs.xmm_space[26];
165      case XMM6_3: return myfpregs.xmm_space[27];
166      case XMM7_0: return myfpregs.xmm_space[28];
167      case XMM7_1: return myfpregs.xmm_space[29];
168      case XMM7_2: return myfpregs.xmm_space[30];
169      case XMM7_3: return myfpregs.xmm_space[31];
170      case XMM8_0: return myfpregs.xmm_space[32];
171      case XMM8_1: return myfpregs.xmm_space[33];
172      case XMM8_2: return myfpregs.xmm_space[34];
173      case XMM8_3: return myfpregs.xmm_space[35];
174      case XMM9_0: return myfpregs.xmm_space[36];
175      case XMM9_1: return myfpregs.xmm_space[37];
176      case XMM9_2: return myfpregs.xmm_space[38];
177      case XMM9_3: return myfpregs.xmm_space[39];
178      case XMM10_0: return myfpregs.xmm_space[40];
179      case XMM10_1: return myfpregs.xmm_space[41];
180      case XMM10_2: return myfpregs.xmm_space[42];
181      case XMM10_3: return myfpregs.xmm_space[43];
182      case XMM11_0: return myfpregs.xmm_space[44];
183      case XMM11_1: return myfpregs.xmm_space[45];
184      case XMM11_2: return myfpregs.xmm_space[46];
185      case XMM11_3: return myfpregs.xmm_space[47];
186      case XMM12_0: return myfpregs.xmm_space[48];
187      case XMM12_1: return myfpregs.xmm_space[49];
188      case XMM12_2: return myfpregs.xmm_space[50];
189      case XMM12_3: return myfpregs.xmm_space[51];
190      case XMM13_0: return myfpregs.xmm_space[52];
191      case XMM13_1: return myfpregs.xmm_space[53];
192      case XMM13_2: return myfpregs.xmm_space[54];
193      case XMM13_3: return myfpregs.xmm_space[55];
194      case XMM14_0: return myfpregs.xmm_space[56];
195      case XMM14_1: return myfpregs.xmm_space[57];
196      case XMM14_2: return myfpregs.xmm_space[58];
197      case XMM14_3: return myfpregs.xmm_space[59];
198      case XMM15_0: return myfpregs.xmm_space[60];
199      case XMM15_1: return myfpregs.xmm_space[61];
200      case XMM15_2: return myfpregs.xmm_space[62];
201      case XMM15_3: return myfpregs.xmm_space[63];
202      default:
203        assert(0);
204        return 0;
205    }
206}
207
208bool
209AMD64TraceChild::update(int pid)
210{
211    oldregs = regs;
212    oldfpregs = fpregs;
213    if (ptrace(PTRACE_GETREGS, pid, 0, &regs) != 0) {
214        cerr << "update: " << strerror(errno) << endl;
215        return false;
216    }
217    if (ptrace(PTRACE_GETFPREGS, pid, 0, &fpregs) != 0) {
218        cerr << "update: " << strerror(errno) << endl;
219        return false;
220    }
221    for (unsigned int x = 0; x < numregs; x++)
222        regDiffSinceUpdate[x] = (getRegVal(x) != getOldRegVal(x));
223    return true;
224}
225
226AMD64TraceChild::AMD64TraceChild()
227{
228    for (unsigned int x = 0; x < numregs; x++)
229        regDiffSinceUpdate[x] = false;
230}
231
232int64_t
233AMD64TraceChild::getRegVal(int num)
234{
235    return getRegs(regs, fpregs, num);
236}
237
238int64_t
239AMD64TraceChild::getOldRegVal(int num)
240{
241    return getRegs(oldregs, oldfpregs, num);
242}
243
244ostream &
245AMD64TraceChild::outputStartState(ostream & os)
246{
247    uint64_t sp = getSP();
248    uint64_t pc = getPC();
249    uint64_t highestInfo = 0;
250    char obuf[1024];
251    sprintf(obuf, "Initial stack pointer = 0x%016lx\n", sp);
252    os << obuf;
253    sprintf(obuf, "Initial program counter = 0x%016lx\n", pc);
254    os << obuf;
255
256    //Output the argument count
257    uint64_t cargc = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
258    sprintf(obuf, "0x%016lx: Argc = 0x%016lx\n", sp, cargc);
259    os << obuf;
260    sp += 8;
261
262    //Output argv pointers
263    int argCount = 0;
264    uint64_t cargv;
265    do {
266        cargv = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
267        sprintf(obuf, "0x%016lx: argv[%d] = 0x%016lx\n",
268                sp, argCount++, cargv);
269        if (cargv)
270            if (highestInfo < cargv)
271                highestInfo = cargv;
272        os << obuf;
273        sp += 8;
274    } while (cargv);
275
276    //Output the envp pointers
277    int envCount = 0;
278    uint64_t cenvp;
279    do {
280        cenvp = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
281        sprintf(obuf, "0x%016lx: envp[%d] = 0x%016lx\n",
282                sp, envCount++, cenvp);
283        os << obuf;
284        sp += 8;
285    } while (cenvp);
286    uint64_t auxType, auxVal;
287    do {
288        auxType = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
289        sp += 8;
290        auxVal = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
291        sp += 8;
292        sprintf(obuf, "0x%016lx: Auxiliary vector = {0x%016lx, 0x%016lx}\n",
293                sp - 16, auxType, auxVal);
294        os << obuf;
295    } while (auxType != 0 || auxVal != 0);
296    //Print out the argument strings, environment strings, and file name.
297    string current;
298    uint64_t buf;
299    uint64_t currentStart = sp;
300    bool clearedInitialPadding = false;
301    do {
302        buf = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
303        char * cbuf = (char *)&buf;
304        for (int x = 0; x < sizeof(uint64_t); x++) {
305            if (cbuf[x])
306                current += cbuf[x];
307            else {
308                sprintf(obuf, "0x%016lx: \"%s\"\n",
309                        currentStart, current.c_str());
310                os << obuf;
311                current = "";
312                currentStart = sp + x + 1;
313            }
314        }
315        sp += 8;
316        clearedInitialPadding = clearedInitialPadding || buf != 0;
317    } while (!clearedInitialPadding || buf != 0 || sp <= highestInfo);
318    return os;
319}
320
321uint64_t
322AMD64TraceChild::findSyscall()
323{
324    uint64_t rip = getPC();
325    bool foundOpcode = false;
326    bool twoByteOpcode = false;
327    for (;;) {
328        uint64_t buf = ptrace(PTRACE_PEEKDATA, pid, rip, 0);
329        for (int i = 0; i < sizeof(uint64_t); i++) {
330            unsigned char byte = buf & 0xFF;
331            if (!foundOpcode) {
332                if (!(byte == 0x66 || //operand override
333                     byte == 0x67 || //address override
334                     byte == 0x2E || //cs
335                     byte == 0x3E || //ds
336                     byte == 0x26 || //es
337                     byte == 0x64 || //fs
338                     byte == 0x65 || //gs
339                     byte == 0x36 || //ss
340                     byte == 0xF0 || //lock
341                     byte == 0xF2 || //repe
342                     byte == 0xF3 || //repne
343                     (byte >= 0x40 && byte <= 0x4F) // REX
344                    )) {
345                    foundOpcode = true;
346                }
347            }
348            if (foundOpcode) {
349                if (twoByteOpcode) {
350                    //SYSCALL or SYSENTER
351                    if (byte == 0x05 || byte == 0x34)
352                        return rip + 1;
353                    else
354                        return 0;
355                }
356                if (!twoByteOpcode) {
357                    if (byte == 0xCC) // INT3
358                        return rip + 1;
359                    else if (byte == 0xCD) // INT with byte immediate
360                        return rip + 2;
361                    else if (byte == 0x0F) // two byte opcode prefix
362                        twoByteOpcode = true;
363                    else
364                        return 0;
365                }
366            }
367            buf >>= 8;
368            rip++;
369        }
370    }
371}
372
373bool
374AMD64TraceChild::step()
375{
376    uint64_t ripAfterSyscall = findSyscall();
377    if (ripAfterSyscall) {
378        //Get the original contents of memory
379        uint64_t buf = ptrace(PTRACE_PEEKDATA, pid, ripAfterSyscall, 0);
380        //Patch the first two bytes of the memory immediately after this with
381        //jmp -2. Either single stepping will take over before this
382        //instruction, leaving the rip where it should be, or it will take
383        //over after this instruction, -still- leaving the rip where it should
384        //be.
385        uint64_t newBuf = (buf & ~0xFFFF) | 0xFEEB;
386        //Write the patched memory to the processes address space
387        ptrace(PTRACE_POKEDATA, pid, ripAfterSyscall, newBuf);
388        //Step and hit it
389        ptraceSingleStep();
390        //Put things back to the way they started
391        ptrace(PTRACE_POKEDATA, pid, ripAfterSyscall, buf);
392    } else {
393        //Get all the way past repe and repne string instructions in one shot.
394        uint64_t newPC, origPC = getPC();
395        do {
396            ptraceSingleStep();
397            newPC = getPC();
398        } while (newPC == origPC);
399    }
400}
401
402TraceChild * genTraceChild()
403{
404    return new AMD64TraceChild;
405}
406