summaryrefslogtreecommitdiff
path: root/lib/librthread/rthread_debug.c
blob: 4115bc7b077fb901daaa3013a390a8599f9769ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* $OpenBSD: rthread_debug.c,v 1.5 2016/09/01 10:56:46 deraadt Exp $ */

/* PUBLIC DOMAIN: No Rights Reserved. Marco S Hyman <marc@snafu.org> */

#include <pthread.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "rthread.h"

REDIRECT_SYSCALL(issetugid);

int _rthread_debug_level;

/*
 * Note: messages truncated at 255 characters.   Could use vasprintf,
 * but don't want to use malloc here so the function can be used
 * in signal handlers.
 */
#define MAX_MSG_LEN 256
#define RTHREAD_ENV_DEBUG	"RTHREAD_DEBUG"

/*
 * format and send output to stderr if the given "level" is less than or
 * equal to the current debug level.   Messages with a level <= 0 will
 * always be printed.
 */
void
_rthread_debug(int level, const char *fmt, ...)
{
	char msg[MAX_MSG_LEN];
	char *p;
	int cnt;
	ssize_t c;

	if (_rthread_debug_level >= level) {
		va_list ap;
		va_start(ap, fmt);
		cnt = vsnprintf(msg, MAX_MSG_LEN, fmt, ap);
		va_end(ap);
		if (cnt > MAX_MSG_LEN - 1)
			cnt = MAX_MSG_LEN - 1;
		p = msg;
		do {
			c = write(STDERR_FILENO, p, cnt);
			if (c == -1)
				break;
			if (c != cnt)
				sched_yield();
			p += c;
			cnt -= c;
		} while (cnt > 0);
	}
}

/*
 * set the debug level from an environment string.  Bogus values are
 * silently ignored.
 */
void
_rthread_debug_init(void)
{
	char *envp;
	char *rem;

	if (issetugid())
		return;
	envp = getenv(RTHREAD_ENV_DEBUG);
	if (envp) {
		_rthread_debug_level = (int) strtol(envp, &rem, 0);
		if (*rem || _rthread_debug_level < 0)
			_rthread_debug_level = 0;
	}
}