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

Last change on this file since 3320 was 3320, checked in by Pascal Terjan, 13 years ago
  • Fix passing of env to execve syscall
  • Property svn:eol-style set to native
File size: 16.2 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 *newargv[] = { 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    l = strlen(command)+1;
376    l2 = sizeof(char *);
377    p2 = regs.RSP;
378    memcpy_into_target(t, p2, command, l);
379    p2 += l;
380    argvaddr = p2;
381    memcpy_into_target(t, p2, (char *)&regs.RSP, l2);
382    p2 += l2;
383    memcpy_into_target(t, p2, (char *)&newargv, l2);
384    p2 += l2;
385    memcpy_into_target(t, p2, env, envsize);
386    envaddr = p2;
387    p2 += envsize;
388    envptraddr = p2;
389    p = env;
390    while (p < env+envsize)
391    {
392        long diffp = p - env + envaddr;
393        memcpy_into_target(t, p2, (char *)&diffp, l2);
394        p2 += l2;
395        p += strlen(p)+1;
396    }
397    memcpy_into_target(t, p2, (char *)&newargv, l2);
398    free(env);
399    ret = remote_syscall(t, MYCALL_EXECVE, regs.RSP, argvaddr, envptraddr);
400
401    if(ret < 0)
402    {
403        errno = ret;
404        return -1;
405    }
406
407    return ret;
408#else
409    errno = ENOSYS;
410    return -1;
411#endif
412}
413
414/*
415 * XXX: the following functions are local
416 */
417
418#if defined USE_GRAB
419static int memcpy_from_target(struct mytrace *t,
420                              char* dest, long src, size_t n)
421{
422    static int const align = sizeof(long) - 1;
423
424    while(n)
425    {
426        long data;
427        size_t todo = sizeof(long) - (src & align);
428
429        if(n < todo)
430            todo = n;
431
432        data = ptrace(PTRACE_PEEKTEXT, t->pid, src - (src & align), 0);
433        if(errno)
434        {
435            perror("ptrace_peektext");
436            return -1;
437        }
438        memcpy(dest, (char *)&data + (src & align), todo);
439
440        dest += todo;
441        src += todo;
442        n -= todo;
443    }
444
445    return 0;
446}
447
448static int memcpy_into_target(struct mytrace *t,
449                              long dest, char const *src, size_t n)
450{
451    static int const align = sizeof(long) - 1;
452
453    while(n)
454    {
455        long data;
456        size_t todo = sizeof(long) - (dest & align);
457
458        if(n < todo)
459            todo = n;
460        if(todo != sizeof(long))
461        {
462            data = ptrace(PTRACE_PEEKTEXT, t->pid, dest - (dest & align), 0);
463            if(errno)
464            {
465                perror("ptrace_peektext");
466                return -1;
467            }
468        }
469
470        memcpy((char *)&data + (dest & align), src, todo);
471        ptrace(PTRACE_POKETEXT, t->pid, dest - (dest & align), data);
472        if(errno)
473        {
474            perror("ptrace_poketext");
475            return -1;
476        }
477
478        src += todo;
479        dest += todo;
480        n -= todo;
481    }
482
483    return 0;
484}
485
486static long remote_syscall(struct mytrace *t, long call,
487                           long arg1, long arg2, long arg3)
488{
489    /* Method for remote syscall:
490     *  - wait until the traced application exits from a syscall
491     *  - save registers
492     *  - rewind eip/rip to point on the syscall instruction
493     *  - single step: execute syscall instruction
494     *  - retrieve resulting registers
495     *  - restore registers */
496    struct user_regs_struct regs, oldregs;
497    long oinst;
498    int bits;
499    int offset = 2;
500
501    if(call < 0 || call >= (long)(sizeof(syscallnames)/sizeof(*syscallnames)))
502    {
503        fprintf(stderr, "unknown remote syscall %li\n", call);
504        return -1;
505    }
506
507    debug("remote syscall %s(0x%lx, 0x%lx, 0x%lx)",
508          syscallnames[call], arg1, arg2, arg3);
509
510#if defined __x86_64__
511    bits = 64;
512#else
513    bits = 32;
514#endif
515
516    for(;;)
517    {
518        if(ptrace(PTRACE_GETREGS, t->pid, NULL, &oldregs) < 0)
519        {
520            fprintf(stderr, "PTRACE_GETREGS failed\n");
521            return -1;
522        }
523
524        oinst = ptrace(PTRACE_PEEKTEXT, t->pid, oldregs.RIP - 2, 0) & 0xffff;
525
526#if defined __x86_64__
527        if(oinst == SYSCALL_AMD64)
528            break;
529        if(oinst == SYSCALL_X86 || oinst == SYSCALL_X86_NEW)
530        {
531            bits = 32;
532            break;
533        }
534#else
535        if(oinst == SYSCALL_X86 || oinst == SYSCALL_X86_NEW)
536            break;
537#endif
538
539        if(ptrace(PTRACE_SYSCALL, t->pid, NULL, 0) < 0)
540        {
541            perror("ptrace_syscall (1)");
542            return -1;
543        }
544        waitpid(t->pid, NULL, 0);
545        if(ptrace(PTRACE_SYSCALL, t->pid, NULL, 0) < 0)
546        {
547            perror("ptrace_syscall (2)");
548            return -1;
549        }
550        waitpid(t->pid, NULL, 0);
551    }
552
553    print_registers(t->pid);
554
555    if(oinst == SYSCALL_X86_NEW)
556    {
557        /*  Get back to sysenter */
558        while((ptrace(PTRACE_PEEKTEXT, t->pid, oldregs.RIP - offset, 0) & 0xffff) != 0x340f)
559            offset++;
560        oldregs.RBP = oldregs.RSP;
561    }
562
563    regs = oldregs;
564    regs.RIP = regs.RIP - offset;
565#if defined __x86_64__
566    if(bits == 64)
567    {
568        regs.RAX = syscalls64[call];
569        regs.RDI = arg1;
570        regs.RSI = arg2;
571        regs.RDX = arg3;
572    }
573    else
574#endif
575    {
576        regs.RAX = syscalls32[call];
577        regs.RBX = arg1;
578        regs.RCX = arg2;
579        regs.RDX = arg3;
580    }
581
582    if(ptrace(PTRACE_SETREGS, t->pid, NULL, &regs) < 0)
583    {
584        fprintf(stderr, "PTRACE_SETREGS failed\n");
585        return -1;
586    }
587
588    for(;;)
589    {
590        int status;
591
592        print_registers(t->pid);
593
594        if(ptrace(PTRACE_SINGLESTEP, t->pid, NULL, NULL) < 0)
595        {
596            fprintf(stderr, "PTRACE_SINGLESTEP failed\n");
597            return -1;
598        }
599        waitpid(t->pid, &status, 0);
600
601        if(WIFEXITED(status))
602            return 0;
603
604        if(!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP)
605            continue;
606
607        /* Fuck Linux: there is no macro for this */
608        switch((status >> 16) & 0xffff)
609        {
610        case PTRACE_EVENT_FORK:
611            if(ptrace(PTRACE_GETEVENTMSG, t->pid, 0, &t->child) < 0)
612            {
613                fprintf(stderr, "PTRACE_GETEVENTMSG failed\n");
614                return -1;
615            }
616            debug("PTRACE_GETEVENTMSG %d", t->child);
617            continue;
618        case PTRACE_EVENT_EXIT:
619            debug("PTRACE_EVENT_EXIT");
620            /* The process is about to exit, don't do anything else */
621            return 0;
622        case PTRACE_EVENT_EXEC:
623            debug("PTRACE_EVENT_EXEC");
624            return 0;
625        }
626
627        break;
628    }
629
630    print_registers(t->pid);
631
632    if(ptrace(PTRACE_GETREGS, t->pid, NULL, &regs) < 0)
633    {
634        fprintf(stderr, "PTRACE_GETREGS failed\n");
635        return -1;
636    }
637
638    if(ptrace(PTRACE_SETREGS, t->pid, NULL, &oldregs) < 0)
639    {
640        fprintf(stderr, "PTRACE_SETREGS failed\n");
641        return -1;
642    }
643    print_registers(t->pid);
644
645    debug("syscall %s returned %ld", syscallnames[call], regs.RAX);
646
647    if((long)regs.RAX < 0)
648    {
649        errno = -(long)regs.RAX;
650        perror("syscall");
651        return -1;
652    }
653
654    return regs.RAX;
655}
656
657/* For debugging purposes only. Prints register and stack information. */
658#if defined DEBUG
659static void print_registers(pid_t pid)
660{
661    union { long int l; unsigned char data[sizeof(long int)]; } inst;
662    struct user_regs_struct regs;
663    int i;
664
665    if(ptrace(PTRACE_GETREGS, pid, NULL, &regs) < 0)
666    {
667        perror("ptrace_getregs");
668        exit(errno);
669    }
670
671    fprintf(stderr, "  / %s: "FMT"   ", STRINGIFY(RAX), regs.RAX);
672    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RBX), regs.RBX);
673    fprintf(stderr, "  | %s: "FMT"   ", STRINGIFY(RCX), regs.RCX);
674    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RDX), regs.RDX);
675    fprintf(stderr, "  | %s: "FMT"   ", STRINGIFY(RDI), regs.RDI);
676    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RSI), regs.RSI);
677    fprintf(stderr, "  | %s: "FMT"   ", STRINGIFY(RSP), regs.RSP);
678    fprintf(stderr, "%s: "FMT"\n", STRINGIFY(RIP), regs.RIP);
679
680    inst.l = ptrace(PTRACE_PEEKTEXT, pid, regs.RIP - 4, 0);
681    fprintf(stderr, "  | code: ... %02x %02x %02x %02x <---> ",
682            inst.data[0], inst.data[1], inst.data[2], inst.data[3]);
683    inst.l = ptrace(PTRACE_PEEKTEXT, pid, regs.RIP, 0);
684    fprintf(stderr, "%02x %02x %02x %02x ...\n",
685            inst.data[0], inst.data[1], inst.data[2], inst.data[3]);
686
687    fprintf(stderr, "  \\ stack: ... ");
688    for(i = -16; i < 24; i += sizeof(long))
689    {
690        inst.l = ptrace(PTRACE_PEEKDATA, pid, regs.RSP + i, 0);
691#if defined __x86_64__
692        fprintf(stderr, "%02x %02x %02x %02x %02x %02x %02x %02x ",
693                inst.data[0], inst.data[1], inst.data[2], inst.data[3],
694                inst.data[4], inst.data[5], inst.data[6], inst.data[7]);
695#else
696        fprintf(stderr, "%02x %02x %02x %02x ",
697                inst.data[0], inst.data[1], inst.data[2], inst.data[3]);
698#endif
699        if(i == 0)
700            fprintf(stderr, "[%s] ", STRINGIFY(RSP));
701    }
702    fprintf(stderr, "...\n");
703}
704#endif /* DEBUG */
705
706#endif /* USE_GRAB */
Note: See TracBrowser for help on using the repository browser.