| [444] | 1 | /* sbrk.c -- Implementation of the low-level sbrk() routine | 
|---|
 | 2 |  * | 
|---|
 | 3 |  * Copyright (c) 2004 National Semiconductor Corporation | 
|---|
 | 4 |  * | 
|---|
 | 5 |  * The authors hereby grant permission to use, copy, modify, distribute, | 
|---|
 | 6 |  * and license this software and its documentation for any purpose, provided | 
|---|
 | 7 |  * that existing copyright notices are retained in all copies and that this | 
|---|
 | 8 |  * notice is included verbatim in any distributions. No written agreement, | 
|---|
 | 9 |  * license, or royalty fee is required for any of the authorized uses. | 
|---|
 | 10 |  * Modifications to this software may be copyrighted by their authors | 
|---|
 | 11 |  * and need not follow the licensing terms described here, provided that | 
|---|
 | 12 |  * the new terms are clearly indicated on the first page of each file where | 
|---|
 | 13 |  * they apply. | 
|---|
 | 14 |  */ | 
|---|
 | 15 |  | 
|---|
 | 16 | #include <errno.h> | 
|---|
 | 17 | #include <stddef.h> /* where ptrdiff_t is defined */ | 
|---|
 | 18 | #include <stdlib.h> | 
|---|
 | 19 |  | 
|---|
 | 20 | /* Extend heap space by size bytes. | 
|---|
 | 21 |    Return start of new space allocated, or -1 for errors  | 
|---|
 | 22 |    Error cases: | 
|---|
 | 23 |     1. Allocation is not within heap range */ | 
|---|
 | 24 |  | 
|---|
 | 25 | void * sbrk (ptrdiff_t size) | 
|---|
 | 26 | { | 
|---|
 | 27 |   /* | 
|---|
 | 28 |   * The following two memory locations should be defined in the linker script file | 
|---|
 | 29 |   */ | 
|---|
 | 30 |   extern const char _HEAP_START; /* start of heap */ | 
|---|
 | 31 |   extern const char _HEAP_MAX;   /* end of heap (maximum value of heap_ptr) */ | 
|---|
 | 32 |  | 
|---|
 | 33 |   static const char * heap_ptr;  /* pointer to head of heap */ | 
|---|
 | 34 |   const char * old_heap_ptr; | 
|---|
 | 35 |   static unsigned char init_sbrk = 0; | 
|---|
 | 36 |  | 
|---|
 | 37 |   /* heap_ptr is initialized to HEAP_START */ | 
|---|
 | 38 |   if (init_sbrk == 0)  | 
|---|
 | 39 |   { | 
|---|
 | 40 |     heap_ptr = &_HEAP_START; | 
|---|
 | 41 |     init_sbrk = 1; | 
|---|
 | 42 |   } | 
|---|
 | 43 |  | 
|---|
 | 44 |   old_heap_ptr = heap_ptr; | 
|---|
 | 45 |  | 
|---|
 | 46 |   if ((heap_ptr + size) > &_HEAP_MAX) | 
|---|
 | 47 |   {  | 
|---|
 | 48 |     /* top of heap is bigger than _HEAP_MAX */ | 
|---|
 | 49 |     errno = ENOMEM; | 
|---|
 | 50 |     return (void *) -1; | 
|---|
 | 51 |   } | 
|---|
 | 52 |  | 
|---|
 | 53 |   /* success: update heap_ptr and return previous value */ | 
|---|
 | 54 |   heap_ptr += size; | 
|---|
 | 55 |   return (void *)old_heap_ptr; | 
|---|
 | 56 | } | 
|---|