libcm is a C development framework with an emphasis on audio signal processing applications.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmMem.h 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //{
  2. //(
  3. // The cmMem class implements a memory allocation manager interface.
  4. //
  5. //
  6. // Using cmMem allows memory leaks and some instances of memory corruption
  7. // to be be detected. It can also perform memory block alignment.
  8. //
  9. // The cmMm class acts as an interface for implementing functions designed to replace
  10. // malloc() and free(). cmMm does not actually allocate memory itself but rather
  11. // tracks and conditions block of memory provided by other sources. In this sense
  12. // it acts as a backend for a memory allocation manager.
  13. // cmMallocDebug.h gives an example of using cmMm to interface to malloc() and free().
  14. // cmLinkedHeap.h gives an example of using cmMm to link to an alternate heap manager.
  15. // See cmMdTest() and cmLHeapTest() for usage examples of cmMm.
  16. //
  17. // cmMm works as follows:
  18. //
  19. // 1. A client memory manager creates and configures a cmMm object via cmMmInitialize().
  20. // As part of the configuration the client gives callback functions which implement
  21. // actual memory allocation and release. In practice this means the callback probably
  22. // call malloc() or free().
  23. // 2. At some point later when the client needs to allocate a block of memory it calls
  24. // cmMmAllocate() with the size of the requested block. cmMm translates this request
  25. // into a call to the client provided memory allocation callback to get a block of raw
  26. // memory which is slightly larger than the request block.
  27. // 3. Given the raw memory block cmMm conditions it in the following ways and returns
  28. // it to the client.
  29. // * The base of the blocks data area is shifted such that it is has an arbitrary
  30. // address aligned according to the value set by the alignByteCnt parameter to cmMmInitialize().
  31. // Address aligment is sometimes required by routines which make use of the the SIMD
  32. // unit on some CPUs.
  33. // * 'Guard' bytes are prepended and appended to the blocks data area.
  34. // These bytes are set to the known fixed value (0xaa). At some point later cmMm can
  35. // then test for accidental writes just before or just after the legal data area by
  36. // checking the value of these guard bytes.
  37. // * The number of bytes allocated is written just prior to the leading guard bytes.
  38. // This allows the memory manager to track the
  39. // size of the memory and thereby makes reallocations() to smaller or equal data areas
  40. // very fast. This also allows the size of the data area to be known just by having a
  41. // pointer to the data area (see cmMmByteCount()). This basic information is not availabe
  42. // via malloc().
  43. // * A record is added to an internal database to track the allocation code location
  44. // (file name, file line, function name) and the allocation status (active or released).
  45. // * The client may request that a new block of memory be automatically filled with zeros.
  46. // If automatic zeroing is not requested then the block is filled with 0x55 to indicate that
  47. // it is not initialized. This can be useful when attempting to recognize uninitialized
  48. // memory during debugging.
  49. //
  50. // When a client requests that a block of memory is released cmMm does the following:
  51. //
  52. // 1. If deferred release is enabled (kDeferFreeFl) then the block is filled with 0x33
  53. // but the callback to freeFunc() is not actually made. This allows cmMm to track attempted
  54. // writes to freed memory areas. When deferred release is enabled the freeFunc() is not called
  55. // on any blocks until cmMmFinalize(). If the program continually allocates memory over the
  56. // life of the program this may mean that the program will eventually exhaust physical memory.
  57. // 2. If tracking is enabled (kTrackMmFl) then the block pointer is looked up in the internal database.
  58. // If the pointer is not found then a kMissingRecdRC is returned indicating an attempt to release
  59. // a non-allocated block.
  60. // 3. If tracking is enabled (kTrackMmFl) then the block is marked as released in the
  61. // internal tracking database. At the end of the program all blocks should be marked for release
  62. // otherwise they are considered leaks.
  63. //
  64. //
  65. // At any time during the life of the cmMm object the client can request a report of the
  66. // allocated blocks cmMmReport(). This report examines each allocated block for corrupt guard bytes,
  67. // double frees (attempts to release an allocated block that was already released), and
  68. // leaked blocks (active blocks).
  69. //
  70. //)
  71. #ifndef cmMem_h
  72. #define cmMem_h
  73. #ifdef __cplusplus
  74. extern "C" {
  75. #endif
  76. //(
  77. typedef cmHandle_t cmMmH_t; //< cmMm handle type.
  78. typedef cmRC_t cmMmRC_t; //< cmMm result code types.
  79. // cmMm result codes
  80. enum
  81. {
  82. kOkMmRC = cmOkRC,
  83. kObjAllocFailMmRC,
  84. kTrkAllocFailMmRC,
  85. kAllocFailMmRC,
  86. kFreeFailMmRC,
  87. kMissingRecdMmRC,
  88. kGuardCorruptMmRC,
  89. kWriteAfterFreeMmRC,
  90. kLeakDetectedMmRC,
  91. kDblFreeDetectedMmRC,
  92. kParamErrMmRC
  93. };
  94. // All cmMmH_t variables should be initialized with this value prior to calling cmMmInitialize().
  95. extern cmMmH_t cmMmNullHandle;
  96. // Function signature for data allocation routine client provided to cmMmInitialize().
  97. // Return NULL if byteCnt == 0.
  98. typedef void* (*cmAllocMmFunc_t)(void* funcArgPtr, unsigned byteCnt);
  99. // Function signature for data release routine client provided to cmMmInitialize().
  100. // Return true on success and false on failure. Return true if ptr==NULL.
  101. typedef bool (*cmFreeMmFunc_t)( void* funcArgPtr, void* ptr);
  102. // Flags for use with cmMmInitialize()
  103. enum
  104. {
  105. kTrackMmFl = 0x01, //< Track alloc's and free's for use by cmMmReport().
  106. kDeferFreeMmFl = 0x02, //< Defer memory release until cmMmFinalize() (ignored unless kTrackMmFl is set.) Allows checks for 'write after release'.
  107. kFillUninitMmFl = 0x04, //< Fill uninitialized (non-zeroed) memory with a 0x55 upon allocation
  108. kFillFreedMmFl = 0x08 //< Fill freed memory with 0x33. This allow checks for wite-after-free.
  109. };
  110. // Create a new cmMm object.
  111. // If *hp was not initalized by an earlier call to cmMmInitialize() then it should
  112. // be set to cmMmNullHandle prior to calling this function. If *hp is a valid handle
  113. // then it is automatically finalized by an internal call to cmMmFinalize() prior to
  114. // being re-iniitalized.
  115. cmMmRC_t cmMmInitialize(
  116. cmMmH_t* hp, //< Pointer to a client provided cmMmH_t handle to recieve the handle of the new object.
  117. cmAllocMmFunc_t allocFunc, //< The memory allocation function equivalent to malloc().
  118. cmFreeMmFunc_t freeFunc, //< The memory release function equivalent to free().
  119. void* funcArgPtr, //< An application supplied data value sent with call backs to allocFunc() and freeFunc().
  120. unsigned guardByteCnt, //< Count of guardBytes to precede and follow each allocated block.
  121. unsigned alignByteCnt, //< Address alignment to provide for each allocated block.
  122. unsigned flags, //< Configuration flags (See cmXXXMmFl).
  123. cmRpt_t* rptPtr //< Pointer to an error reporting object.
  124. );
  125. // Release a cmMm object created by an earlier call to cmMmInitialize(). Upon successful completion *hp is set to cmMmNullHandle.
  126. cmMmRC_t cmMmFinalize( cmMmH_t* hp );
  127. unsigned cmMmGuardByteCount( cmMmH_t h ); //< Return the count of guard bytes this cmMm object is applying.
  128. unsigned cmMmAlignByteCount( cmMmH_t h ); //< Return the byte alignment this cmMm object is applying.
  129. unsigned cmMmInitializeFlags( cmMmH_t h ); //< Return the configuration flags this cmMm object was initialized with.
  130. // Return true if 'h' is a valid handle for an existing cmMm object.
  131. bool cmMmIsValid( cmMmH_t h );
  132. // flags for use with cmMmAllocate()
  133. enum cmMmAllocFlags_t
  134. {
  135. kZeroMmFl = 0x01, //< Initialize new memory area to zero.
  136. kAlignMmFl = 0x02, //< Align the returned memory according to the alignByteCnt set in cmMmInitialize().
  137. kPreserveMmFl = 0x04 //< Preserve existing memory contents during reallocation (orgDataPtr!=NULL).
  138. };
  139. // Allocate a block of memory.
  140. // Calling this function results in a call to the function named in allocFunc() in cmMmInitialize().
  141. void* cmMmAllocate(
  142. cmMmH_t h, //< Handle for this cmMm object returned from an earlier successful call to cmMmInitialize().
  143. void* orgDataPtr, //< If this is a re-allocation then this pointer should point to the original allocation otherwise it should be NULL.
  144. unsigned newEleCnt, //< Count of elmements in this allocation.
  145. unsigned newEleByteCnt, //< Bytes per element in this allocation. The total memory request is newEleCnt*newEleByteCnt.
  146. enum cmMmAllocFlags_t flags, //< See cmMmAllocFlags_t.
  147. const char* fileName, //< Name of the C file from which the allocation request is being made.
  148. const char* funcName, //< Name of the C function from which the allocation request is being made.
  149. unsigned fileLine //< Line in the C file on which the allocation request is being made.
  150. );
  151. // Free memory pointed to by dataPtr.
  152. // If dataPtr==NULL then the functon does nothing and returns.
  153. // Calling this function results in a call to the function named in freeFunc() in cmMmInitialize().
  154. // This is the release mode memory free routine. See cmMmFreeDebug() for the debug mode memory release routine.
  155. // See \ref debug_mode for more about debug vs. release mode.
  156. cmMmRC_t cmMmFree( cmMmH_t h, void* dataPtr );
  157. // Debug mode version of cmMmFree(). See cmMmFree() for the release mode memory free routine.
  158. // See debug_mode for more about debug vs. release mode.
  159. // This routine is functionally identical to the cmMmFree() but takes the calling
  160. // location information for use in tracking the block of memory.
  161. cmMmRC_t cmMmFreeDebug( cmMmH_t h, void* dataPtr, const char* fileName, const char* funcName, unsigned fileLine );
  162. // This function is identical to cmMmFree() but takes the address of the pointer
  163. // to the block of memory to free. Upon successful completion *dataPtrPtr is
  164. // set to NULL. In general this should be the preferred version of the free routine
  165. // because it helps to eliminate problems of reusing deallocated memory blocks.
  166. // Note that although dataPtrPtr must point to a valid address *dataPtrPtr may be NULL.
  167. // This routine is generally only used in the release compile mode.
  168. // See cmMmFreePtrDebug() for the debug mode version. See \ref debug_mode for more
  169. // about compile vs. release mode.
  170. cmMmRC_t cmMmFreePtr( cmMmH_t h, void** dataPtrPtr );
  171. // Debug compile mode version of cmMmFreePtr().
  172. // This function is functionally identical to cmMmFreePtr() but accepts information
  173. // on the location of the call to aid in debuging.
  174. cmMmRC_t cmMmFreePtrDebug( cmMmH_t h, void* dataPtr, const char* fileName, const char* funcName, unsigned fileLine );
  175. // Return the size of a memory block returned from cmMmAllocate().
  176. unsigned cmMmByteCount( cmMmH_t h, const void* dataPtr );
  177. // Return the unique id associated with an address returned from cmMmAllocate().
  178. unsigned cmMmDebugId( cmMmH_t h, const void* dataPtr);
  179. // Flags for use with cmMmReport().
  180. enum
  181. {
  182. kSuppressSummaryMmFl = 0x01, //< Do not print a memory use summary report.
  183. kIgnoreNormalMmFl = 0x02, //< Do not print information for non-leaked,non-corrupt memory blocks.
  184. kIgnoreLeaksMmFl = 0x04 //< Do not print information for leaked blocks.
  185. };
  186. // Report on the memory tracking data.
  187. // Returns kMmOkRC if no errors were found otherwise returns the error of the
  188. // last anomoly reported.
  189. cmMmRC_t cmMmReport( cmMmH_t h, unsigned flags );
  190. // Analyze the memory assoc'd with a specific tracking record for corruption.
  191. // Returns: kOkMmRC,kGuardCorruptMmRC,kWriteAfterFreeMmRc, or kMissingRecdMmRC.
  192. // This function is only useful if kTrackMmFl was set in cmMmInitialize().
  193. // Write-after-free errors are only detectable if kDeferFreeMmFl was set in cmMmInitialize().
  194. cmMmRC_t cmMmIsGuardCorrupt( cmMmH_t h, unsigned id );
  195. // Check all tracking records by calling cmMmmIsGuardCorrupt() on each record.
  196. cmMmRC_t cmMmCheckAllGuards( cmMmH_t h );
  197. //)
  198. //}
  199. #ifdef __cplusplus
  200. }
  201. #endif
  202. #endif