1 /* alloc.c -- Default memory allocation routines.
2 
3   (c) 1998-2006 (W3C) MIT, ERCIM, Keio University
4   See tidy.h for the copyright notice.
5 
6   CVS Info :
7 
8     $Author: arnaud02 $
9     $Date: 2006/12/29 16:31:07 $
10     $Revision: 1.7 $
11 
12 */
13 
14 #include "tidy.h"
15 #include "forward.h"
16 
17 static TidyMalloc  g_malloc  = NULL;
18 static TidyRealloc g_realloc = NULL;
19 static TidyFree    g_free    = NULL;
20 static TidyPanic   g_panic   = NULL;
21 
tidySetMallocCall(TidyMalloc fmalloc)22 Bool TIDY_CALL tidySetMallocCall( TidyMalloc fmalloc )
23 {
24   g_malloc  = fmalloc;
25   return yes;
26 }
tidySetReallocCall(TidyRealloc frealloc)27 Bool TIDY_CALL tidySetReallocCall( TidyRealloc frealloc )
28 {
29   g_realloc = frealloc;
30   return yes;
31 }
tidySetFreeCall(TidyFree ffree)32 Bool TIDY_CALL tidySetFreeCall( TidyFree ffree )
33 {
34   g_free    = ffree;
35   return yes;
36 }
tidySetPanicCall(TidyPanic fpanic)37 Bool TIDY_CALL tidySetPanicCall( TidyPanic fpanic )
38 {
39   g_panic   = fpanic;
40   return yes;
41 }
42 
defaultPanic(TidyAllocator * ARG_UNUSED (allocator),ctmbstr msg)43 static void TIDY_CALL defaultPanic( TidyAllocator* ARG_UNUSED(allocator), ctmbstr msg )
44 {
45   if ( g_panic )
46     g_panic( msg );
47   else
48   {
49     /* 2 signifies a serious error */
50     fprintf( stderr, "Fatal error: %s\n", msg );
51 #ifdef _DEBUG
52     assert(0);
53 #endif
54     exit(2);
55   }
56 }
57 
defaultAlloc(TidyAllocator * allocator,size_t size)58 static void* TIDY_CALL defaultAlloc( TidyAllocator* allocator, size_t size )
59 {
60     void *p = ( g_malloc ? g_malloc(size) : malloc(size) );
61     if ( !p )
62         defaultPanic( allocator,"Out of memory!");
63     return p;
64 }
65 
defaultRealloc(TidyAllocator * allocator,void * mem,size_t newsize)66 static void* TIDY_CALL defaultRealloc( TidyAllocator* allocator, void* mem, size_t newsize )
67 {
68     void *p;
69     if ( mem == NULL )
70         return defaultAlloc( allocator, newsize );
71 
72     p = ( g_realloc ? g_realloc(mem, newsize) : realloc(mem, newsize) );
73     if (!p)
74         defaultPanic( allocator, "Out of memory!");
75     return p;
76 }
77 
defaultFree(TidyAllocator * ARG_UNUSED (allocator),void * mem)78 static void TIDY_CALL defaultFree( TidyAllocator* ARG_UNUSED(allocator), void* mem )
79 {
80     if ( mem )
81     {
82         if ( g_free )
83             g_free( mem );
84         else
85             free( mem );
86     }
87 }
88 
89 static const TidyAllocatorVtbl defaultVtbl = {
90     defaultAlloc,
91     defaultRealloc,
92     defaultFree,
93     defaultPanic
94 };
95 
96 TidyAllocator TY_(g_default_allocator) = {
97     &defaultVtbl
98 };
99 
100 /*
101  * local variables:
102  * mode: c
103  * indent-tabs-mode: nil
104  * c-basic-offset: 4
105  * eval: (c-set-offset 'substatement-open 0)
106  * end:
107  */
108