Eneboo - Documentación para desarrolladores
|
00001 #ifndef _LOCALMALLOCHEAP_H_ 00002 #define _LOCALMALLOCHEAP_H_ 00003 00004 #include <dlfcn.h> 00005 00006 #include "ansiwrapper.h" 00007 #include "sizeheap.h" 00008 #include "staticheap.h" 00009 00010 extern "C" { 00011 size_t malloc_usable_size (void *); 00012 00013 typedef void * mallocFunction (size_t); 00014 typedef void freeFunction (void *); 00015 typedef size_t msizeFunction (void *); 00016 00017 typedef void exitFunction (int); 00018 exitFunction * trueExitFunction; 00019 } 00020 00021 namespace HL { 00022 00023 class LocalMallocHeap { 00024 public: 00025 00026 LocalMallocHeap (void) 00027 : freefn (NULL), 00028 msizefn (NULL), 00029 mallocfn (NULL), 00030 firsttime (true) 00031 {} 00032 00033 inline void * malloc (size_t sz) { 00034 if (firsttime) { 00035 00036 firsttime = false; 00037 00038 // We haven't initialized anything yet. 00039 // Initialize all of the malloc shim functions. 00040 00041 freefn = (freeFunction *) dlsym (RTLD_NEXT, "free"); 00042 msizefn = (msizeFunction *) dlsym (RTLD_NEXT, "malloc_usable_size"); 00043 trueExitFunction = (exitFunction *) dlsym (RTLD_NEXT, "exit"); 00044 mallocfn = (mallocFunction *) dlsym (RTLD_NEXT, "malloc"); 00045 00046 if (!(freefn && msizefn && trueExitFunction && mallocfn)) { 00047 fprintf (stderr, "Serious problem!\n"); 00048 abort(); 00049 } 00050 00051 assert (freefn); 00052 assert (msizefn); 00053 assert (trueExitFunction); 00054 assert (mallocfn); 00055 00056 // Go get some memory from malloc! 00057 return (*mallocfn)(sz); 00058 } 00059 00060 // Now, once we have mallocfn resolved, we can use it. 00061 // Otherwise, we're still in dlsym-land, and have to use our local heap. 00062 00063 if (mallocfn) { 00064 return (*mallocfn)(sz); 00065 } else { 00066 void * ptr = localHeap.malloc (sz); 00067 assert (ptr); 00068 return ptr; 00069 } 00070 } 00071 00072 inline void free (void * ptr) { 00073 if (mallocfn) { 00074 if (localHeap.isValid (ptr)) { 00075 // We got a pointer to the temporary allocation buffer. 00076 localHeap.free (ptr); 00077 } else { 00078 (*freefn)(ptr); 00079 } 00080 } 00081 } 00082 00083 inline size_t getSize (void * ptr) { 00084 if (localHeap.isValid (ptr)) { 00085 return localHeap.getSize (ptr); 00086 } else if (mallocfn) { 00087 return (*msizefn)(ptr); 00088 } else { 00089 // This should never happen. 00090 return 0; 00091 } 00092 } 00093 00094 private: 00095 00096 bool firsttime; 00097 00098 // Shim functions below. 00099 00100 freeFunction * freefn; 00101 msizeFunction * msizefn; 00102 mallocFunction * mallocfn; 00103 00106 00107 ANSIWrapper<SizeHeap<StaticHeap<65536> > > localHeap; 00108 00109 }; 00110 00111 } 00112 00113 #endif