source: neercs/trunk/src/mytrace.c @ 3322

Last change on this file since 3322 was 3322, checked in by Pascal Terjan, 11 years ago
  • Add comments to mytrace_exec
  • Property svn:eol-style set to native
File size: 16.6 KB
Line 
1/*
2 *  neercs        console-based window manager
3 *  Copyright (c) 2008 Pascal Terjan
4 *            (c) 2008 Sam Hocevar <sam@zoy.org>
5 *                All Rights Reserved
6 *
7 *  $Id$
8 *
9 *  This program is free software. It comes without any warranty, to
10 *  the extent permitted by applicable law. You can redistribute it
11 *  and/or modify it under the terms of the Do What The Fuck You Want
12 *  To Public License, Version 2, as published by Sam Hocevar. See
13 *  http://sam.zoy.org/wtfpl/COPYING for more details.
14 */
15
16#include "config.h"
17
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <stdio.h>
22#include <stdlib.h>
23#include <string.h>
24
25#if defined USE_GRAB
26#   include <sys/ptrace.h>
27#   include <sys/stat.h>
28#   include <sys/syscall.h>
29#   include <sys/user.h>
30#   include <sys/wait.h>
31#endif
32
33#include "neercs.h"
34#include "mytrace.h"
35
36#if defined USE_GRAB
37static int memcpy_from_target(struct mytrace *t,
38                              char* dest, long src, size_t n);
39static int memcpy_into_target(struct mytrace *t,
40                              long dest, char const *src, size_t n);
41static long remote_syscall(struct mytrace *t, long call,
42                           long arg1, long arg2, long arg3);
43#   if defined DEBUG
44static void print_registers(pid_t pid);
45#   else
46#       define print_registers(x) do {} while(0)
47#   endif
48
49#define X(x) #x
50#define STRINGIFY(x) X(x)
51
52#define SYSCALL_X86     0x80cd  /* CD 80 = int $0x80 */
53#define SYSCALL_X86_NEW 0xf3eb  /* EB F3 = jmp <__kernel_vsyscall+0x3> */
54#define SYSENTER        0x340f  /* 0F 34 = sysenter */
55#define SYSCALL_AMD64   0x050fL /* 0F 05 = syscall */
56
57#if defined __x86_64__
58#   define RAX rax
59#   define RBX rbx
60#   define RCX rcx
61#   define RDX rdx
62#   define RSP rsp
63#   define RBP rbp
64#   define RIP rip
65#   define RDI rdi
66#   define RSI rsi
67#   define FMT "%016lx"
68#else
69#   define RAX eax
70#   define RBX ebx
71#   define RCX ecx
72#   define RDX edx
73#   define RSP esp
74#   define RBP ebp
75#   define RIP eip
76#   define RDI edi
77#   define RSI esi
78#   define FMT "%08lx"
79#endif
80
81#define MYCALL_OPEN     0
82#define MYCALL_CLOSE    1
83#define MYCALL_WRITE    2
84#define MYCALL_DUP2     3
85#define MYCALL_SETPGID  4
86#define MYCALL_SETSID   5
87#define MYCALL_KILL     6
88#define MYCALL_FORK     7
89#define MYCALL_EXIT     8
90#define MYCALL_EXECVE   9
91
92#if defined __x86_64__
93/* from unistd_32.h on an amd64 system */
94int syscalls32[] = { 5, 6, 4, 63, 57, 66, 37, 2, 1, 11 };
95int syscalls64[] =
96#else
97int syscalls32[] =
98#endif
99    { SYS_open, SYS_close, SYS_write, SYS_dup2, SYS_setpgid, SYS_setsid,
100      SYS_kill, SYS_fork, SYS_exit, SYS_execve };
101
102char const *syscallnames[] =
103    { "open", "close", "write", "dup2", "setpgid", "setsid", "kill", "fork",
104      "exit", "execve" };
105
106#endif /* USE_GRAB */
107
108struct mytrace
109{
110    pid_t pid, child;
111};
112
113struct mytrace* mytrace_attach(long int pid)
114{
115#if defined USE_GRAB
116    struct mytrace *t;
117    int status;
118
119    if(ptrace(PTRACE_ATTACH, pid, 0, 0) < 0)
120    {
121        perror("ptrace_attach");
122        return NULL;
123    }
124    if(waitpid(pid, &status, 0) < 0)
125    {
126        perror("waitpid");
127        return NULL;
128    }
129    if(!WIFSTOPPED(status))
130    {
131        fprintf(stderr, "traced process was not stopped\n");
132        ptrace(PTRACE_DETACH, pid, 0, 0);
133        return NULL;
134    }
135
136    t = malloc(sizeof(struct mytrace));
137    t->pid = pid;
138    t->child = 0;
139
140    return t;
141#else
142    errno = ENOSYS;
143    return NULL;
144#endif
145}
146
147struct mytrace* mytrace_fork(struct mytrace *t)
148{
149#if defined USE_GRAB
150    struct mytrace *child;
151
152    ptrace(PTRACE_SETOPTIONS, t->pid, NULL, PTRACE_O_TRACEFORK);
153    remote_syscall(t, MYCALL_FORK, 0, 0, 0);
154    waitpid(t->child, NULL, 0);
155
156    child = malloc(sizeof(struct mytrace));
157    child->pid = t->child;
158    child->child = 0;
159
160    return child;
161#else
162    errno = ENOSYS;
163    return NULL;
164#endif
165}
166
167int mytrace_detach(struct mytrace *t)
168{
169#if defined USE_GRAB
170    ptrace(PTRACE_DETACH, t->pid, 0, 0);
171    free(t);
172
173    return 0;
174#else
175    errno = ENOSYS;
176    return -1;
177#endif
178}
179
180long mytrace_getpid(struct mytrace *t)
181{
182#if defined USE_GRAB
183    return t->pid;
184#else
185    errno = ENOSYS;
186    return -1;
187#endif
188}
189
190int mytrace_open(struct mytrace *t, char const *path, int mode)
191{
192#if defined USE_GRAB
193    char backup_data[4096];
194    struct user_regs_struct regs;
195    size_t size = strlen(path) + 1;
196    int ret;
197
198    if(ptrace(PTRACE_GETREGS, t->pid, NULL, &regs) < 0)
199    {
200        fprintf(stderr, "PTRACE_GETREGS failed\n");
201        return errno;
202    }
203
204    /* Backup the data that we will use */
205    if(memcpy_from_target(t, backup_data, regs.RSP, size) < 0)
206        return -1;
207
208    memcpy_into_target(t, regs.RSP, path, size);
209
210    ret = remote_syscall(t, MYCALL_OPEN, regs.RSP, O_RDWR, 0755);
211
212    /* Restore the data */
213    memcpy_into_target(t, regs.RSP, backup_data, size);
214
215    if(ret < 0)
216    {
217        errno = ret;
218        return -1;
219    }
220
221    return ret;
222#else
223    errno = ENOSYS;
224    return -1;
225#endif
226}
227
228int mytrace_close(struct mytrace *t, int fd)
229{
230#if defined USE_GRAB
231    return remote_syscall(t, MYCALL_CLOSE, fd, 0, 0);
232#else
233    errno = ENOSYS;
234    return -1;
235#endif
236}
237
238int mytrace_write(struct mytrace *t, int fd, char const *data, size_t len)
239{
240#if defined USE_GRAB
241    struct user_regs_struct regs;
242    char *backup_data;
243    int ret;
244
245    if(ptrace(PTRACE_GETREGS, t->pid, NULL, &regs) < 0)
246    {
247        fprintf(stderr, "PTRACE_GETREGS failed\n");
248        return errno;
249    }
250
251    backup_data = malloc(len);
252
253    /* Backup the data that we will use */
254    if(memcpy_from_target(t, backup_data, regs.RSP, len) < 0)
255        return -1;
256
257    memcpy_into_target(t, regs.RSP, data, len);
258
259    ret = remote_syscall(t, MYCALL_WRITE, fd, regs.RSP, len);
260
261    /* Restore the data */
262    memcpy_into_target(t, regs.RSP, backup_data, len);
263
264    if(ret < 0)
265    {
266        errno = ret;
267        return -1;
268    }
269
270    return ret;
271#else
272    errno = ENOSYS;
273    return -1;
274#endif
275}
276
277int mytrace_dup2(struct mytrace *t, int oldfd, int newfd)
278{
279#if defined USE_GRAB
280    return remote_syscall(t, MYCALL_DUP2, oldfd, newfd, 0);
281#else
282    errno = ENOSYS;
283    return -1;
284#endif
285}
286
287int mytrace_setpgid(struct mytrace *t, long pid, long pgid)
288{
289#if defined USE_GRAB
290    return remote_syscall(t, MYCALL_SETPGID, pid, pgid, 0);
291#else
292    errno = ENOSYS;
293    return -1;
294#endif
295}
296
297int mytrace_setsid(struct mytrace *t)
298{
299#if defined USE_GRAB
300    return remote_syscall(t, MYCALL_SETSID, 0, 0, 0);
301#else
302    errno = ENOSYS;
303    return -1;
304#endif
305}
306
307int mytrace_kill(struct mytrace *t, long pid, int sig)
308{
309#if defined USE_GRAB
310    return remote_syscall(t, MYCALL_KILL, pid, sig, 0);
311#else
312    errno = ENOSYS;
313    return -1;
314#endif
315}
316
317int mytrace_exit(struct mytrace *t, int status)
318{
319#if defined USE_GRAB
320    ptrace(PTRACE_SETOPTIONS, t->pid, NULL, PTRACE_O_TRACEEXIT);
321    return remote_syscall(t, MYCALL_EXIT, status, 0, 0);
322#else
323    errno = ENOSYS;
324    return -1;
325#endif
326}
327
328int mytrace_exec(struct mytrace *t, char const *command)
329{
330#if defined USE_GRAB
331    struct user_regs_struct regs;
332    char *env, *p;
333    long p2, envaddr, argvaddr, envptraddr;
334    char envpath[PATH_MAX+1];
335    ssize_t envsize = 16*1024;
336    int ret, fd, l, l2;
337    char *nullp = NULL;
338    ssize_t r;
339
340    ptrace(PTRACE_SETOPTIONS, t->pid, NULL, PTRACE_O_TRACEEXEC);
341
342    if(ptrace(PTRACE_GETREGS, t->pid, NULL, &regs) < 0)
343    {
344        fprintf(stderr, "PTRACE_GETREGS failed\n");
345        return errno;
346    }
347
348    debug("PTRACE_GETREGS done");
349    env = malloc(envsize);
350    if (!env)
351        return -1;
352
353    snprintf(envpath, PATH_MAX, "/proc/%d/environ", t->pid);
354
355    fd = open(envpath, O_RDONLY);
356    if (fd == -1)
357        return -1;
358    r = read(fd, env, envsize);
359    close(fd);
360    if (r == -1)
361        return -1;
362    while (r == envsize)
363    {
364        free(env);
365        env = malloc(envsize);
366        if (!env)
367            return -1;
368        fd = open(envpath, O_RDONLY);
369        r = read(fd, env, envsize);
370        close(fd);
371        if (r == -1)
372            return -1;
373    }
374    envsize = r;
375    l2 = sizeof(char *); /* Size of a pointer */
376    p2 = regs.RSP;
377
378    /* First argument is the command string */
379    l = strlen(command)+1;
380    memcpy_into_target(t, p2, command, l);
381    p2 += l;
382
383    /* Second argument is argv */
384    argvaddr = p2;
385    /* argv[0] is a pointer to the command string */
386    memcpy_into_target(t, p2, (char *)&regs.RSP, l2);
387    p2 += l2;
388    /* Then follows a NULL pointer */
389    memcpy_into_target(t, p2, (char *)&nullp, l2);
390    p2 += l2;
391
392    /* Third argument is the environment */
393    /* First, copy all the strings */
394    memcpy_into_target(t, p2, env, envsize);
395    envaddr = p2;
396    p2 += envsize;
397    /* Then write an array of pointers to the strings */
398    envptraddr = p2;
399    p = env;
400    while (p < env+envsize)
401    {
402        long diffp = p - env + envaddr;
403        memcpy_into_target(t, p2, (char *)&diffp, l2);
404        p2 += l2;
405        p += strlen(p)+1;
406    }
407    /* And have a NULL pointer at the end of the array */
408    memcpy_into_target(t, p2, (char *)&nullp, l2);
409    free(env);
410
411    ret = remote_syscall(t, MYCALL_EXECVE, regs.RSP, argvaddr, envptraddr);
412
413    if(ret < 0)
414    {
415        errno = ret;
416        return -1;
417    }
418
419    return ret;
420#else
421    errno = ENOSYS;
422    return -1;
423#endif
424}
425
426/*
427 * XXX: the following functions are local
428 */
429
430#if defined USE_GRAB
431static int memcpy_from_target(struct mytrace *t,
432                              char* dest, long src, size_t n)
433{
434    static int const align = sizeof(long) - 1;
435
436    while(n)
437    {
438        long data;
439        size_t todo = sizeof(long) - (src & align);
440
441        if(n < todo)
442            todo = n;
443
444        data = ptrace(PTRACE_PEEKTEXT, t->pid, src - (src & align), 0);
445        if(errno)
446        {
447            perror("ptrace_peektext");
448            return -1;
449        }
450        memcpy(dest, (char *)&data + (src & align), todo);
451
452        dest += todo;
453        src += todo;
454        n -= todo;
455    }
456
457    return 0;
458}
459
460static int memcpy_into_target(struct mytrace *t,
461                              long dest, char const *src, size_t n)
462{
463    static int const align = sizeof(long) - 1;
464
465    while(n)
466    {
467        long data;
468        size_t todo = sizeof(long) - (dest & align);
469
470        if(n < todo)
471            todo = n;
472        if(todo != sizeof(long))
473        {
474            data = ptrace(PTRACE_PEEKTEXT, t->pid, dest - (dest & align), 0);
475            if(errno)
476            {
477                perror("ptrace_peektext");
478                return -1;
479            }
480        }
481
482        memcpy((char *)&data + (dest & align), src, todo);
483        ptrace(PTRACE_POKETEXT, t->pid, dest - (dest & align), data);
484        if(errno)
485        {
486            perror("ptrace_poketext");
487            return -1;
488        }
489
490        src += todo;
491        dest += todo;
492        n -= todo;
493    }
494
495    return 0;
496}
497
498static long remote_syscall(struct mytrace *t, long call,
499                           long arg1, long arg2, long arg3)
500{
501    /* Method for remote syscall:
502     *  - wait until the traced application exits from a syscall
503     *  - save registers
504     *  - rewind eip/rip to point on the syscall instruction
505     *  - single step: execute syscall instruction
506     *  - retrieve resulting registers
507     *  - restore registers */
508    struct user_regs_struct regs, oldregs;
509    long oinst;
510    int bits;
511    int offset = 2;
512
513    if(call < 0 || call >= (long)(sizeof(syscallnames)/sizeof(*syscallnames)))
514    {
515        fprintf(stderr, "unknown remote syscall %li\n", call);
516        return -1;
517    }
518
519    debug("remote syscall %s(0x%lx, 0x%lx, 0x%lx)",
520          syscallnames[call], arg1, arg2, arg3);
521
522#if defined __x86_64__
523    bits = 64;
524#else
525    bits = 32;
526#endif
527
528    for(;;)
529    {
530        if(ptrace(PTRACE_GETREGS, t->pid, NULL, &oldregs) < 0)
531        {
532            fprintf(stderr, "PTRACE_GETREGS failed\n");
533            return -1;
534        }
535
536        oinst = ptrace(PTRACE_PEEKTEXT, t->pid, oldregs.RIP - 2, 0) & 0xffff;
537
538#if defined __x86_64__
539        if(oinst == SYSCALL_AMD64)
540            break;
541        if(oinst == SYSCALL_X86 || oinst == SYSCALL_X86_NEW)
542        {
543            bits = 32;
544            break;
545        }
546#else
547        if(oinst == SYSCALL_X86 || oinst == SYSCALL_X86_NEW)
548            break;
549#endif
550
551        if(ptrace(PTRACE_SYSCALL, t->pid, NULL, 0) < 0)
552        {
553            perror("ptrace_syscall (1)");
554            return -1;
555        }
556        waitpid(t->pid, NULL, 0);
557        if(ptrace(PTRACE_SYSCALL, t->pid, NULL, 0) < 0)
558        {
559            perror("ptrace_syscall (2)");
560            return -1;
561        }
562        waitpid(t->pid, NULL, 0);
563    }
564
565    print_registers(t->pid);
566
567    if(oinst == SYSCALL_X86_NEW)
568    {
569        /*  Get back to sysenter */
570        while((ptrace(PTRACE_PEEKTEXT, t->pid, oldregs.RIP - offset, 0) & 0xffff) != 0x340f)
571            offset++;
572        oldregs.RBP = oldregs.RSP;
573    }
574
575    regs = oldregs;
576    regs.RIP = regs.RIP - offset;
577#if defined __x86_64__
578    if(bits == 64)
579    {
580        regs.RAX = syscalls64[call];
581        regs.RDI = arg1;
582        regs.RSI = arg2;
583        regs.RDX = arg3;
584    }
585    else
586#endif
587    {
588        regs.RAX = syscalls32[call];
589        regs.RBX = arg1;
590        regs.RCX = arg2;
591        regs.RDX = arg3;
592    }
593
594    if(ptrace(PTRACE_SETREGS, t->pid, NULL, &regs) < 0)
595    {
596        fprintf(stderr, "PTRACE_SETREGS failed\n");
597        return -1;
598    }
599
600    for(;;)
601    {
602        int status;
603
604        print_registers(t->pid);
605
606        if(ptrace(PTRACE_SINGLESTEP, t->pid, NULL, NULL) < 0)
607        {
608            fprintf(stderr, "PTRACE_SINGLESTEP failed\n");
609            return -1;
610        }
611        waitpid(t->pid, &status, 0);
612
613        if(WIFEXITED(status))
614            return 0;
615
616        if(!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP)
617            continue;
618
619        /* Fuck Linux: there is no macro for this */
620        switch((status >> 16) & 0xffff)
621        {
622        case PTRACE_EVENT_FORK:
623            if(ptrace(PTRACE_GETEVENTMSG, t->pid, 0, &t->child) < 0)
624            {
625                fprintf(stderr, "PTRACE_GETEVENTMSG failed\n");
626                return -1;
627            }
628            debug("PTRACE_GETEVENTMSG %d", t->child);
629            continue;
630        case PTRACE_EVENT_EXIT:
631            debug("PTRACE_EVENT_EXIT");
632            /* The process is about to exit, don't do anything else */
633            return 0;
634        case PTRACE_EVENT_EXEC:
635            debug("PTRACE_EVENT_EXEC");
636            return 0;
637        }
638
639        break;
640    }
641
642    print_registers(t->pid);
643
644    if(ptrace(PTRACE_GETREGS, t->pid, NULL, &regs) < 0)
645    {
646        fprintf(stderr, "PTRACE_GETREGS failed\n");
647        return -1;
648    }
649
650    if(ptrace(PTRACE_SETREGS, t->pid, NULL, &oldregs) < 0)
651    {
652        fprintf(stderr, "PTRACE_SETREGS failed\n");
653        return -1;
654    }
655    print_registers(t->pid);
656
657    debug("syscall %s returned %ld", syscallnames[call], regs.RAX);
658
659    if((long)regs.RAX < 0)
660    {
661        errno = -(long)regs.RAX;
662        perror("syscall");
663        return -1;
664    }
665
666    return regs.RAX;
667}
668
669/* For debugging purposes only. Prints register and stack information. */
670#if defined DEBUG
671static void print_registers(pid_t pid)
672{
673    union { long int l; unsigned char data[sizeof(long int)]; } inst;
674    struct user_regs_struct regs;
675    int i;
676
677    if(ptrace(PTRACE_GETREGS, pid, NULL, &regs) < 0)
678    {
679        perror("ptrace_getregs");
680        exit(errno);
681    }
682
683    fprintf(stderr, "  / %s: "FMT"   ", STRINGIFY(RAX), regs.RAX);
684    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RBX), regs.RBX);
685    fprintf(stderr, "  | %s: "FMT"   ", STRINGIFY(RCX), regs.RCX);
686    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RDX), regs.RDX);
687    fprintf(stderr, "  | %s: "FMT"   ", STRINGIFY(RDI), regs.RDI);
688    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RSI), regs.RSI);
689    fprintf(stderr, "  | %s: "FMT"   ", STRINGIFY(RSP), regs.RSP);
690    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RIP), regs.RIP);
691
692    inst.l = ptrace(PTRACE_PEEKTEXT, pid, regs.RIP - 4, 0);
693    fprintf(stderr, "  | code: ... %02x %02x %02x %02x <---> ",
694            inst.data[0], inst.data[1], inst.data[2], inst.data[3]);
695    inst.l = ptrace(PTRACE_PEEKTEXT, pid, regs.RIP, 0);
696    fprintf(stderr, "%02x %02x %02x %02x ...\n",
697            inst.data[0], inst.data[1], inst.data[2], inst.data[3]);
698
699    fprintf(stderr, "  \\ stack: ... ");
700    for(i = -16; i < 24; i += sizeof(long))
701    {
702        inst.l = ptrace(PTRACE_PEEKDATA, pid, regs.RSP + i, 0);
703#if defined __x86_64__
704        fprintf(stderr, "%02x %02x %02x %02x %02x %02x %02x %02x ",
705                inst.data[0], inst.data[1], inst.data[2], inst.data[3],
706                inst.data[4], inst.data[5], inst.data[6], inst.data[7]);
707#else
708        fprintf(stderr, "%02x %02x %02x %02x ",
709                inst.data[0], inst.data[1], inst.data[2], inst.data[3]);
710#endif
711        if(i == 0)
712            fprintf(stderr, "[%s] ", STRINGIFY(RSP));
713    }
714    fprintf(stderr, "...\n");
715}
716#endif /* DEBUG */
717
718#endif /* USE_GRAB */
Note: See TracBrowser for help on using the repository browser.