xref: /openbsd/usr.bin/dc/mem.c (revision 898184e3)
1 /*	$OpenBSD: mem.c,v 1.5 2009/10/27 23:59:37 deraadt Exp $	*/
2 
3 /*
4  * Copyright (c) 2003, Otto Moerbeek <otto@drijf.net>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <ssl/err.h>
20 
21 #include <err.h>
22 #include <stdlib.h>
23 #include <string.h>
24 
25 #include "extern.h"
26 
27 struct number *
28 new_number(void)
29 {
30 	struct number *n;
31 
32 	n = bmalloc(sizeof(*n));
33 	n->scale = 0;
34 	n->number = BN_new();
35 	if (n->number == NULL)
36 		err(1, NULL);
37 	return n;
38 }
39 
40 void
41 free_number(struct number *n)
42 {
43 	BN_free(n->number);
44 	free(n);
45 }
46 
47 struct number *
48 dup_number(const struct number *a)
49 {
50 	struct number *n;
51 
52 	n = bmalloc(sizeof(*n));
53 	n->scale = a->scale;
54 	n->number = BN_dup(a->number);
55 	bn_checkp(n->number);
56 	return n;
57 }
58 
59 void *
60 bmalloc(size_t sz)
61 {
62 	void *p;
63 
64 	p = malloc(sz);
65 	if (p == NULL)
66 		err(1, NULL);
67 	return p;
68 }
69 
70 void *
71 brealloc(void *p, size_t sz)
72 {
73 	void *q;
74 
75 	q = realloc(p, sz);
76 	if (q == NULL)
77 		err(1, NULL);
78 	return q;
79 }
80 
81 char *
82 bstrdup(const char *p)
83 {
84 	char *q;
85 
86 	q = strdup(p);
87 	if (q == NULL)
88 		err(1, NULL);
89 	return q;
90 }
91 
92 void
93 bn_check(int x)						\
94 {
95 	if (x == 0)
96 		err(1, "big number failure %lx", ERR_get_error());
97 }
98 
99 void
100 bn_checkp(const void *p)						\
101 {
102 	if (p == NULL)
103 		err(1, "allocation failure %lx", ERR_get_error());
104 }
105