tracechild.cc revision 4795
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 <iostream>
32#include <iomanip>
33#include <errno.h>
34#include <sys/ptrace.h>
35#include <stdint.h>
36
37#include "tracechild_amd64.hh"
38
39using namespace std;
40
41char * AMD64TraceChild::regNames[numregs] = {
42                //GPRs
43                "rax", "rbx", "rcx", "rdx",
44                //Index registers
45                "rsi", "rdi",
46                //Base pointer and stack pointer
47                "rbp", "rsp",
48                //New 64 bit mode registers
49                "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
50                //Segmentation registers
51                "cs", "ds", "es", "fs", "gs", "ss", "fs_base", "gs_base",
52                //PC
53                "rip",
54                //Flags
55                "eflags"};
56
57bool AMD64TraceChild::sendState(int socket)
58{
59    uint64_t regVal = 0;
60    for(int x = 0; x <= R15; x++)
61    {
62        regVal = getRegVal(x);
63        if(write(socket, &regVal, sizeof(regVal)) == -1)
64        {
65            cerr << "Write failed! " << strerror(errno) << endl;
66            tracing = false;
67            return false;
68        }
69    }
70    regVal = getRegVal(RIP);
71    if(write(socket, &regVal, sizeof(regVal)) == -1)
72    {
73        cerr << "Write failed! " << strerror(errno) << endl;
74        tracing = false;
75        return false;
76    }
77    return true;
78}
79
80int64_t AMD64TraceChild::getRegs(user_regs_struct & myregs, int num)
81{
82        assert(num < numregs && num >= 0);
83        switch(num)
84        {
85                //GPRs
86                case RAX: return myregs.rax;
87                case RBX: return myregs.rbx;
88                case RCX: return myregs.rcx;
89                case RDX: return myregs.rdx;
90                //Index registers
91                case RSI: return myregs.rsi;
92                case RDI: return myregs.rdi;
93                //Base pointer and stack pointer
94                case RBP: return myregs.rbp;
95                case RSP: return myregs.rsp;
96                //New 64 bit mode registers
97                case R8: return myregs.r8;
98                case R9: return myregs.r9;
99                case R10: return myregs.r10;
100                case R11: return myregs.r11;
101                case R12: return myregs.r12;
102                case R13: return myregs.r13;
103                case R14: return myregs.r14;
104                case R15: return myregs.r15;
105                //Segmentation registers
106                case CS: return myregs.cs;
107                case DS: return myregs.ds;
108                case ES: return myregs.es;
109                case FS: return myregs.fs;
110                case GS: return myregs.gs;
111                case SS: return myregs.ss;
112                case FS_BASE: return myregs.fs_base;
113                case GS_BASE: return myregs.gs_base;
114                //PC
115                case RIP: return myregs.rip;
116                //Flags
117                case EFLAGS: return myregs.eflags;
118                default:
119                        assert(0);
120                        return 0;
121        }
122}
123
124bool AMD64TraceChild::update(int pid)
125{
126    oldregs = regs;
127    if(ptrace(PTRACE_GETREGS, pid, 0, &regs) != 0)
128    {
129        cerr << "update: " << strerror(errno) << endl;
130        return false;
131    }
132    for(unsigned int x = 0; x < numregs; x++)
133        regDiffSinceUpdate[x] = (getRegVal(x) != getOldRegVal(x));
134    return true;
135}
136
137AMD64TraceChild::AMD64TraceChild()
138{
139    for(unsigned int x = 0; x < numregs; x++)
140        regDiffSinceUpdate[x] = false;
141}
142
143int64_t AMD64TraceChild::getRegVal(int num)
144{
145        return getRegs(regs, num);
146}
147
148int64_t AMD64TraceChild::getOldRegVal(int num)
149{
150        return getRegs(oldregs, num);
151}
152
153char * AMD64TraceChild::printReg(int num)
154{
155        sprintf(printBuffer, "0x%08X", getRegVal(num));
156        return printBuffer;
157}
158
159ostream & AMD64TraceChild::outputStartState(ostream & os)
160{
161    uint64_t sp = getSP();
162    uint64_t pc = getPC();
163    char obuf[1024];
164    sprintf(obuf, "Initial stack pointer = 0x%016llx\n", sp);
165    os << obuf;
166    sprintf(obuf, "Initial program counter = 0x%016llx\n", pc);
167    os << obuf;
168
169    //Output the argument count
170    uint64_t cargc = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
171    sprintf(obuf, "0x%016llx: Argc = 0x%016llx\n", sp, cargc);
172    os << obuf;
173    sp += 8;
174
175    //Output argv pointers
176    int argCount = 0;
177    uint64_t cargv;
178    do
179    {
180        cargv = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
181        sprintf(obuf, "0x%016llx: argv[%d] = 0x%016llx\n",
182                sp, argCount++, cargv);
183        os << obuf;
184        sp += 8;
185    } while(cargv);
186
187    //Output the envp pointers
188    int envCount = 0;
189    uint64_t cenvp;
190    do
191    {
192        cenvp = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
193        sprintf(obuf, "0x%016llx: envp[%d] = 0x%016llx\n",
194                sp, envCount++, cenvp);
195        os << obuf;
196        sp += 8;
197    } while(cenvp);
198    uint64_t auxType, auxVal;
199    do
200    {
201        auxType = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
202        sp += 8;
203        auxVal = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
204        sp += 8;
205        sprintf(obuf, "0x%016llx: Auxiliary vector = {0x%016llx, 0x%016llx}\n",
206                sp - 16, auxType, auxVal);
207        os << obuf;
208    } while(auxType != 0 || auxVal != 0);
209    //Print out the argument strings, environment strings, and file name.
210    string current;
211    uint64_t buf;
212    uint64_t currentStart = sp;
213    bool clearedInitialPadding = false;
214    do
215    {
216        buf = ptrace(PTRACE_PEEKDATA, pid, sp, 0);
217        char * cbuf = (char *)&buf;
218        for(int x = 0; x < sizeof(uint64_t); x++)
219        {
220            if(cbuf[x])
221                current += cbuf[x];
222            else
223            {
224                sprintf(obuf, "0x%016llx: \"%s\"\n",
225                        currentStart, current.c_str());
226                os << obuf;
227                current = "";
228                currentStart = sp + x + 1;
229            }
230        }
231        sp += 8;
232        clearedInitialPadding = clearedInitialPadding || buf != 0;
233    } while(!clearedInitialPadding || buf != 0);
234    return os;
235}
236
237uint64_t AMD64TraceChild::findSyscall()
238{
239    uint64_t rip = getPC();
240    bool foundOpcode = false;
241    bool twoByteOpcode = false;
242    for(;;)
243    {
244        uint64_t buf = ptrace(PTRACE_PEEKDATA, pid, rip, 0);
245        for(int i = 0; i < sizeof(uint64_t); i++)
246        {
247            unsigned char byte = buf & 0xFF;
248            if(!foundOpcode)
249            {
250                if(!(byte == 0x66 || //operand override
251                     byte == 0x67 || //address override
252                     byte == 0x2E || //cs
253                     byte == 0x3E || //ds
254                     byte == 0x26 || //es
255                     byte == 0x64 || //fs
256                     byte == 0x65 || //gs
257                     byte == 0x36 || //ss
258                     byte == 0xF0 || //lock
259                     byte == 0xF2 || //repe
260                     byte == 0xF3 || //repne
261                     (byte >= 0x40 && byte <= 0x4F) // REX
262                    ))
263                {
264                    foundOpcode = true;
265                }
266            }
267            if(foundOpcode)
268            {
269                if(twoByteOpcode)
270                {
271                    //SYSCALL or SYSENTER
272                    if(byte == 0x05 || byte == 0x34)
273                        return rip + 1;
274                    else
275                        return 0;
276                }
277                if(!twoByteOpcode)
278                {
279                    if(byte == 0xCC) // INT3
280                        return rip + 1;
281                    else if(byte == 0xCD) // INT with byte immediate
282                        return rip + 2;
283                    else if(byte == 0x0F) // two byte opcode prefix
284                        twoByteOpcode = true;
285                    else
286                        return 0;
287                }
288            }
289            buf >>= 8;
290            rip++;
291        }
292    }
293}
294
295bool AMD64TraceChild::step()
296{
297    uint64_t ripAfterSyscall = findSyscall();
298    if(ripAfterSyscall)
299    {
300        //Get the original contents of memory
301        uint64_t buf = ptrace(PTRACE_PEEKDATA, pid, ripAfterSyscall, 0);
302        //Patch the first two bytes of the memory immediately after this with
303        //jmp -2. Either single stepping will take over before this
304        //instruction, leaving the rip where it should be, or it will take
305        //over after this instruction, -still- leaving the rip where it should
306        //be.
307        uint64_t newBuf = (buf & ~0xFFFF) | 0xFEEB;
308        //Write the patched memory to the processes address space
309        ptrace(PTRACE_POKEDATA, pid, ripAfterSyscall, newBuf);
310        //Step and hit it
311        ptraceSingleStep();
312        //Put things back to the way they started
313        ptrace(PTRACE_POKEDATA, pid, ripAfterSyscall, buf);
314    }
315    else
316        ptraceSingleStep();
317}
318
319TraceChild * genTraceChild()
320{
321        return new AMD64TraceChild;
322}
323