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