tizen 2.0
[external/ltrace.git] / debug.c
1 #include <stdio.h>
2 #include <stdarg.h>
3
4 #include "common.h"
5
6 void
7 debug_(int level, const char *file, int line, const char *fmt, ...) {
8         char buf[1024];
9         va_list args;
10
11         if (!(options.debug & level)) {
12                 return;
13         }
14         va_start(args, fmt);
15         vsnprintf(buf, 1024, fmt, args);
16         va_end(args);
17
18         output_line(NULL, "DEBUG: %s:%d: %s", file, line, buf);
19 }
20
21 /*
22  * The following section provides a way to print things, like hex dumps,
23  * with out using buffered output.  This was written by Steve Munroe of IBM.
24  */
25
26 #include <stdio.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <sys/ptrace.h>
31
32 static int
33 xwritehexl(long i) {
34         int rc = 0;
35         char text[17];
36         int j;
37         unsigned long temp = (unsigned long)i;
38
39         for (j = 15; j >= 0; j--) {
40                 char c;
41                 c = (char)((temp & 0x0f) + '0');
42                 if (c > '9') {
43                         c = (char)(c + ('a' - '9' - 1));
44                 }
45                 text[j] = c;
46                 temp = temp >> 4;
47         }
48
49         rc = write(1, text, 16);
50         return rc;
51 }
52
53 static int
54 xwritec(char c) {
55         char temp = c;
56         char *text = &temp;
57         int rc = 0;
58         rc = write(1, text, 1);
59         return rc;
60 }
61
62 static int
63 xwritecr(void) {
64         return xwritec('\n');
65 }
66
67 static int
68 xwritedump(void *ptr, long addr, int len) {
69         int rc = 0;
70         long *tprt = (long *)ptr;
71         int i;
72
73         for (i = 0; i < len; i += 8) {
74                 xwritehexl(addr);
75                 xwritec('-');
76                 xwritec('>');
77                 xwritehexl(*tprt++);
78                 xwritecr();
79                 addr += sizeof(long);
80         }
81
82         return rc;
83 }
84
85 int
86 xinfdump(long pid, void *ptr, int len) {
87         int rc;
88         int i;
89         long wrdcnt;
90         long *infwords;
91         long addr;
92
93         wrdcnt = len / sizeof(long) + 1;
94         infwords = malloc(wrdcnt * sizeof(long));
95         if (!infwords) {
96                 perror("ltrace: malloc");
97                 exit(1);
98         }
99         addr = (long)ptr;
100
101         addr = ((addr + sizeof(long) - 1) / sizeof(long)) * sizeof(long);
102
103         for (i = 0; i < wrdcnt; ++i) {
104                 infwords[i] = ptrace(PTRACE_PEEKTEXT, pid, addr);
105                 addr += sizeof(long);
106         }
107
108         rc = xwritedump(infwords, (long)ptr, len);
109
110         free(infwords);
111         return rc;
112 }