summaryrefslogtreecommitdiff
path: root/lib/exceptions.c
blob: 72842a442cd9275db03b645d0ba3c8ac49832a00 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
 *
 * Gestionnaire d'exceptions
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#else
#define _(x) x
#endif
#include "exceptions.h"
#include "pile.h"

char *contexts[128];
int clevel = 0;
int global_error = 0;

char *Estrdup(char *o)
{
	char *r;

	if (o) {
		if (!(r = strdup(o))) {
			exception(2, _("Out of memory."));
		}
	} else {
		return NULL;
	}
	return r;
}

void *Emalloc(size_t s)
{
	void *r;

	if (s) {
		if (!(r = malloc(s))) {
			exception(2, _("Out of memory."));
		}
	} else {
		return NULL;
	}
	return r;
}

void pushcontext(char *c)
{
	if (clevel == 128) {
		exception(2, _("Too much error contexts during pushcontext()."));
	}
	contexts[clevel++] = Estrdup(c);
#ifdef DEBUG
	fprintf(stderr, "%s\n", c);
#endif
}

void popcontext(void)
{
	if (clevel == 0) {
		exception(2, _("Error context empty, but popcontext() called."));
	}
	free(contexts[--clevel]);
}

void flushcontext(void)
{
	while (clevel) {
		popcontext();
	}
}

/* exception avec level=1 pour une erreur non fatale avec vidage de la pile sinon 
pour toutre valeur de level erreur avec terminaison du programme */

void exception(int level, char *msg) 
{
	int i;
	switch (level) {
	case 1:
		fprintf(stderr, "  Error description: %s\n", msg);
		flush_pile();
		global_error = 1;
		break;
	default:
		fprintf(stderr, "Error detected. Showing context.\n");
		for (i = 0; i < clevel; i++) {
			fprintf(stderr, " (%i) - %s\n", i, contexts[i]);
		}
		fprintf(stderr, "  Error description: %s\n", msg);
		exit(1);
		break;
	}	
}