| 1 | /*
 | 
|---|
| 2 |  * Allocation functions (malloc)
 | 
|---|
| 3 |  *
 | 
|---|
| 4 |  * Copyright (c) 2014, 2015 Gregor Richards
 | 
|---|
| 5 |  *
 | 
|---|
| 6 |  * Permission to use, copy, modify, and/or 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 ANY
 | 
|---|
| 13 |  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 | 
|---|
| 14 |  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 | 
|---|
| 15 |  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 | 
|---|
| 16 |  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 | 
|---|
| 17 |  */
 | 
|---|
| 18 | 
 | 
|---|
| 19 | static void *allocPool(int mustSucceed)
 | 
|---|
| 20 | {
 | 
|---|
| 21 |     static ggc_mutex_t poolLock = GGC_MUTEX_INITIALIZER;
 | 
|---|
| 22 |     static unsigned char *space = NULL, *spaceEnd = NULL;
 | 
|---|
| 23 |     void *ret;
 | 
|---|
| 24 | 
 | 
|---|
| 25 |     /* do we already have some available space? */
 | 
|---|
| 26 |     ggc_mutex_lock_raw(&poolLock);
 | 
|---|
| 27 |     if (!space || space + GGGGC_POOL_BYTES > spaceEnd) {
 | 
|---|
| 28 |         ggc_size_t i;
 | 
|---|
| 29 | 
 | 
|---|
| 30 |         /* since we can't pre-align, align by getting as much as we can manage */
 | 
|---|
| 31 |         for (i = 16; i >= 2; i /= 2) {
 | 
|---|
| 32 |             space = malloc(GGGGC_POOL_BYTES * i);
 | 
|---|
| 33 |             if (space) break;
 | 
|---|
| 34 |         }
 | 
|---|
| 35 |         if (!space) {
 | 
|---|
| 36 |             if (mustSucceed) {
 | 
|---|
| 37 |                 perror("malloc");
 | 
|---|
| 38 |                 abort();
 | 
|---|
| 39 |             }
 | 
|---|
| 40 |             return NULL;
 | 
|---|
| 41 |         }
 | 
|---|
| 42 |         spaceEnd = space + GGGGC_POOL_BYTES * i;
 | 
|---|
| 43 | 
 | 
|---|
| 44 |         /* align it */
 | 
|---|
| 45 |         space = (unsigned char *) GGGGC_POOL_OF(space + GGGGC_POOL_BYTES - 1);
 | 
|---|
| 46 |     }
 | 
|---|
| 47 | 
 | 
|---|
| 48 |     ret = (struct GGGGC_Pool *) space;
 | 
|---|
| 49 |     space += GGGGC_POOL_BYTES;
 | 
|---|
| 50 |     ggc_mutex_unlock(&poolLock);
 | 
|---|
| 51 | 
 | 
|---|
| 52 |     return ret;
 | 
|---|
| 53 | }
 | 
|---|