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