File: utils.c

package info (click to toggle)
cryptsetup 20050111-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 252 kB
  • ctags: 156
  • sloc: ansic: 1,305; sh: 675; makefile: 159
file content (125 lines) | stat: -rw-r--r-- 1,747 bytes parent folder | download
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdarg.h>

#include "libcryptsetup.h"
#include "internal.h"

struct safe_allocation {
	size_t	size;
	char	data[1];
};

static char *error;

void set_error_va(const char *fmt, va_list va)
{
	int bufsize;

	bufsize = fmt ? (strlen(fmt) + 1) : 0;
	if (bufsize < 128)
		bufsize = 128;

	if (error)
		free(error);
	if (!fmt) {
		error = NULL;
		return;
	}

	error = malloc(bufsize);

	for(;;) {
		int n;

		n = vsnprintf(error, bufsize, fmt, va);

		if (n >= 0 && n < bufsize)
			break;

		if (n >= 0)
			bufsize = n + 1;
		else
			bufsize *= 2;

		error = realloc(error, bufsize);
	}
}

void set_error(const char *fmt, ...)
{
	va_list va;

	va_start(va, fmt);
	set_error_va(fmt, va);
	va_end(va);
}

const char *get_error(void)
{
	return error;
}

void *safe_alloc(size_t size)
{
	struct safe_allocation *alloc;

	if (!size)
		return NULL;

	alloc = malloc(size + offsetof(struct safe_allocation, data));
	if (!alloc)
		return NULL;

	alloc->size = size;

	return &alloc->data;
}

void safe_free(void *data)
{
	struct safe_allocation *alloc;

	if (!data)
		return;

	alloc = data - offsetof(struct safe_allocation, data);

	memset(data, 0, alloc->size);

	alloc->size = 0x55aa55aa;
	free(alloc);
}

void *safe_realloc(void *data, size_t size)
{
	void *new_data;

	new_data = safe_alloc(size);

	if (new_data && data) {
		struct safe_allocation *alloc;

		alloc = data - offsetof(struct safe_allocation, data);

		if (size > alloc->size)
			size = alloc->size;

		memcpy(new_data, data, size);
	}

	safe_free(data);
	return new_data;
}

char *safe_strdup(const char *s)
{
	char *s2 = safe_alloc(strlen(s) + 1);

	if (!s2)
		return NULL;

	return strcpy(s2, s);
}