Remove /* foo.c */ comments
[openssl.git] / crypto / bn / bn_ctx.c
1 /* Written by Ulf Moeller for the OpenSSL project. */
2 /* ====================================================================
3  * Copyright (c) 1998-2004 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55
56 #if !defined(BN_CTX_DEBUG) && !defined(BN_DEBUG)
57 # ifndef NDEBUG
58 #  define NDEBUG
59 # endif
60 #endif
61
62 #include <assert.h>
63
64 #include "internal/cryptlib.h"
65 #include "bn_lcl.h"
66
67 /*-
68  * TODO list
69  *
70  * 1. Check a bunch of "(words+1)" type hacks in various bignum functions and
71  * check they can be safely removed.
72  *  - Check +1 and other ugliness in BN_from_montgomery()
73  *
74  * 2. Consider allowing a BN_new_ex() that, at least, lets you specify an
75  * appropriate 'block' size that will be honoured by bn_expand_internal() to
76  * prevent piddly little reallocations. OTOH, profiling bignum expansions in
77  * BN_CTX doesn't show this to be a big issue.
78  */
79
80 /* How many bignums are in each "pool item"; */
81 #define BN_CTX_POOL_SIZE        16
82 /* The stack frame info is resizing, set a first-time expansion size; */
83 #define BN_CTX_START_FRAMES     32
84
85 /***********/
86 /* BN_POOL */
87 /***********/
88
89 /* A bundle of bignums that can be linked with other bundles */
90 typedef struct bignum_pool_item {
91     /* The bignum values */
92     BIGNUM vals[BN_CTX_POOL_SIZE];
93     /* Linked-list admin */
94     struct bignum_pool_item *prev, *next;
95 } BN_POOL_ITEM;
96 /* A linked-list of bignums grouped in bundles */
97 typedef struct bignum_pool {
98     /* Linked-list admin */
99     BN_POOL_ITEM *head, *current, *tail;
100     /* Stack depth and allocation size */
101     unsigned used, size;
102 } BN_POOL;
103 static void BN_POOL_init(BN_POOL *);
104 static void BN_POOL_finish(BN_POOL *);
105 static BIGNUM *BN_POOL_get(BN_POOL *, int);
106 static void BN_POOL_release(BN_POOL *, unsigned int);
107
108 /************/
109 /* BN_STACK */
110 /************/
111
112 /* A wrapper to manage the "stack frames" */
113 typedef struct bignum_ctx_stack {
114     /* Array of indexes into the bignum stack */
115     unsigned int *indexes;
116     /* Number of stack frames, and the size of the allocated array */
117     unsigned int depth, size;
118 } BN_STACK;
119 static void BN_STACK_init(BN_STACK *);
120 static void BN_STACK_finish(BN_STACK *);
121 static int BN_STACK_push(BN_STACK *, unsigned int);
122 static unsigned int BN_STACK_pop(BN_STACK *);
123
124 /**********/
125 /* BN_CTX */
126 /**********/
127
128 /* The opaque BN_CTX type */
129 struct bignum_ctx {
130     /* The bignum bundles */
131     BN_POOL pool;
132     /* The "stack frames", if you will */
133     BN_STACK stack;
134     /* The number of bignums currently assigned */
135     unsigned int used;
136     /* Depth of stack overflow */
137     int err_stack;
138     /* Block "gets" until an "end" (compatibility behaviour) */
139     int too_many;
140     /* Flags. */
141     int flags;
142 };
143
144 /* Enable this to find BN_CTX bugs */
145 #ifdef BN_CTX_DEBUG
146 static const char *ctxdbg_cur = NULL;
147 static void ctxdbg(BN_CTX *ctx)
148 {
149     unsigned int bnidx = 0, fpidx = 0;
150     BN_POOL_ITEM *item = ctx->pool.head;
151     BN_STACK *stack = &ctx->stack;
152     fprintf(stderr, "(%16p): ", ctx);
153     while (bnidx < ctx->used) {
154         fprintf(stderr, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
155         if (!(bnidx % BN_CTX_POOL_SIZE))
156             item = item->next;
157     }
158     fprintf(stderr, "\n");
159     bnidx = 0;
160     fprintf(stderr, "          : ");
161     while (fpidx < stack->depth) {
162         while (bnidx++ < stack->indexes[fpidx])
163             fprintf(stderr, "    ");
164         fprintf(stderr, "^^^ ");
165         bnidx++;
166         fpidx++;
167     }
168     fprintf(stderr, "\n");
169 }
170
171 # define CTXDBG_ENTRY(str, ctx)  do { \
172                                 ctxdbg_cur = (str); \
173                                 fprintf(stderr,"Starting %s\n", ctxdbg_cur); \
174                                 ctxdbg(ctx); \
175                                 } while(0)
176 # define CTXDBG_EXIT(ctx)        do { \
177                                 fprintf(stderr,"Ending %s\n", ctxdbg_cur); \
178                                 ctxdbg(ctx); \
179                                 } while(0)
180 # define CTXDBG_RET(ctx,ret)
181 #else
182 # define CTXDBG_ENTRY(str, ctx)
183 # define CTXDBG_EXIT(ctx)
184 # define CTXDBG_RET(ctx,ret)
185 #endif
186
187
188 BN_CTX *BN_CTX_new(void)
189 {
190     BN_CTX *ret;
191
192     if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
193         BNerr(BN_F_BN_CTX_NEW, ERR_R_MALLOC_FAILURE);
194         return NULL;
195     }
196     /* Initialise the structure */
197     BN_POOL_init(&ret->pool);
198     BN_STACK_init(&ret->stack);
199     return ret;
200 }
201
202 BN_CTX *BN_CTX_secure_new(void)
203 {
204     BN_CTX *ret = BN_CTX_new();
205
206     if (ret != NULL)
207         ret->flags = BN_FLG_SECURE;
208     return ret;
209 }
210
211 void BN_CTX_free(BN_CTX *ctx)
212 {
213     if (ctx == NULL)
214         return;
215 #ifdef BN_CTX_DEBUG
216     {
217         BN_POOL_ITEM *pool = ctx->pool.head;
218         fprintf(stderr, "BN_CTX_free, stack-size=%d, pool-bignums=%d\n",
219                 ctx->stack.size, ctx->pool.size);
220         fprintf(stderr, "dmaxs: ");
221         while (pool) {
222             unsigned loop = 0;
223             while (loop < BN_CTX_POOL_SIZE)
224                 fprintf(stderr, "%02x ", pool->vals[loop++].dmax);
225             pool = pool->next;
226         }
227         fprintf(stderr, "\n");
228     }
229 #endif
230     BN_STACK_finish(&ctx->stack);
231     BN_POOL_finish(&ctx->pool);
232     OPENSSL_free(ctx);
233 }
234
235 void BN_CTX_start(BN_CTX *ctx)
236 {
237     CTXDBG_ENTRY("BN_CTX_start", ctx);
238     /* If we're already overflowing ... */
239     if (ctx->err_stack || ctx->too_many)
240         ctx->err_stack++;
241     /* (Try to) get a new frame pointer */
242     else if (!BN_STACK_push(&ctx->stack, ctx->used)) {
243         BNerr(BN_F_BN_CTX_START, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
244         ctx->err_stack++;
245     }
246     CTXDBG_EXIT(ctx);
247 }
248
249 void BN_CTX_end(BN_CTX *ctx)
250 {
251     CTXDBG_ENTRY("BN_CTX_end", ctx);
252     if (ctx->err_stack)
253         ctx->err_stack--;
254     else {
255         unsigned int fp = BN_STACK_pop(&ctx->stack);
256         /* Does this stack frame have anything to release? */
257         if (fp < ctx->used)
258             BN_POOL_release(&ctx->pool, ctx->used - fp);
259         ctx->used = fp;
260         /* Unjam "too_many" in case "get" had failed */
261         ctx->too_many = 0;
262     }
263     CTXDBG_EXIT(ctx);
264 }
265
266 BIGNUM *BN_CTX_get(BN_CTX *ctx)
267 {
268     BIGNUM *ret;
269
270     CTXDBG_ENTRY("BN_CTX_get", ctx);
271     if (ctx->err_stack || ctx->too_many)
272         return NULL;
273     if ((ret = BN_POOL_get(&ctx->pool, ctx->flags)) == NULL) {
274         /*
275          * Setting too_many prevents repeated "get" attempts from cluttering
276          * the error stack.
277          */
278         ctx->too_many = 1;
279         BNerr(BN_F_BN_CTX_GET, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
280         return NULL;
281     }
282     /* OK, make sure the returned bignum is "zero" */
283     BN_zero(ret);
284     ctx->used++;
285     CTXDBG_RET(ctx, ret);
286     return ret;
287 }
288
289 /************/
290 /* BN_STACK */
291 /************/
292
293 static void BN_STACK_init(BN_STACK *st)
294 {
295     st->indexes = NULL;
296     st->depth = st->size = 0;
297 }
298
299 static void BN_STACK_finish(BN_STACK *st)
300 {
301     OPENSSL_free(st->indexes);
302     st->indexes = NULL;
303 }
304
305
306 static int BN_STACK_push(BN_STACK *st, unsigned int idx)
307 {
308     if (st->depth == st->size) {
309         /* Need to expand */
310         unsigned int newsize =
311             st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES;
312         unsigned int *newitems = OPENSSL_malloc(sizeof(*newitems) * newsize);
313         if (newitems == NULL)
314             return 0;
315         if (st->depth)
316             memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth);
317         OPENSSL_free(st->indexes);
318         st->indexes = newitems;
319         st->size = newsize;
320     }
321     st->indexes[(st->depth)++] = idx;
322     return 1;
323 }
324
325 static unsigned int BN_STACK_pop(BN_STACK *st)
326 {
327     return st->indexes[--(st->depth)];
328 }
329
330 /***********/
331 /* BN_POOL */
332 /***********/
333
334 static void BN_POOL_init(BN_POOL *p)
335 {
336     p->head = p->current = p->tail = NULL;
337     p->used = p->size = 0;
338 }
339
340 static void BN_POOL_finish(BN_POOL *p)
341 {
342     unsigned int loop;
343     BIGNUM *bn;
344
345     while (p->head) {
346         for (loop = 0, bn = p->head->vals; loop++ < BN_CTX_POOL_SIZE; bn++)
347             if (bn->d)
348                 BN_clear_free(bn);
349         p->current = p->head->next;
350         OPENSSL_free(p->head);
351         p->head = p->current;
352     }
353 }
354
355
356 static BIGNUM *BN_POOL_get(BN_POOL *p, int flag)
357 {
358     BIGNUM *bn;
359     unsigned int loop;
360
361     /* Full; allocate a new pool item and link it in. */
362     if (p->used == p->size) {
363         BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(*item));
364         if (item == NULL)
365             return NULL;
366         for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) {
367             bn_init(bn);
368             if ((flag & BN_FLG_SECURE) != 0)
369                 BN_set_flags(bn, BN_FLG_SECURE);
370         }
371         item->prev = p->tail;
372         item->next = NULL;
373
374         if (p->head == NULL)
375             p->head = p->current = p->tail = item;
376         else {
377             p->tail->next = item;
378             p->tail = item;
379             p->current = item;
380         }
381         p->size += BN_CTX_POOL_SIZE;
382         p->used++;
383         /* Return the first bignum from the new pool */
384         return item->vals;
385     }
386
387     if (!p->used)
388         p->current = p->head;
389     else if ((p->used % BN_CTX_POOL_SIZE) == 0)
390         p->current = p->current->next;
391     return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE);
392 }
393
394 static void BN_POOL_release(BN_POOL *p, unsigned int num)
395 {
396     unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE;
397
398     p->used -= num;
399     while (num--) {
400         bn_check_top(p->current->vals + offset);
401         if (offset == 0) {
402             offset = BN_CTX_POOL_SIZE - 1;
403             p->current = p->current->prev;
404         } else
405             offset--;
406     }
407 }